<?php
/**
 * Cincinnati Fire Department Portal - Self-Registration
 */
require_once __DIR__ . '/config/auth.php';

startSession();

if (!empty($_SESSION['authenticated'])) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCsrf();

    $first   = trim($_POST['first_name'] ?? '');
    $last    = trim($_POST['last_name'] ?? '');
    $email   = trim($_POST['email'] ?? '');
    $user    = trim($_POST['username'] ?? '');
    $pass    = $_POST['password'] ?? '';
    $confirm = $_POST['password_confirm'] ?? '';
    $station = trim($_POST['station'] ?? '');
    $badge   = trim($_POST['badge_number'] ?? '');
    $role    = $_POST['role'] ?? 'firefighter';

    // Validate
    if ($first === '' || $last === '' || $email === '' || $user === '' || $pass === '') {
        $error = 'All required fields must be filled in.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } elseif (strlen($pass) < 8) {
        $error = 'Password must be at least 8 characters.';
    } elseif ($pass !== $confirm) {
        $error = 'Passwords do not match.';
    } elseif (!array_key_exists($role, ROLES)) {
        $error = 'Invalid role selected.';
    } else {
        $db = getDB();
        // Check for duplicate username or email
        $stmt = $db->prepare('SELECT id FROM users WHERE username = :u OR email = :e');
        $stmt->execute([':u' => $user, ':e' => $email]);
        if ($stmt->fetch()) {
            $error = 'Username or email already exists.';
        } else {
            $hash = password_hash($pass, PASSWORD_BCRYPT, ['cost' => 12]);
            $stmt = $db->prepare('INSERT INTO users (first_name, last_name, email, username, password_hash, role, station, badge_number, status) VALUES (:fn, :ln, :em, :un, :ph, :role, :st, :badge, :status)');
            $stmt->execute([
                ':fn'     => $first,
                ':ln'     => $last,
                ':em'     => $email,
                ':un'     => $user,
                ':ph'     => $hash,
                ':role'   => $role,
                ':st'     => $station,
                ':badge'  => $badge,
                ':status' => 'pending'
            ]);

            auditLog('registration', null, "New registration: $user ($email)");

            // Notify admin via email
            $adminEmail = getSetting('admin_email', 'admin@cincinnatifire.ai');
            $subject = "New Portal Registration: $first $last";
            $body = "A new user has registered for the Cincinnati Fire Portal:\n\n";
            $body .= "Name: $first $last\nUsername: $user\nEmail: $email\n";
            $body .= "Station: $station\nBadge: $badge\nRequested Role: " . (ROLES[$role]['label'] ?? $role) . "\n\n";
            $body .= "Log in to the admin panel to approve this account.";
            @mail($adminEmail, $subject, $body, "From: noreply@cincinnatifire.ai");

            $success = true;
        }
    }
}

$csrf = generateCsrfToken();
$roleOptions = ROLES;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Request Access — Cincinnati Fire Department</title>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/img/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="assets/img/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/img/apple-touch-icon.png">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", system-ui, sans-serif;
            background: #F2F2F7;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            -webkit-font-smoothing: antialiased;
        }
        .register-container { width: 100%; max-width: 480px; }
        .register-card {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08), 0 0 1px rgba(0,0,0,0.1);
            padding: 36px 32px;
        }
        .register-card h1 {
            font-size: 22px;
            font-weight: 700;
            color: #1C1C1E;
            text-align: center;
            margin-bottom: 4px;
        }
        .register-card .subtitle {
            font-size: 14px;
            color: #8E8E93;
            text-align: center;
            margin-bottom: 24px;
        }
        .alert {
            padding: 12px 16px;
            border-radius: 10px;
            font-size: 14px;
            margin-bottom: 20px;
        }
        .alert-error { background: #FEE2E2; color: #991B1B; border: 1px solid #FECACA; }
        .alert-success { background: #D1FAE5; color: #065F46; border: 1px solid #A7F3D0; }
        .form-row { display: flex; gap: 12px; }
        .form-row .form-group { flex: 1; }
        .form-group { margin-bottom: 14px; }
        .form-group label { display: block; font-size: 13px; font-weight: 600; color: #3A3A3C; margin-bottom: 5px; }
        .form-group input, .form-group select {
            width: 100%;
            padding: 11px 14px;
            font-size: 15px;
            border: 1px solid #E5E5EA;
            border-radius: 10px;
            background: #F9F9F9;
            color: #1C1C1E;
            outline: none;
            transition: border-color 0.2s, box-shadow 0.2s;
            font-family: inherit;
        }
        .form-group input:focus, .form-group select:focus {
            border-color: #0B2240;
            box-shadow: 0 0 0 3px rgba(11,34,64,0.15);
            background: #fff;
        }
        .btn-submit {
            width: 100%;
            padding: 14px;
            font-size: 16px;
            font-weight: 600;
            background: #0B2240;
            color: #fff;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            transition: background 0.2s, transform 0.1s;
            font-family: inherit;
            margin-top: 8px;
        }
        .btn-submit:hover { background: #071829; }
        .btn-submit:active { transform: scale(0.98); }
        .back-link {
            display: block;
            text-align: center;
            margin-top: 16px;
            font-size: 14px;
            color: #0B2240;
            text-decoration: none;
            font-weight: 600;
        }
        .back-link:hover { text-decoration: underline; }
        .required::after { content: " *"; color: #0B2240; }
        @media (max-width: 480px) {
            .form-row { flex-direction: column; gap: 0; }
            .register-card { padding: 28px 20px; }
        }
    </style>
</head>
<body>
<div class="register-container">
    <div class="register-card">
        <h1>Request Access</h1>
        <p class="subtitle">Cincinnati Fire Department Staff Portal</p>

        <?php if ($success): ?>
            <div class="alert alert-success">
                Your request has been submitted. An administrator will review and approve your account.
                You will be notified at the email address you provided.
            </div>
            <a href="index.php" class="back-link">&larr; Return to Sign In</a>
        <?php else: ?>

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

        <form method="POST" action="register.php">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">

            <div class="form-row">
                <div class="form-group">
                    <label for="first_name" class="required">First Name</label>
                    <input type="text" id="first_name" name="first_name" required
                           value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label for="last_name" class="required">Last Name</label>
                    <input type="text" id="last_name" name="last_name" required
                           value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>">
                </div>
            </div>

            <div class="form-group">
                <label for="email" class="required">Email</label>
                <input type="email" id="email" name="email" required
                       value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
            </div>

            <div class="form-group">
                <label for="username" class="required">Username</label>
                <input type="text" id="username" name="username" required autocomplete="username"
                       value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="password" class="required">Password</label>
                    <input type="password" id="password" name="password" required autocomplete="new-password"
                           minlength="8" placeholder="Min. 8 characters">
                </div>
                <div class="form-group">
                    <label for="password_confirm" class="required">Confirm</label>
                    <input type="password" id="password_confirm" name="password_confirm" required
                           autocomplete="new-password">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="station">Station Number</label>
                    <input type="text" id="station" name="station"
                           value="<?= htmlspecialchars($_POST['station'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label for="badge_number">Badge Number</label>
                    <input type="text" id="badge_number" name="badge_number"
                           value="<?= htmlspecialchars($_POST['badge_number'] ?? '') ?>">
                </div>
            </div>

            <div class="form-group">
                <label for="role">Requested Role</label>
                <select id="role" name="role">
                    <?php foreach ($roleOptions as $key => $info): ?>
                        <?php if ($key === 'admin') continue; ?>
                        <option value="<?= $key ?>" <?= (($_POST['role'] ?? 'firefighter') === $key) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($info['label']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <button type="submit" class="btn-submit">Submit Request</button>
        </form>

        <a href="index.php" class="back-link">&larr; Back to Sign In</a>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
