<?php
session_start();
include 'php/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$role = $_SESSION['role'];
$isAdmin = ($role == 'admin');
if (!$isAdmin) die("Access denied.");

$dbName = 'shop';
$message = '';

// ----------------- Backup -----------------
if (isset($_POST['backup'])) {

    $tablesResult = $con->query("SHOW TABLES");
    $sqlScript = "";

    while ($row = $tablesResult->fetch_row()) {
        $table = $row[0];

        // CREATE TABLE
        $createTableResult = $con->query("SHOW CREATE TABLE `$table`");
        $createRow = $createTableResult->fetch_assoc();
        $sqlScript .= "\n\n" . $createRow['Create Table'] . ";\n\n";

        // INSERT DATA
        $dataResult = $con->query("SELECT * FROM `$table`");
        while ($dataRow = $dataResult->fetch_assoc()) {
            $columns = array_keys($dataRow);
            $values = array_map(function($val) use ($con){
                return "'" . $con->real_escape_string($val) . "'";
            }, array_values($dataRow));

            $sqlScript .= "INSERT INTO `$table` (`" . implode('`,`',$columns) . "`) VALUES (" . implode(',', $values) . ");\n";
        }
    }

    // Save and download
    $backupFile = $dbName . '.sql';
    file_put_contents($backupFile, $sqlScript);

    header('Content-Description: File Transfer');
    header('Content-Type: application/sql');
    header('Content-Disposition: attachment; filename="'.basename($backupFile).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($backupFile));
    readfile($backupFile);
    unlink($backupFile);
    exit;
}

// ----------------- Restore -----------------
if (isset($_POST['restore'])) {
    if (isset($_FILES['sql_file']) && $_FILES['sql_file']['error'] === 0) {
        $sql = file_get_contents($_FILES['sql_file']['tmp_name']);
        if ($sql) {
            $queries = explode(";\n", $sql);
            foreach ($queries as $query) {
                $query = trim($query);
                if (!empty($query)) $con->query($query);
            }
            $message = "Database restored successfully!";
        } else {
            $message = "Uploaded file is empty.";
        }
    } else {
        $message = "Please upload a valid SQL file.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Backup & Restore Database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="container mt-4">
    <h2>Backup & Restore Database</h2>

    <?php if($message): ?>
        <div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <div class="card mb-3">
        <div class="card-header bg-success text-white">Backup Database</div>
        <div class="card-body">
            <form method="post">
                <button type="submit" name="backup" class="btn btn-success">Download shop.sql</button>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-warning text-dark">Restore Database</div>
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="sql_file">Upload SQL File:</label>
                    <input type="file" name="sql_file" id="sql_file" class="form-control" required>
                </div>
                <button type="submit" name="restore" class="btn btn-warning">Restore Database</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>
