<?php
/**
 * setup.php — One-time first Super Admin creation page
 *
 * TWO-LAYER PROTECTION:
 *   Layer 1 — Setup token: the URL must contain ?token=SETUP_TOKEN (from config.php).
 *              Without the correct token, this page returns 403 and reveals nothing.
 *   Layer 2 — Self-disabling: once any super_admin exists in the DB, the form
 *              is removed permanently regardless of the token.
 *
 * HOW TO USE:
 *   1. Run install/schema.sql in phpMyAdmin first.
 *   2. Edit config/config.php: set DB credentials and a unique SETUP_TOKEN.
 *   3. Visit  yoursite.com/ces-portal/setup.php?token=YOUR_TOKEN_HERE
 *   4. Fill in the form to create your Super Admin account.
 *   5. Log in. This page permanently refuses all access after that.
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/csrf.php';

// ── Layer 1: setup token check ────────────────────────────────────────────────
// Applied to BOTH GET and POST. The form action embeds the token in the URL
// so the same check covers both without a hidden field.

$provided_token = $_GET['token'] ?? '';
$expected_token = defined('SETUP_TOKEN') ? SETUP_TOKEN : '';

$token_ok = (
    $provided_token !== ''
    && $expected_token !== ''
    && $expected_token !== 'CHANGE_THIS_TO_A_RANDOM_SETUP_TOKEN'
    && hash_equals($expected_token, $provided_token)
);

if (!$token_ok) {
    // Return 403 with a generic message — do not hint that a setup page exists.
    http_response_code(403);
    exit('403 Forbidden');
}

// ── Layer 2: refuse if a super_admin already exists ───────────────────────────
// Token already verified above. Now check DB state.

function setup_already_done(): bool {
    try {
        $count = db()->query(
            "SELECT COUNT(*) FROM users WHERE role = 'super_admin'"
        )->fetchColumn();
        return (int)$count > 0;
    } catch (Throwable $e) {
        // DB not reachable or table doesn't exist yet — allow setup to proceed
        return false;
    }
}

$already_done = setup_already_done();

$error   = '';
$success = false;

if (!$already_done && $_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $name             = trim($_POST['name'] ?? '');
    $username         = trim($_POST['username'] ?? '');
    $email            = trim($_POST['email'] ?? '');
    $password         = $_POST['password'] ?? '';
    $password_confirm = $_POST['password_confirm'] ?? '';

    // ── Validation ────────────────────────────────────────────────────────────
    $errors = [];

    if ($name === '')     $errors[] = 'Full name is required.';
    if ($username === '') $errors[] = 'Username is required.';
    elseif (!preg_match('/^[a-zA-Z0-9._-]+$/', $username))
        $errors[] = 'Username may only contain letters, numbers, dots, underscores, and hyphens.';
    if ($email === '')    $errors[] = 'Email is required.';
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))
        $errors[] = 'Email is not a valid address.';
    if ($password === '') $errors[] = 'Password is required.';
    elseif (strlen($password) < 10)
        $errors[] = 'Password must be at least 10 characters.';
    elseif ($password !== $password_confirm)
        $errors[] = 'Passwords do not match.';

    if ($errors) {
        $error = implode(' ', $errors);
    } else {
        // Re-check inside the POST path — race-condition safety
        if (setup_already_done()) {
            $error = 'Setup has already been completed by another request.';
        } else {
            try {
                $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
                $stmt = db()->prepare(
                    'INSERT INTO users
                        (name, username, email, password_hash, role, active, created_at)
                     VALUES
                        (?, ?, ?, ?, \'super_admin\', 1, NOW())'
                );
                $stmt->execute([$name, $username, $email, $hash]);
                $success = true;
            } catch (Throwable $e) {
                // Duplicate username/email
                if ($e->getCode() === '23000') {
                    $error = 'That username or email is already taken.';
                } else {
                    $error = 'Database error. Check your config/config.php settings.';
                    error_log('setup.php error: ' . $e->getMessage());
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>First-Time Setup — <?= e(APP_NAME) ?></title>
    <link rel="shortcut icon" type="image/x-icon" href="<?= base_url('assets/img/favicon.png') ?>">
    <link rel="stylesheet" href="<?= base_url('assets/vendor/css/bootstrap.css') ?>">
    <link rel="stylesheet" href="<?= base_url('assets/css/custom.css') ?>">
    <style>
        body { background: #f5f6fa; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
        .setup-card { width: 100%; max-width: 480px; }
        .setup-header { background: linear-gradient(135deg, #3b5de7 0%, #45cafc 100%);
                        padding: 2rem; border-radius: 0.75rem 0.75rem 0 0; text-align: center; }
    </style>
</head>
<body>

<div class="setup-card shadow-sm">

    <div class="setup-header">
        <img src="<?= base_url('assets/img/logo_white.png') ?>" alt="<?= e(APP_NAME) ?>" style="max-height:44px;" class="mb-3">
        <h5 class="text-white fw-bold mb-0">First-Time Setup</h5>
        <p class="text-white mb-0" style="opacity:.8;font-size:.875rem;">Create your Super Admin account</p>
    </div>

    <div class="card border-0" style="border-radius:0 0 0.75rem 0.75rem;">
        <div class="card-body p-4">

            <?php if ($already_done): ?>
            <!-- ── Setup already complete ──────────────────────────────────── -->
            <div class="text-center py-3">
                <div style="font-size:3rem;">&#x2705;</div>
                <h5 class="fw-bold mt-3 mb-2">Setup Complete</h5>
                <p class="text-muted mb-4">
                    A Super Admin account already exists.<br>
                    This page is permanently disabled.
                </p>
                <a href="<?= base_url('login.php') ?>" class="btn btn-primary">Go to Login</a>
            </div>

            <?php elseif ($success): ?>
            <!-- ── Success ─────────────────────────────────────────────────── -->
            <div class="text-center py-3">
                <div style="font-size:3rem;">&#x1F513;</div>
                <h5 class="fw-bold mt-3 mb-2">Account Created!</h5>
                <p class="text-muted mb-4">
                    Your Super Admin account is ready.<br>
                    This setup page is now permanently disabled.
                </p>
                <a href="<?= base_url('login.php') ?>" class="btn btn-primary btn-lg">Sign In Now</a>
            </div>

            <?php else: ?>
            <!-- ── Setup form ──────────────────────────────────────────────── -->

            <p class="text-muted mb-4" style="font-size:.875rem;">
                No admin accounts exist yet. Fill in the form below to create the
                first Super Admin. This page will be permanently disabled afterward.
            </p>

            <?php if ($error): ?>
            <div class="alert alert-danger"><?= e($error) ?></div>
            <?php endif; ?>

            <form method="POST" action="setup.php?token=<?= urlencode(SETUP_TOKEN) ?>" novalidate>
                <?= csrf_field() ?>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Full Name <span class="text-danger">*</span></label>
                    <input type="text" name="name" class="form-control"
                           value="<?= e($_POST['name'] ?? '') ?>"
                           placeholder="Jane Smith" required maxlength="200" autofocus>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Username <span class="text-danger">*</span></label>
                    <input type="text" name="username" class="form-control"
                           value="<?= e($_POST['username'] ?? '') ?>"
                           placeholder="jane.smith" required maxlength="80"
                           pattern="[a-zA-Z0-9._-]+"
                           title="Letters, numbers, dots, underscores, hyphens only">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Email Address <span class="text-danger">*</span></label>
                    <input type="email" name="email" class="form-control"
                           value="<?= e($_POST['email'] ?? '') ?>"
                           placeholder="you@yourdomain.com" required maxlength="200">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Password <span class="text-danger">*</span></label>
                    <input type="password" name="password" class="form-control"
                           placeholder="Minimum 10 characters" required minlength="10"
                           autocomplete="new-password">
                    <div class="form-text">Use a strong, unique password. Store it in a password manager.</div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-semibold">Confirm Password <span class="text-danger">*</span></label>
                    <input type="password" name="password_confirm" class="form-control"
                           placeholder="Repeat your password" required autocomplete="new-password">
                </div>

                <button type="submit" class="btn btn-primary btn-lg w-100">
                    Create Super Admin Account
                </button>
            </form>
            <?php endif; ?>

        </div>
    </div>
</div>

<script src="<?= base_url('assets/vendor/js/jquery.min.js') ?>"></script>
<script src="<?= base_url('assets/vendor/js/bootstrap.min.js') ?>"></script>
</body>
</html>
