<?php
$message = "";

try {
    $pdo = new PDO("mysql:host=localhost;dbname=school_checkin", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

$is_admin_mode = isset($_GET['admin']) && $_GET['admin'] == 1;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $role     = $_POST['role'] ?? 'teacher'; // default to teacher
    $schoolCode = 'SDAESI';

    // Admin: no license required. Teacher: license required.
    if (!$username || !$password || ($role !== 'admin' && empty($_POST['license_key']))) {
        $message = "⚠ Please fill in all fields" . ($role !== 'admin' ? " including license key." : ".");
    } else {
        // If not admin, validate license key
        if ($role !== 'admin') {
            $licenseKey = $_POST['license_key'];
            $stmt = $pdo->prepare("SELECT * FROM license_keys WHERE license_key = ? AND school_code = ? AND is_active = 1 AND valid_until >= CURDATE()");
            $stmt->execute([$licenseKey, $schoolCode]);
            if ($stmt->rowCount() === 0) {
                $message = "❌ Invalid or expired license key.";
                goto html_form;
            }
        } else {
            $licenseKey = NULL;
        }

        // Check if username exists
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->rowCount() > 0) {
            $message = "⚠ Username already exists!";
        } else {
            // Register user
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $insert = $pdo->prepare("INSERT INTO users (username, password, license_key, school_code, role) VALUES (?, ?, ?, ?, ?)");
            if ($insert->execute([$username, $hashed_password, $licenseKey, $schoolCode, $role])) {
                $message = "✅ Account created successfully!";
            } else {
                $message = "❌ Registration failed. Please try again.";
            }
        }
    }
}
html_form:
?>
<!DOCTYPE html>
<html>
<head>
    <title><?= $is_admin_mode ? "Create Admin Account" : "Create Teacher Account" ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-dark text-white">
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-5">
                <div class="card shadow border-0">
                    <div class="card-header bg-primary text-white text-center">
                        <h4><?= $is_admin_mode ? "Create Admin Account" : "Create Teacher Account" ?></h4>
                    </div>
                    <div class="card-body">
                        <?php if ($message): ?>
                            <div class="alert alert-info text-center"><?= $message ?></div>
                        <?php endif; ?>
                        <form method="POST" action="">
                            <div class="mb-3">
                                <label class="form-label">Username</label>
                                <input type="text" name="username" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Password</label>
                                <input type="password" name="password" class="form-control" required>
                            </div>
                            <?php if ($is_admin_mode): ?>
                                <input type="hidden" name="role" value="admin">
                            <?php else: ?>
                                <input type="hidden" name="role" value="teacher">
                                <div class="mb-3">
                                    <label class="form-label">License Key</label>
                                    <input type="text" name="license_key" class="form-control" required>
                                </div>
                            <?php endif; ?>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">Register</button>
                            </div>
                        </form>
                        <div class="text-center mt-3">
                            <a href="login.php" class="text-decoration-none">← Back to Login</a>
                        </div>
                    </div>
                </div>
                <p class="text-center text-muted small mt-3">SIOCON QR SYSTEM</p>
            </div>
        </div>
    </div>
</body>
</html>