<?php
// ===== Database connection settings =====
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_port = 3306;
// ========================================

// Directory where backups will be saved
$backup_dir = __DIR__ . '/backups';
if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Config file to remember settings
$config_file = __DIR__ . '/backup_config.json';
$config = [
    'mysqldump_path' => 'c:\\xampp\\mysql\\bin\\',  // default
];
if (file_exists($config_file)) {
    $saved = json_decode(file_get_contents($config_file), true);
    if (is_array($saved)) {
        $config = array_merge($config, $saved);
    }
}

// -------- Handle "Save Settings" --------
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_settings') {
    $newPath = trim($_POST['mysqldump_path'] ?? '');
    if ($newPath !== '') {
        // Ensure trailing slash
        if (!preg_match('#[\\\\/]$#', $newPath)) {
            $newPath .= DIRECTORY_SEPARATOR;
        }
        $config['mysqldump_path'] = $newPath;
        file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
        $message = "Settings saved.";
        $messageType = 'success';
    } else {
        $message = "Path cannot be empty.";
        $messageType = 'error';
    }
}

// Build full mysqldump executable path
$mysqldump_exe = rtrim($config['mysqldump_path'], '\\/') . DIRECTORY_SEPARATOR . 'mysqldump.exe';

// -------- Handle Backup Action --------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($_POST['action'] ?? '', ['backup_one', 'backup_all'])) {
    $action = $_POST['action'];
    $date   = date('Ymd');
    $mysqli = new mysqli($db_host, $db_user, $db_pass, '', $db_port);

    if ($mysqli->connect_errno) {
        $message = "Connection failed: " . $mysqli->connect_error;
        $messageType = 'error';
    } else {
        $targets = [];
        if ($action === 'backup_all') {
            $res = $mysqli->query("SHOW DATABASES");
            while ($row = $res->fetch_row()) {
                $db = $row[0];
                if (in_array($db, ['information_schema', 'performance_schema', 'mysql', 'sys', 'test'])) {
                    continue;
                }
                $targets[] = $db;
            }
        } elseif ($action === 'backup_one' && !empty($_POST['db_name'])) {
            $targets[] = $_POST['db_name'];
        }

        $successCount = 0;
        $errors = [];

        foreach ($targets as $db) {
            $filename = $db . '_' . $date . '.sql';
            $filepath = $backup_dir . DIRECTORY_SEPARATOR . $filename;

            $cmd = sprintf(
                '%s --host=%s --port=%d --user=%s %s --result-file=%s %s 2>&1',
                escapeshellarg($mysqldump_exe),
                escapeshellarg($db_host),
                (int)$db_port,
                escapeshellarg($db_user),
                $db_pass !== '' ? '--password=' . escapeshellarg($db_pass) : '',
                escapeshellarg($filepath),
                escapeshellarg($db)
            );

            $output = [];
            $returnCode = 0;
            exec($cmd, $output, $returnCode);

            if ($returnCode === 0 && file_exists($filepath) && filesize($filepath) > 0) {
                $successCount++;
            } else {
                $errors[] = $db . ' [exit=' . $returnCode . '] ' . implode(' ', $output);
            }
        }

        if ($successCount > 0) {
            $message = "Backup completed: $successCount database(s) saved to <code>/backups</code> ($date).";
            $messageType = 'success';
        }
        if (!empty($errors)) {
            $message .= " Errors: " . htmlspecialchars(implode('; ', $errors));
            $messageType = 'error';
        }

        $mysqli->close();
    }
}

// -------- Fetch Database List --------
$mysqli = new mysqli($db_host, $db_user, $db_pass, '', $db_port);
if ($mysqli->connect_errno) {
    die("Connection failed: " . $mysqli->connect_error);
}
$result = $mysqli->query("SHOW DATABASES");
$databases = [];
while ($row = $result->fetch_row()) {
    $db = $row[0];
    if (in_array($db, ['information_schema', 'performance_schema', 'mysql', 'sys', 'test'])) {
        continue;
    }
    $databases[] = $db;
}
$mysqli->close();

// Check if mysqldump exists
$mysqldump_exists = file_exists($mysqldump_exe);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MySQL Databases & Backups</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 900px; margin: 40px auto; padding: 0 20px; color: #333; }
        h1 { margin-bottom: 5px; }
        h2 { margin-top: 35px; border-bottom: 2px solid #eee; padding-bottom: 6px; }
        .count { color: #666; font-size: 14px; margin-top: 0; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 10px 12px; border-bottom: 1px solid #ddd; text-align: left; }
        th { background: #f5f5f5; }
        tr:hover { background: #f9f9f9; }
        .btn {
            display: inline-block; padding: 6px 14px; border: none; border-radius: 5px;
            background: #0078d4; color: #fff; cursor: pointer; font-size: 13px;
            text-decoration: none; transition: background .15s;
        }
        .btn:hover { background: #005fa3; }
        .btn-save { background: #6b7280; }
        .btn-save:hover { background: #4b5563; }
        .btn-all { background: #16a34a; padding: 10px 20px; font-size: 15px; }
        .btn-all:hover { background: #12813c; }
        .msg { padding: 12px 16px; border-radius: 6px; margin: 16px 0; }
        .msg.success { background: #e6f7e6; border: 1px solid #b7e0b7; color: #1a6b1a; }
        .msg.error { background: #fde8e8; border: 1px solid #f5b7b7; color: #9b1c1c; }
        .date-badge { color: #666; font-size: 13px; }
        code { background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 13px; }
        .settings-box {
            background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;
            padding: 18px 20px; margin-top: 20px;
        }
        .settings-box label { display: block; font-weight: 600; margin-bottom: 6px; font-size: 14px; }
        .settings-box input[type=text] {
            width: 100%; padding: 9px 12px; border: 1px solid #cbd5e1; border-radius: 5px;
            font-family: monospace; font-size: 14px; box-sizing: border-box;
        }
        .settings-box .row { display: flex; gap: 10px; align-items: center; margin-top: 10px; }
        .status-ok  { color: #16a34a; font-weight: 600; font-size: 13px; }
        .status-bad { color: #dc2626; font-weight: 600; font-size: 13px; }
        .hint { color: #64748b; font-size: 12px; margin-top: 6px; }
    </style>
</head>
<body>
    <h1>MySQL Databases</h1>
    <p class="count">
        <?= count($databases) ?> database(s) on <code><?= htmlspecialchars($db_host) ?></code>
        &nbsp;|&nbsp; Today: <code><?= date('Ymd') ?></code>
    </p>

    <?php if ($message): ?>
        <div class="msg <?= $messageType ?>"><?= $message ?></div>
    <?php endif; ?>

    <!-- ========== SETTINGS ========== -->
    <div class="settings-box">
        <form method="post">
            <input type="hidden" name="action" value="save_settings">
            <label for="mysqldump_path">mysqldump folder path</label>
            <div class="row">
                <input
                    type="text"
                    id="mysqldump_path"
                    name="mysqldump_path"
                    value="<?= htmlspecialchars($config['mysqldump_path']) ?>"
                    placeholder="e:\xampp\mysql\bin\"
                >
                <button type="submit" class="btn btn-save">Save</button>
            </div>
            <div class="hint">
                Full executable used:
                <code><?= htmlspecialchars($mysqldump_exe) ?></code>
                &nbsp;
                <?php if ($mysqldump_exists): ?>
                    <span class="status-ok">✓ found</span>
                <?php else: ?>
                    <span class="status-bad">✗ not found</span>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- ========== DATABASE LIST ========== -->
    <h2>Databases</h2>
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Database Name</th>
                <th>Backup File</th>
                <th style="text-align:right;">Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($databases as $i => $db): ?>
                <tr>
                    <td><?= $i + 1 ?></td>
                    <td><strong><?= htmlspecialchars($db) ?></strong></td>
                    <td class="date-badge"><code><?= htmlspecialchars($db) ?>_<?= date('Ymd') ?>.sql</code></td>
                    <td style="text-align:right;">
                        <form method="post" style="margin:0;">
                            <input type="hidden" name="action" value="backup_one">
                            <input type="hidden" name="db_name" value="<?= htmlspecialchars($db) ?>">
                            <button type="submit" class="btn">💾 Backup</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div style="margin-top:25px; text-align:center;">
        <form method="post" onsubmit="return confirm('Backup ALL databases now?');">
            <input type="hidden" name="action" value="backup_all">
            <button type="submit" class="btn btn-all">💾 Backup All Databases</button>
        </form>
    </div>

    <p style="margin-top:30px; color:#888; font-size:13px;">
        Backups are saved to <code>/backups</code> as <code>{db_name}_<?= date('Ymd') ?>.sql</code>
    </p>
</body>
</html>