<?php
/**
 * ONE-TIME INSTALL SCRIPT
 * ------------------------------------------------------------
 * Run this once from the browser (e.g. http://localhost/rms/install.php)
 * or via CLI (php install.php) to create the database tables,
 * load seed data, and set your admin password securely.
 *
 * DELETE THIS FILE after running it successfully.
 * ------------------------------------------------------------
 */

define('ROOT_PATH', __DIR__);
require_once ROOT_PATH . '/config/config.php';

$host = DB_HOST; $user = DB_USER; $pass = DB_PASS; $dbName = DB_NAME;

try {
    // Connect without selecting DB first, in case it doesn't exist yet
    $pdo = new PDO("mysql:host={$host};charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $pdo->exec("USE `{$dbName}`");

    echo "<pre>";
    echo "✔ Database '{$dbName}' ready.\n";

    // --- Run schema.sql ---
    $schema = file_get_contents(ROOT_PATH . '/database/schema.sql');
    foreach (array_filter(array_map('trim', explode(';', $schema))) as $stmt) {
        if ($stmt !== '' && stripos($stmt, 'SET FOREIGN_KEY_CHECKS') === false) {
            $pdo->exec($stmt);
        } elseif (stripos($stmt, 'SET FOREIGN_KEY_CHECKS') !== false) {
            $pdo->exec($stmt);
        }
    }
    echo "✔ Tables created.\n";

    // --- Run seed.sql ---
    $seed = file_get_contents(ROOT_PATH . '/database/seed.sql');
    foreach (array_filter(array_map('trim', explode(';', $seed))) as $stmt) {
        if ($stmt !== '') {
            $pdo->exec($stmt);
        }
    }
    echo "✔ Seed data loaded (roles, permissions, sample menu, settings).\n";

    // --- Set a real admin password ---
    $adminUsername = 'admin';
    $adminPassword = 'Admin@123'; // CHANGE THIS after first login via Users page
    $hash = password_hash($adminPassword, PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("UPDATE users SET password_hash = :hash WHERE username = :u");
    $stmt->execute(['hash' => $hash, 'u' => $adminUsername]);
    echo "✔ Admin password set.\n\n";

    echo "=========================================\n";
    echo " Setup complete!\n";
    echo " Login at: " . BASE_URL . "/login\n";
    echo " Username: {$adminUsername}\n";
    echo " Password: {$adminPassword}\n";
    echo "=========================================\n";
    echo "\n⚠ IMPORTANT: Delete install.php now, and change the admin password after logging in.\n";
    echo "</pre>";
} catch (PDOException $e) {
    echo "<pre>❌ Install failed: " . htmlspecialchars($e->getMessage()) . "</pre>";
}
