<?php
require 'includes/config.php';

// 1. Security Check - Block access if admin already exists
$check = $pdo->query("SELECT COUNT(*) FROM admin_account")->fetchColumn();
if ($check > 0) {
    header("Location: login.php");
    exit();
}

$message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 2. Data Cleaning (Sanitization)
    // Remove tags and trim whitespace
    $user  = trim(strip_tags($_POST['username']));
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $phone = preg_replace('/[^0-9+]/', '', $_POST['phone']); // Only keep digits and +
    $pass  = $_POST['password'];

    // 3. Strict Input Validation
    if (empty($user) || empty($email) || empty($phone)) {
        $message = "All fields are required.";
    }
    // Validate Username: Only allow alphanumeric and underscore (No special characters like ; # [ ])
    elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $user)) {
        $message = "Username can only contain letters, numbers, and underscores.";
    }
    // Validate Email format
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Invalid email format.";
    }
    // Validate Password Strength (1 Capital, 1 Digit, 1 Special Character, Min 8 Length)
    elseif (!preg_match('@[A-Z]@', $pass) || !preg_match('@[0-9]@', $pass) || !preg_match('@[^\w]@', $pass) || strlen($pass) < 8) {
        $message = "Password must be at least 8 characters and include a capital letter, a number, and a special character.";
    } 
    else {
        // 4. Secure Hashing
        $hashed_pass = password_hash($pass, PASSWORD_DEFAULT);

        try {
            // Using Prepared Statements (Prevents SQL Injection)
            $stmt = $pdo->prepare("INSERT INTO admin_account (username, email, phone_number, password) VALUES (?, ?, ?, ?)");
            
            if ($stmt->execute([$user, $email, $phone, $hashed_pass])) {
                header("Location: login.php?setup=success");
                exit();
            }
        } catch (PDOException $e) {
            $message = "Registration failed: Duplicate data or Database error.";
        }
    }
}

// Wrap message in UI for display
if (!empty($message)) {
    $message = "<div class='alert alert-danger'>" . htmlspecialchars($message) . "</div>";
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>System Setup | School Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; height: 100vh; display: flex; align-items: center; }
        .setup-card { max-width: 500px; margin: auto; border: none; border-radius: 15px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
        .card-header { background: #4e73df; color: white; border-radius: 15px 15px 0 0 !important; padding: 25px; text-align: center; }
        .req-item { font-size: 0.8rem; color: #858796; margin-bottom: 2px; transition: 0.3s; }
        .req-item.text-success { color: #1cc88a !important; font-weight: bold; }
        .form-control:focus { border-color: #4e73df; box-shadow: none; }
    </style>
</head>
<body>

<div class="container">
    <div class="card setup-card">
        <div class="card-header">
            <h4 class="mb-0 fw-bold"><i class="fas fa-cog me-2"></i>System Initialization</h4>
            <small class="opacity-75">Configure your master administrator account</small>
        </div>
        <div class="card-body p-4">
            <?php echo $message; ?>
            <form method="POST" id="setupForm">
                <div class="mb-3">
                    <label class="form-label small fw-bold">Username</label>
                    <input type="text" name="username" class="form-control" placeholder="admin" required>
                </div>
                
                <div class="row mb-3">
                    <div class="col-6">
                        <label class="form-label small fw-bold">Email</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label small fw-bold">Phone</label>
                        <input type="text" name="phone" class="form-control" required>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label small fw-bold">Password</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                    
                    <div class="mt-3 p-3 bg-light rounded-3 border">
                        <div id="len" class="req-item"><i class="fas fa-circle-notch me-2"></i>At least 8 characters</div>
                        <div id="cap" class="req-item"><i class="fas fa-circle-notch me-2"></i>At least one capital letter</div>
                        <div id="num" class="req-item"><i class="fas fa-circle-notch me-2"></i>At least one number</div>
                        <div id="spc" class="req-item"><i class="fas fa-circle-notch me-2"></i>At least one special character</div>
                    </div>
                </div>

                <button type="submit" id="submitBtn" class="btn btn-primary w-100 py-2 fw-bold disabled">
                    Finish Setup & Start
                </button>
            </form>
        </div>
    </div>
</div>

<script>
const pwd = document.getElementById('password');
const btn = document.getElementById('submitBtn');
const reqs = {
    len: v => v.length >= 8,
    cap: v => /[A-Z]/.test(v),
    num: v => /[0-9]/.test(v),
    spc: v => /[^\w]/.test(v)
};

pwd.addEventListener('input', () => {
    let validCount = 0;
    for (const [id, test] of Object.entries(reqs)) {
        const el = document.getElementById(id);
        if (test(pwd.value)) {
            el.classList.add('text-success');
            el.querySelector('i').className = 'fas fa-check-circle me-2';
            validCount++;
        } else {
            el.classList.remove('text-success');
            el.querySelector('i').className = 'fas fa-circle-notch me-2';
        }
    }
    if(validCount === 4) btn.classList.remove('disabled');
    else btn.classList.add('disabled');
});
</script>

</body>
</html>