<?php
/**
 * Jalankan sekali untuk membuat database dan user admin.
 * Akses: http://localhost/klasifikasi/install.php
 * Hapus file ini setelah instalasi berhasil.
 */

$host = 'localhost';
$user = 'root';
$pass = '';

$messages = [];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ]);

        $sql = file_get_contents(__DIR__ . '/database/schema.sql');
        $statements = array_filter(array_map('trim', explode(';', $sql)));

        foreach ($statements as $statement) {
            if ($statement !== '' && stripos($statement, 'INSERT INTO users') === false) {
                $pdo->exec($statement);
            }
        }

        $pdo->exec('USE pip_klasifikasi');
        try {
            $pdo->exec('ALTER TABLE siswa MODIFY COLUMN penghasilan_ortu VARCHAR(150) NOT NULL DEFAULT ""');
            $pdo->exec('ALTER TABLE data_latih MODIFY COLUMN penghasilan_ortu VARCHAR(150) NOT NULL');
        } catch (PDOException $e) {
            // Kolom sudah benar pada instalasi baru
        }

        $hash = password_hash('admin123', PASSWORD_DEFAULT);
        $pdo->exec('DELETE FROM users');
        $stmt = $pdo->prepare('INSERT INTO users (username, password, nama, email, role) VALUES (?, ?, ?, ?, ?)');
        $stmt->execute(['admin', $hash, 'Administrator', 'admin@pip.local', 'Admin']);

        $messages[] = 'Database berhasil dibuat.';
        $messages[] = 'Login: username <strong>admin</strong>, password <strong>admin123</strong>';
    } catch (PDOException $e) {
        $errors[] = 'Error: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Instalasi - PIP Klasifikasi</title>
  <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="login-page">
  <div class="login-card" style="max-width:480px">
    <h1 style="margin-bottom:1rem">Instalasi Database</h1>
    <?php foreach ($errors as $err): ?>
      <div class="alert alert-danger"><?= htmlspecialchars($err) ?></div>
    <?php endforeach; ?>
    <?php foreach ($messages as $msg): ?>
      <div class="alert alert-success"><?= $msg ?></div>
    <?php endforeach; ?>
    <?php if (empty($messages)): ?>
    <p style="margin-bottom:1rem;font-size:0.9rem">Pastikan MySQL/XAMPP aktif, lalu klik tombol di bawah.</p>
    <form method="post">
      <button type="submit" class="btn btn-primary">Install Database</button>
    </form>
    <?php else: ?>
    <a href="index.php" class="btn btn-primary" style="display:block;text-align:center;margin-top:1rem">Ke Halaman Login</a>
    <?php endif; ?>
  </div>
</body>
</html>
