<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

$host = getenv('MYSQL_HOST') ?: '';
$user = getenv('MYSQL_USER') ?: 'root';
$pass = getenv('MYSQL_PASSWORD') ?: '';
$db   = 'testfill';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db`");
    $pdo->exec("USE `$db`");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS filler (
            id INT AUTO_INCREMENT PRIMARY KEY,
            data LONGBLOB
        )
    ");
} catch (\PDOException $e) {
    die("❌ DB connection failed: " . $e->getMessage());
}

function getDbStats($pdo, $db) {
    $stmt = $pdo->query("
        SELECT 
            ROUND(SUM(data_length + index_length) / 1024 / 1024 / 1024, 2) AS total_size_gb,
            SUM(table_rows) AS total_rows
        FROM information_schema.tables
        WHERE table_schema = '$db'
    ");
    $result = $stmt->fetch();
    $sizeGb = $result['total_size_gb'] ?? '0';
    $rows = $result['total_rows'] ?? '0';
    $avgMb = ($rows > 0) ? round(($sizeGb * 1024) / $rows, 2) : 0;
    return [$sizeGb, $rows, $avgMb];
}

list($dbSize, $rowCount, $avgRowMb) = getDbStats($pdo, $db);

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fill'])) {
    $iterations = 1024;
    $data = str_repeat(random_bytes(1024), 1024); // 1MB
    $stmt = $pdo->prepare("INSERT INTO filler (data) VALUES (:data)");

    for ($i = 0; $i < $iterations; $i++) {
        $stmt->execute([':data' => $data]);
    }

    list($dbSize, $rowCount, $avgRowMb) = getDbStats($pdo, $db);

    $message = "<p style='color: green;'>✅ 1GB inserted into MariaDB successfully.</p>";
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>MariaDB Filler</title>
</head>
<body>
    <h1>MariaDB Storage Filler</h1>
    <?= $message ?>
    <ul>
        <li><strong>📦 MariaDB Used Size:</strong> <?= $dbSize ?> GB</li>
        <li><strong>📊 Total Rows:</strong> <?= $rowCount ?></li>
        <li><strong>📐 Average Row Size:</strong> <?= $avgRowMb ?> MB</li>
    </ul>

    <form method="post">
        <button name="fill" value="1" type="submit">Insert 1GB into DB</button>
    </form>
</body>
</html>

