<?php
/**
 * ScholarExam Install Wizard
 * Drop this in your cPanel web root, navigate to /install/ and follow the steps.
 */

define('CONFIG_FILE', dirname(__DIR__) . '/config.json');
define('LOCK_FILE',   dirname(__DIR__) . '/install/.installed');

// If already installed, show message
if (file_exists(LOCK_FILE)) {
    die('<!DOCTYPE html><html><head><title>Already Installed</title>
    <style>body{font-family:sans-serif;max-width:600px;margin:80px auto;text-align:center;padding:20px}
    .ok{background:#f0fdf4;border:2px solid #16a34a;border-radius:12px;padding:30px}
    h2{color:#15803d}a{color:#2563eb}</style></head>
    <body><div class="ok"><h2>ScholarExam Already Installed</h2>
    <p>The system has been configured. <a href="/">Go to the application</a></p>
    <p style="font-size:12px;color:#666">To reinstall, delete the <code>install/.installed</code> file.</p>
    </div></body></html>');
}

$step   = isset($_POST['step'])   ? (int)$_POST['step']   : 1;
$errors = [];
$success = false;
$dbInfo = [];

// ── Step 2: Test connection + create tables ─────────────────────────────────
if ($step === 2 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $host   = trim($_POST['db_host']   ?? 'localhost');
    $port   = (int)($_POST['db_port']  ?? 3306);
    $user   = trim($_POST['db_user']   ?? '');
    $pass   = $_POST['db_pass']        ?? '';
    $dbname = trim($_POST['db_name']   ?? '');

    if (!$host || !$user || !$dbname) {
        $errors[] = 'Host, username and database name are required.';
        $step = 1;
    } else {
        try {
            $dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4";
            $pdo = new PDO($dsn, $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);

            // Create tables
            $tables = file_get_contents(__DIR__ . '/schema.sql');
            if ($tables) {
                foreach (array_filter(explode(';', $tables)) as $stmt) {
                    $trimmed = trim($stmt);
                    if ($trimmed) $pdo->exec($trimmed);
                }
            } else {
                // Inline schema (fallback)
                createTables($pdo);
            }

            // Seed defaults
            seedDefaults($pdo, $pass);

            // Write config
            $config = ['host' => $host, 'port' => $port, 'user' => $user, 'password' => $pass, 'database' => $dbname];
            file_put_contents(CONFIG_FILE, json_encode($config, JSON_PRETTY_PRINT));

            // Write lock
            file_put_contents(LOCK_FILE, date('c'));

            $success = true;
            $step    = 3;
        } catch (PDOException $e) {
            $errors[] = 'Database error: ' . $e->getMessage();
            $step = 1;
            $dbInfo = compact('host','port','user','dbname');
        }
    }
}

// ── Inline schema creation ───────────────────────────────────────────────────
function createTables(PDO $pdo): void {
    $stmts = [
        "CREATE TABLE IF NOT EXISTS `credentials` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `role` VARCHAR(50) NOT NULL UNIQUE,
          `password_hash` TEXT NOT NULL,
          `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `school_settings` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `name` VARCHAR(255) NOT NULL DEFAULT 'ScholarExam Academy',
          `motto` TEXT NOT NULL DEFAULT 'Knowledge. Discipline. Excellence.',
          `address` TEXT NOT NULL DEFAULT '12 Education Avenue, Lagos',
          `phone` VARCHAR(50) NOT NULL DEFAULT '+234 800 000 0000',
          `email` VARCHAR(100) NOT NULL DEFAULT 'info@scholarexam.school',
          `logo_url` TEXT,
          `primary_color` VARCHAR(20) DEFAULT '#3b82f6',
          `currency` VARCHAR(10) NOT NULL DEFAULT 'NGN',
          `grading_scale` TEXT NOT NULL DEFAULT 'A:80-100,B:70-79,C:60-69,D:50-59,E:40-49,F:0-39',
          `term_name` VARCHAR(100) NOT NULL DEFAULT 'First Term',
          `session_name` VARCHAR(100) NOT NULL DEFAULT '2025/2026',
          `principal_name` VARCHAR(100) DEFAULT 'Dr. A. Okonkwo',
          `next_term_begins` VARCHAR(50),
          `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `system_status` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `locked` TINYINT(1) NOT NULL DEFAULT 0,
          `maintenance_message` TEXT NOT NULL DEFAULT 'System is undergoing maintenance.',
          `version` VARCHAR(20) NOT NULL DEFAULT '1.0.0',
          `last_updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `classes` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `name` VARCHAR(100) NOT NULL,
          `level` VARCHAR(100) NOT NULL,
          `teacher` VARCHAR(100) NOT NULL,
          `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `subjects` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `name` VARCHAR(100) NOT NULL,
          `code` VARCHAR(20) NOT NULL,
          `class_id` INT NOT NULL,
          `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `students` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `student_id` VARCHAR(50) NOT NULL UNIQUE,
          `first_name` VARCHAR(100) NOT NULL,
          `last_name` VARCHAR(100) NOT NULL,
          `class_id` INT NOT NULL,
          `gender` VARCHAR(20) NOT NULL,
          `date_of_birth` VARCHAR(20),
          `guardian_name` VARCHAR(100),
          `guardian_phone` VARCHAR(50),
          `photo_url` TEXT,
          `address` TEXT,
          `admission_date` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `questions` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `subject_id` INT NOT NULL,
          `type` VARCHAR(30) NOT NULL,
          `prompt` TEXT NOT NULL,
          `options` JSON,
          `correct_answer` TEXT,
          `marks` INT NOT NULL DEFAULT 1,
          `difficulty` VARCHAR(20),
          `explanation` TEXT,
          `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `exams` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `title` VARCHAR(255) NOT NULL,
          `instructions` TEXT,
          `subject_id` INT NOT NULL,
          `class_id` INT NOT NULL,
          `duration_minutes` INT NOT NULL DEFAULT 60,
          `total_marks` INT NOT NULL DEFAULT 100,
          `pass_mark` INT,
          `status` VARCHAR(20) NOT NULL DEFAULT 'draft',
          `scheduled_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
          `venue` VARCHAR(100),
          `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `exam_questions` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `exam_id` INT NOT NULL,
          `question_id` INT NOT NULL,
          `position` INT NOT NULL DEFAULT 0
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `exam_sessions` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `exam_id` INT NOT NULL,
          `student_id` INT NOT NULL,
          `started_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
          `submitted_at` DATETIME,
          `status` VARCHAR(20) NOT NULL DEFAULT 'in_progress'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `exam_answers` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `session_id` INT NOT NULL,
          `question_id` INT NOT NULL,
          `answer` TEXT NOT NULL DEFAULT '',
          `is_correct` TINYINT(1),
          `awarded_marks` INT NOT NULL DEFAULT 0
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `exam_results` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `exam_id` INT NOT NULL,
          `student_id` INT NOT NULL,
          `session_id` INT,
          `score` INT NOT NULL DEFAULT 0,
          `total_marks` INT NOT NULL DEFAULT 0,
          `percentage` FLOAT NOT NULL DEFAULT 0,
          `grade` VARCHAR(5) NOT NULL DEFAULT 'F',
          `remark` TEXT,
          `submitted_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `invoices` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `invoice_number` VARCHAR(50) NOT NULL UNIQUE,
          `student_id` INT NOT NULL,
          `term` VARCHAR(100) NOT NULL,
          `items` JSON NOT NULL,
          `total` FLOAT NOT NULL DEFAULT 0,
          `amount_paid` FLOAT NOT NULL DEFAULT 0,
          `status` VARCHAR(20) NOT NULL DEFAULT 'pending',
          `issued_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
          `due_date` VARCHAR(20),
          `notes` TEXT
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `timetable_entries` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `class_id` INT NOT NULL,
          `subject_id` INT NOT NULL,
          `date` VARCHAR(20) NOT NULL,
          `start_time` VARCHAR(10) NOT NULL,
          `end_time` VARCHAR(10) NOT NULL,
          `venue` VARCHAR(100) NOT NULL,
          `teacher` VARCHAR(100) NOT NULL,
          `term` VARCHAR(100) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `activity_log` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `type` VARCHAR(50) NOT NULL,
          `message` TEXT NOT NULL,
          `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `messages` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `sender_role` VARCHAR(50) NOT NULL,
          `sender_name` VARCHAR(100) NOT NULL,
          `audience` VARCHAR(50) NOT NULL,
          `target_class_id` INT,
          `target_student_id` INT,
          `subject` VARCHAR(255) NOT NULL,
          `body` TEXT NOT NULL,
          `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

        "CREATE TABLE IF NOT EXISTS `message_reads` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `message_id` INT NOT NULL,
          `reader_role` VARCHAR(50) NOT NULL,
          `reader_key` VARCHAR(100) NOT NULL,
          `read_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
          UNIQUE KEY `uniq_read` (`message_id`,`reader_role`,`reader_key`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
    ];
    foreach ($stmts as $stmt) $pdo->exec($stmt);
}

function hashPassword(string $pwd): string {
    return hash('sha256', $pwd);
}

function seedDefaults(PDO $pdo, string $dbPass): void {
    // Credentials
    $check = $pdo->query("SELECT COUNT(*) FROM credentials")->fetchColumn();
    if (!$check) {
        $pdo->prepare("INSERT INTO credentials (role, password_hash) VALUES (?, ?)")->execute(['admin',     hashPassword('admin123')]);
        $pdo->prepare("INSERT INTO credentials (role, password_hash) VALUES (?, ?)")->execute(['developer', hashPassword('developer123')]);
    }
    // School settings
    if (!$pdo->query("SELECT COUNT(*) FROM school_settings")->fetchColumn()) {
        $pdo->exec("INSERT INTO school_settings (name) VALUES ('ScholarExam Academy')");
    }
    // System status
    if (!$pdo->query("SELECT COUNT(*) FROM system_status")->fetchColumn()) {
        $pdo->exec("INSERT INTO system_status (locked) VALUES (0)");
    }
    // Activity log
    if (!$pdo->query("SELECT COUNT(*) FROM activity_log")->fetchColumn()) {
        $pdo->exec("INSERT INTO activity_log (type, message) VALUES ('system', 'ScholarExam installed successfully.')");
    }
}

// ── Render ───────────────────────────────────────────────────────────────────
$defaultHost = 'localhost';
$defaultUser = 'rbnbtcii_projec5';
$defaultDb   = 'rbnbtcii_project5';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ScholarExam Install Wizard</title>
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:linear-gradient(135deg,#1e3a5f 0%,#0f2340 100%);min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
  .card{background:#fff;border-radius:16px;box-shadow:0 25px 60px rgba(0,0,0,.35);max-width:560px;width:100%;overflow:hidden}
  .header{background:linear-gradient(135deg,#2563eb,#1d4ed8);padding:32px;text-align:center;color:#fff}
  .header h1{font-size:24px;font-weight:800;margin-bottom:4px}
  .header p{opacity:.85;font-size:14px}
  .logo{width:52px;height:52px;background:rgba(255,255,255,.15);border-radius:12px;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;font-size:26px}
  .body{padding:32px}
  .steps{display:flex;margin-bottom:28px;gap:0}
  .step{flex:1;text-align:center;padding:10px 0;font-size:12px;font-weight:600;position:relative}
  .step.done{color:#16a34a}
  .step.active{color:#2563eb}
  .step.pending{color:#9ca3af}
  .step::after{content:'';position:absolute;bottom:0;left:50%;right:-50%;height:2px;background:#e5e7eb}
  .step.done::after{background:#16a34a}
  .step.active::after{background:#2563eb}
  .step:last-child::after{display:none}
  .field{margin-bottom:18px}
  label{display:block;font-size:13px;font-weight:600;color:#374151;margin-bottom:6px}
  input{width:100%;padding:10px 14px;border:1.5px solid #d1d5db;border-radius:8px;font-size:14px;transition:border .2s}
  input:focus{outline:none;border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.1)}
  .hint{font-size:11px;color:#6b7280;margin-top:4px}
  .btn{width:100%;padding:12px;background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:700;cursor:pointer;transition:opacity .2s}
  .btn:hover{opacity:.9}
  .error-box{background:#fef2f2;border:1.5px solid #fca5a5;border-radius:8px;padding:14px;margin-bottom:18px;color:#dc2626;font-size:13px}
  .success-box{background:#f0fdf4;border:1.5px solid #86efac;border-radius:8px;padding:24px;text-align:center}
  .success-box h2{color:#15803d;font-size:20px;margin-bottom:8px}
  .success-box p{color:#166534;font-size:14px;margin-bottom:4px}
  .creds-table{width:100%;border-collapse:collapse;margin:16px 0;font-size:13px}
  .creds-table th,.creds-table td{padding:8px 12px;border:1px solid #d1d5db;text-align:left}
  .creds-table th{background:#f9fafb;font-weight:600}
  .go-btn{display:block;margin:20px auto 0;padding:12px 32px;background:#2563eb;color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:700;cursor:pointer;text-decoration:none;text-align:center}
  .grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
  .warning{background:#fffbeb;border:1.5px solid #fcd34d;border-radius:8px;padding:12px;margin-bottom:18px;font-size:12px;color:#92400e}
  footer{text-align:center;padding:16px;font-size:11px;color:#6b7280;border-top:1px solid #f3f4f6}
  a{color:#2563eb}
</style>
</head>
<body>
<div class="card">
  <div class="header">
    <div class="logo">&#127979;</div>
    <h1>ScholarExam</h1>
    <p>Installation Wizard &mdash; Modern School Examination System</p>
  </div>
  <div class="body">

    <!-- Steps indicator -->
    <div class="steps">
      <div class="step <?= $step >= 1 ? ($step > 1 ? 'done' : 'active') : 'pending' ?>">1. Database</div>
      <div class="step <?= $step >= 2 ? ($step > 2 ? 'done' : 'active') : 'pending' ?>">2. Configure</div>
      <div class="step <?= $step >= 3 ? 'done' : 'pending' ?>">3. Done</div>
    </div>

    <?php if ($errors): ?>
      <div class="error-box">
        <?php foreach ($errors as $e): ?><div>&#9888; <?= htmlspecialchars($e) ?></div><?php endforeach; ?>
      </div>
    <?php endif; ?>

    <?php if ($step === 3 && $success): ?>
    <!-- ── Success ──────────────────────────────────────── -->
    <div class="success-box">
      <div style="font-size:48px;margin-bottom:12px">&#10003;</div>
      <h2>Installation Complete!</h2>
      <p>ScholarExam has been configured and is ready to use.</p>
      <p style="margin-top:12px;font-weight:600">Default login credentials:</p>
      <table class="creds-table">
        <thead><tr><th>Role</th><th>Username / ID</th><th>Password</th></tr></thead>
        <tbody>
          <tr><td>Admin</td><td><em>(password only)</em></td><td>admin123</td></tr>
          <tr><td>Developer</td><td><em>(password only)</em></td><td>developer123</td></tr>
          <tr><td>Teacher</td><td>Any name</td><td>Any password</td></tr>
          <tr><td>Student</td><td>SCH/2026/0001</td><td>SCH/2026/0001</td></tr>
        </tbody>
      </table>
      <p style="font-size:12px;color:#666;margin-top:8px">&#128274; Change passwords immediately after first login.</p>
      <a href="/" class="go-btn">Open ScholarExam &rarr;</a>
    </div>

    <?php elseif ($step <= 1): ?>
    <!-- ── Step 1: Database config ──────────────────────── -->
    <h3 style="font-size:16px;font-weight:700;margin-bottom:6px;color:#111827">Database Configuration</h3>
    <p style="font-size:13px;color:#6b7280;margin-bottom:18px">Enter your MySQL database details. These are typically found in your cPanel database manager.</p>

    <div class="warning">
      &#9432; For cPanel hosting, the host is usually <strong>localhost</strong>. Your database and user were created in <strong>cPanel &gt; MySQL Databases</strong>.
    </div>

    <form method="POST" action="">
      <input type="hidden" name="step" value="2">
      <div class="grid">
        <div class="field">
          <label for="db_host">Database Host</label>
          <input type="text" id="db_host" name="db_host" value="<?= htmlspecialchars($dbInfo['host'] ?? $defaultHost) ?>" required>
        </div>
        <div class="field">
          <label for="db_port">Port</label>
          <input type="number" id="db_port" name="db_port" value="<?= $dbInfo['port'] ?? 3306 ?>">
        </div>
      </div>
      <div class="field">
        <label for="db_name">Database Name</label>
        <input type="text" id="db_name" name="db_name" value="<?= htmlspecialchars($dbInfo['dbname'] ?? $defaultDb) ?>" required>
        <div class="hint">e.g. rbnbtcii_project5</div>
      </div>
      <div class="grid">
        <div class="field">
          <label for="db_user">Database Username</label>
          <input type="text" id="db_user" name="db_user" value="<?= htmlspecialchars($dbInfo['user'] ?? $defaultUser) ?>" required>
          <div class="hint">e.g. rbnbtcii_projec5</div>
        </div>
        <div class="field">
          <label for="db_pass">Database Password</label>
          <input type="password" id="db_pass" name="db_pass" placeholder="Enter password">
        </div>
      </div>
      <button type="submit" class="btn">Test &amp; Install Database &rarr;</button>
    </form>
    <?php endif; ?>

  </div>
  <footer>
    ScholarExam v1.0.0 &mdash; Designed &amp; developed by
    <a href="https://linkedin.com/in/vickyexpress" target="_blank">Adeniyi Victor</a>
    (Full Stack Developer &amp; AI Expert)
  </footer>
</div>
</body>
</html>
