<?php
require __DIR__ . '/../app/bootstrap.php';

function run_sql_file(string $file): void {
  $sql = file_get_contents($file);
  if ($sql === false) throw new RuntimeException('Cannot read schema file.');
  // Remove SQL line comments starting with -- (prevents skipping mixed statements)
  $sql = preg_replace('/^\s*--.*$/m', '', $sql);
  // Split statements safely (simple approach)
  $stmts = array_filter(array_map('trim', preg_split('/;\s*\n/', $sql) ?: []));
  foreach ($stmts as $st) {
    if ($st === '') continue;
    db()->exec($st);
  }
}

$errors = [];
$ok = false;

try {
  run_sql_file(__DIR__ . '/../database/schema.sql');

  // Seed admin if not exists
  $admin = db_one("SELECT id FROM users WHERE email = ? LIMIT 1", ['admin@oasis.local']);
  if (!$admin) {
    $hash = password_hash('Admin@12345', PASSWORD_DEFAULT);
    db_insert(
      "INSERT INTO users (name,email,password_hash,role,created_at,updated_at) VALUES (?,?,?,?,?,?)",
      ['System Admin','admin@oasis.local',$hash,'admin', now_dt(), null]
    );
  }

  $ok = true;
} catch (Throwable $e) {
  $errors[] = $e->getMessage();
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>تثبيت النظام</title>
  <link rel="stylesheet" href="<?= e(url('/assets/app.css')) ?>">
</head>
<body>
  <div class="login-wrap">
    <div class="card">
      <h2>تثبيت/تحديث الجداول</h2>
      <hr>
      <?php if ($ok): ?>
        <div class="alert success">تم إنشاء/تحديث الجداول بنجاح، وتم التأكد من وجود مستخدم الأدمن.</div>
        <div class="small">
          <b>الدخول:</b> admin@oasis.local / Admin@12345
        </div>
        <hr>
        <a class="btn primary" href="<?= e(url('/login.php')) ?>">اذهب لتسجيل الدخول</a>
      <?php else: ?>
        <div class="alert error">فشل التثبيت.</div>
        <?php foreach ($errors as $er): ?>
          <div class="small"><?= e($er) ?></div>
        <?php endforeach; ?>
        <hr>
        <a class="btn" href="<?= e(url('/login.php')) ?>">عودة</a>
      <?php endif; ?>
    </div>
  </div>
</body>
</html>
