<?php
declare(strict_types=1);

/**
 * SGAccount – Register First Admin Page
 */

require_once __DIR__ . '/../../Config/config.php';
require_once __DIR__ . '/../../Config/functions.php';
require_once __DIR__ . '/../../Config/database.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$pdo = Database::getConnection();

// Check if an admin already exists
$check = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'admin'")->fetchColumn();
if ($check > 0) {
    set_flash('info', 'An admin account already exists. Please log in.');
    header('Location: router.php?page=login');
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = post('name');
    $email = post('email');
    $password = post('password');
    $confirm = post('confirm');
    $csrf = post('csrf');

    if (!validate_csrf($csrf)) {
        set_flash('error', 'Security token expired. Please refresh and try again.');
        header('Location: router.php?page=register-admin');
        exit;
    }

    if ($password !== $confirm) {
        set_flash('error', 'Passwords do not match.');
    } else {
        // Check email unique
        $exists = $pdo->prepare("SELECT id FROM users WHERE email = :email LIMIT 1");
        $exists->execute(['email' => $email]);
        if ($exists->fetch()) {
            set_flash('error', 'This email is already registered.');
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("
                INSERT INTO users (name, email, password_hash, role, status, created_at, updated_at)
                VALUES (:name, :email, :password_hash, 'admin', 'active', NOW(), NOW())
            ");
            $ok = $stmt->execute(['name' => $name, 'email' => $email, 'password_hash' => $hash]);

            if ($ok) {
                set_flash('success', 'Admin account created successfully! You may now log in.');
                header('Location: router.php?page=login');
                exit;
            } else {
                set_flash('error', 'Registration failed. Please try again.');
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Register Admin | SGAccount</title>

  <!-- AdminLTE / Bootstrap / FontAwesome via CDN -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.css">
</head>

<body class="hold-transition register-page" style="background:#f4f6f9;">
<div class="register-box">
  <div class="register-logo">
    <img src="assets/img/logo.png" alt="Logo" width="60" class="mr-2">
    <b>SG</b>Account
  </div>

  <div class="card card-outline card-primary">
    <div class="card-body register-card-body">
      <p class="login-box-msg">Create the first Administrator account</p>

      <form method="POST" action="">
        <input type="hidden" name="csrf" value="<?= csrf_token() ?>">

        <div class="input-group mb-3">
          <input type="text" name="name" class="form-control" placeholder="Full Name" required>
          <div class="input-group-append">
            <div class="input-group-text"><span class="fas fa-user"></span></div>
          </div>
        </div>

        <div class="input-group mb-3">
          <input type="email" name="email" class="form-control" placeholder="Email" required>
          <div class="input-group-append">
            <div class="input-group-text"><span class="fas fa-envelope"></span></div>
          </div>
        </div>

        <div class="input-group mb-3">
          <input type="password" name="password" class="form-control" placeholder="Password" required minlength="6">
          <div class="input-group-append">
            <div class="input-group-text"><span class="fas fa-lock"></span></div>
          </div>
        </div>

        <div class="input-group mb-3">
          <input type="password" name="confirm" class="form-control" placeholder="Confirm Password" required minlength="6">
          <div class="input-group-append">
            <div class="input-group-text"><span class="fas fa-lock"></span></div>
          </div>
        </div>

        <div class="row">
          <div class="col-8">
            <a href="router.php?page=login" class="text-center">Back to Login</a>
          </div>
          <div class="col-4">
            <button type="submit" class="btn btn-primary btn-block">Register</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- JS Libraries -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.js"></script>

<!-- Toastr Flash Notifications -->
<script>
toastr.options = {
  "closeButton": true,
  "progressBar": true,
  "positionClass": "toast-top-right",
  "timeOut": "3500"
};

<?php if ($msg = get_flash('success')): ?>
toastr.success("<?= addslashes($msg) ?>");
<?php endif; ?>

<?php if ($msg = get_flash('error')): ?>
toastr.error("<?= addslashes($msg) ?>");
<?php endif; ?>

<?php if ($msg = get_flash('info')): ?>
toastr.info("<?= addslashes($msg) ?>");
<?php endif; ?>
</script>

</body>
</html>
