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

$importMsg = '';
if (isset($_POST['import_sql']) && isset($_FILES['sql_file'])) {
    $conn = new mysqli("localhost", "root", "", "school_checkin");
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sqlFile = $_FILES['sql_file']['tmp_name'];
    $sqlContent = file_get_contents($sqlFile);

    // Split into individual queries
    $queries = array_filter(array_map('trim', explode(";", $sqlContent)));
    $success = true;
    $conn->set_charset("utf8");

    foreach ($queries as $query) {
        if ($query === '' || strpos($query, '--') === 0 || strpos($query, '/*') === 0) continue;
        if (!$conn->query($query)) {
            $success = false;
            $importMsg = "Error on query: <br><code>$query</code><br><b>" . $conn->error . "</b>";
            break;
        }
    }

    if ($success && $importMsg === '') {
        $importMsg = "✅ Import successful!";
    } elseif ($importMsg === '') {
        $importMsg = "❌ Import failed! Please check your SQL file formatting.";
    }
    $conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Import SQL Database Backup</title>
    <style>
        body { font-family: Arial, sans-serif; background: #181818; color: #fff; }
        .container { background: #242424; margin: 40px auto; padding: 30px; border-radius: 10px; max-width: 410px; }
        input[type=file] { margin-bottom: 10px; }
        button { background: #007bff; color: #fff; border: none; padding: 10px 18px; border-radius: 5px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .msg { margin-top: 18px; font-weight: bold; }
        .msg code { background: #222; color: #f88; padding: 2px 6px; border-radius: 4px;}
    </style>
</head>
<body>
    <div class="container">
        <h2>Import SQL Backup</h2>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="sql_file" accept=".sql" required><br>
            <button type="submit" name="import_sql">Import SQL</button>
        </form>
        <?php if ($importMsg): ?>
            <div class="msg"><?= $importMsg ?></div>
        <?php endif; ?>
        <br>
        <a href="dashboard.php" style="color:#aaa;">← Back to Dashboard</a>
    </div>
</body>
</html>