<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

if (isset($_POST['backup_database'])) {
    $db_host = 'localhost';
    $db_user = 'root';
    $db_password = ''; // No password
    $db_name = 'prodb';

    // Set backup file name (timestamped)
    $backup_file = 'backups/prodb_backup_' . date('Y-m-d_H-i-s') . '.sql';

    // Ensure the backups directory exists
    if (!is_dir('backups')) {
        mkdir('backups', 0777, true);
    }

    // Command to dump the database
    //$command = "mysqldump --host=$db_host --user=$db_user --password=$db_password $db_name > $backup_file";
    $command = '"C:\xampp\mysql\bin\mysqldump.exe" --host=localhost --user=root --password= prodb > ' . $backup_file;

    // Execute the backup command
    $output = null;
    $return_var = null;
    exec($command, $output, $return_var);

    if ($return_var === 0) {
        $message = "<div class='alert alert-success'>Backup successful! <a href='$backup_file' class='alert-link' download>Download Backup</a></div>";
    } else {
        $message = "<div class='alert alert-danger'>Backup failed! Please check server permissions.</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Database Backup</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2 class="mb-4">Backup MySQL Database</h2>

        <?php if (isset($message)) echo $message; ?>

        <form action="" method="POST" class="bg-light p-4 rounded shadow-sm">
            <p>Click the button below to generate a backup of the database.</p>
            <button type="submit" name="backup_database" class="btn btn-primary">Create Backup</button>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
