<?php
/**
 * INSTALLER SISTEM KKN UMUS 2026
 * Akses sekali saja: https://lppm.umus.ac.id/kkn-system/install.php
 * HAPUS FILE INI setelah instalasi berhasil!
 */
require_once __DIR__ . '/includes/config.php';

$msg = [];
$ok  = true;

try {
    $pdo = new PDO('mysql:host='.DB_HOST.';charset=utf8mb4', DB_USER, DB_PASS,
                   [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

    // Buat database jika belum ada
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` DEFAULT CHARACTER SET utf8mb4");
    $pdo->exec("USE `" . DB_NAME . "`");
    $msg[] = '✅ Database <strong>' . DB_NAME . '</strong> siap.';

    // Jalankan SQL schema
    $sql = file_get_contents(__DIR__ . '/../database.sql');
    // Hapus komentar dan eksekusi per statement
    $statements = array_filter(array_map('trim', explode(';', $sql)));
    foreach ($statements as $stmt) {
        if ($stmt && !preg_match('/^--/', $stmt) && !preg_match('/^\/\*/', $stmt)) {
            try { $pdo->exec($stmt); } catch (Exception $e) { /* skip duplicate */ }
        }
    }
    $msg[] = '✅ Tabel database berhasil dibuat.';

    // Hash password admin yang benar
    $hashed = password_hash('kkn2026#', PASSWORD_BCRYPT);
    $stmt   = $pdo->prepare("UPDATE kkn_users SET password = ? WHERE username = 'admin_kkn'");
    $stmt->execute([$hashed]);
    $msg[] = '✅ Password admin di-hash dengan benar.';

    // Cek koneksi SMTP (ping server)
    $fp = @fsockopen(SMTP_HOST, SMTP_PORT, $errno, $errstr, 5);
    if ($fp) {
        fclose($fp);
        $msg[] = '✅ Koneksi SMTP ke <strong>' . SMTP_HOST . ':' . SMTP_PORT . '</strong> berhasil.';
    } else {
        $msg[] = '⚠️ SMTP tidak bisa dijangkau (' . $errstr . '). Email mungkin tidak terkirim.';
    }

} catch (PDOException $e) {
    $ok    = false;
    $msg[] = '❌ Error: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Installer KKN UMUS 2026</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body{font-family:'Inter',sans-serif;background:#F5F7FA;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:2rem;}
.box{background:#fff;border-radius:14px;padding:2.5rem;max-width:560px;width:100%;box-shadow:0 8px 32px rgba(0,0,0,.1);}
h1{color:#0D2E5C;font-size:1.3rem;margin-bottom:1.5rem;}
.msg{padding:10px 14px;border-radius:8px;margin-bottom:.75rem;font-size:.88rem;}
.msg-ok{background:#F0FFF4;border:1px solid #C6F6D5;color:#276749;}
.msg-warn{background:#FFFBEB;border:1px solid #FDE68A;color:#744210;}
.msg-err{background:#FFF5F5;border:1px solid #FED7D7;color:#C53030;}
.btn{display:inline-block;margin-top:1.5rem;padding:12px 28px;background:#0D2E5C;color:#fff;border-radius:8px;text-decoration:none;font-weight:700;font-size:.95rem;}
.warn-box{background:#FFF3CD;border:1px solid #FFE082;border-radius:8px;padding:1rem;margin-top:1.5rem;font-size:.83rem;color:#744210;}
</style>
</head>
<body>
<div class="box">
  <h1>⚙️ Installer Sistem KKN UMUS 2026</h1>
  <?php foreach ($msg as $m): ?>
  <div class="msg <?= str_starts_with($m,'✅')?'msg-ok':(str_starts_with($m,'⚠')?'msg-warn':'msg-err') ?>">
    <?= $m ?>
  </div>
  <?php endforeach; ?>

  <?php if ($ok): ?>
  <div style="background:#E8F0FB;border-radius:8px;padding:1rem;margin-top:1rem;font-size:.85rem;">
    <strong>🎉 Instalasi selesai!</strong><br><br>
    <strong>Login Admin:</strong><br>
    Username: <code>admin_kkn</code><br>
    Password: <code>kkn2026#</code><br><br>
    URL Sistem:<br>
    • <a href="<?= BASE_URL ?>/kkn-login">Login</a><br>
    • <a href="<?= BASE_URL ?>/kkn-daftar">Daftar</a><br>
    • <a href="<?= BASE_URL ?>/kkn-dashboard">Dashboard</a>
  </div>
  <div class="warn-box">
    ⚠️ <strong>PENTING:</strong> Segera hapus file <code>install.php</code> dari server setelah instalasi!<br>
    Path: <code>/home/lppm/public_html/kkn-system/install.php</code>
  </div>
  <a href="<?= BASE_URL ?>/kkn-login" class="btn">→ Buka Halaman Login</a>
  <?php else: ?>
  <div class="warn-box">
    ❌ Instalasi gagal. Pastikan:<br>
    1. Database <code><?= DB_NAME ?></code> sudah dibuat di cPanel → MySQL Databases<br>
    2. User database sudah dibuat dan diberi akses<br>
    3. Password di <code>config.php</code> sudah benar
  </div>
  <?php endif; ?>
</div>
</body>
</html>
