<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db_host = $_POST['db_host'];
    $db_name = $_POST['db_name'];
    $db_user = $_POST['db_user'];
    $db_pass = $_POST['db_pass'];
    $license_key = trim($_POST['license_key']);
    $admin_username = trim($_POST['admin_username']);
    $admin_raw_password = trim($_POST['admin_password']);

    try {
        $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);
    } catch (PDOException $e) {
        die("❌ Database connection failed: " . $e->getMessage());
    }

    // ✅ Update db.php credentials
    $template = file_get_contents('db.php');
    $updated = str_replace(
        ['YOUR_DB_HOST', 'YOUR_DB_NAME', 'YOUR_DB_USER', 'YOUR_DB_PASS'],
        [$db_host, $db_name, $db_user, $db_pass],
        $template
    );
    file_put_contents('db.php', $updated);

    // ✅ Import SQL first
    $sql = file_get_contents('install.sql');
    try {
        $pdo->exec($sql);
    } catch (PDOException $e) {
        die("❌ Failed to import database: " . $e->getMessage());
    }

    // ✅ Update license key
    $stmt = $pdo->prepare("UPDATE branding SET license_key = ? WHERE id = 1");
    $stmt->execute([$license_key]);

    // ✅ Insert new admin user (after table creation)
    $hashedPassword = password_hash(trim($_POST['admin_password']), PASSWORD_DEFAULT);

// ✅ Upsert admin user — insert or update password if username exists
$stmt = $pdo->prepare("
    INSERT INTO admins (username, password)
    VALUES (?, ?)
    ON DUPLICATE KEY UPDATE password = VALUES(password)
");
$stmt->execute([$admin_username, $hashedPassword]);


    // ✅ Mark install complete
    file_put_contents('.installed', 'complete');

    // ✅ Redirect to login
    header("Location: login.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Install Your System</title>
    <meta charset="UTF-8">
    <style>
        body { font-family: sans-serif; max-width: 500px; margin: 40px auto; }
        label { display: block; margin-top: 15px; }
        input { width: 100%; padding: 8px; margin-top: 5px; }
        button { margin-top: 20px; padding: 10px 20px; font-size: 16px; }

        .loading-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.8);
            color: white;
            font-size: 1.6rem;
            text-align: center;
            padding-top: 20%;
            z-index: 9999;
        }

        .spinner {
            margin: 20px auto;
            border: 6px solid #ccc;
            border-top: 6px solid white;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <h1>🚀 System Setup</h1>
    <form method="post">
        <label>MySQL Host</label>
        <input type="text" name="db_host" required placeholder="localhost">

        <label>Database Name</label>
        <input type="text" name="db_name" required>

        <label>Database Username</label>
        <input type="text" name="db_user" required>

        <label>Database Password</label>
        <input type="password" name="db_pass" required>

        <label>License Key</label>
        <input type="text" name="license_key" required>

        <label>Admin Username</label>
        <input type="text" name="admin_username" required>

        <label>Admin Password</label>
        <input type="password" name="admin_password" required>

        <button type="submit">✅ Complete Installation</button>
    </form>

    <div class="loading-overlay" id="loading">
        <div>⏳ Installing your system…<br>Please wait a moment</div>
        <div class="spinner"></div>
    </div>

    <script>
        document.querySelector('form').addEventListener('submit', function () {
            document.getElementById('loading').style.display = 'block';
        });
    </script>
</body>
</html>
