<?php
// SHOW ERRORS
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// START SESSION
session_start();

// REQUIRE PDO CONFIG
require 'pdo_config.php';

$message = '';

if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $role = $_POST['role'] ?? 'teacher';
    $license_key = isset($_POST['license_key']) ? trim($_POST['license_key']) : '';

    try {
        // Always fetch user first, with role check
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND role = ?");
        $stmt->execute([$username, $role]);

        if ($stmt->rowCount() === 1) {
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (password_verify($password, $user['password'])) {
                if ($role === 'admin') {
                    // No license key needed for admin login
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['is_admin'] = 1;
                    $_SESSION['role'] = $user['role'];
                    header("Location: dashboard.php");
                    exit();
                } else {
                    // TEACHER: Require and validate license key
                    if (!$license_key) {
                        $message = "❌ License key is required for teachers.";
                    } else {
                        $stmtLicense = $pdo->prepare("SELECT * FROM license_keys WHERE license_key = ? AND is_active = 1 AND valid_until >= CURDATE()");
                        $stmtLicense->execute([$license_key]);
                        $license = $stmtLicense->fetch(PDO::FETCH_ASSOC);

                        if ($license && $user['license_key'] === $license_key) {
                            $_SESSION['user_id'] = $user['id'];
                            $_SESSION['username'] = $user['username'];
                            $_SESSION['role'] = $user['role'];
                            $_SESSION['is_admin'] = 0;
                            $_SESSION['license_key'] = $license_key;
                            header("Location: dashboard.php");
                            exit();
                        } else if (!$license) {
                            $message = "❌ Invalid or expired license key.";
                        } else {
                            $message = "❌ User is not registered under this license key.";
                        }
                    }
                }
            } else {
                $message = "❌ Incorrect password.";
            }
        } else {
            $message = "❌ User not found or role mismatch.";
        }
    } catch (PDOException $e) {
        $message = "❌ Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login - Student QR System</title>
    <style>
        body {
            font-family: Arial;
            text-align: center;
            padding: 40px 15px;
        }
        body.light { background: #f0f0f0; color: #000; }
        body.dark { background: #121212; color: #fff; }

        .school-logo { width: 100px; margin-bottom: 10px; }
        .school-name { font-size: 18px; font-weight: bold; margin-bottom: 25px; }

        form {
            background: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
            display: inline-block;
        }
        body.dark form {
            background: #1e1e1e;
            box-shadow: 0 0 10px #000;
        }

        input, button, select {
            padding: 10px;
            width: 250px;
            margin: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        body.dark input, body.dark button, body.dark select {
            background-color: #333;
            color: #fff;
            border: 1px solid #555;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
        }
        button:hover {
            background-color: #0056b3;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
    </style>
    <script>
        function toggleLicenseField() {
            var role = document.getElementById('role').value;
            var licenseDiv = document.getElementById('license_div');
            var licenseInput = document.getElementById('license_key');
            if (role === 'admin') {
                licenseDiv.style.display = "none";
                licenseInput.required = false;
            } else {
                licenseDiv.style.display = "block";
                licenseInput.required = true;
            }
        }
    </script>
</head>
<body class="light">

<img src="school_logo.png" class="school-logo" alt="School Logo">
<div class="school-name">SIOCON DISTRICT ADVENTIST ELEMENTARY SCHOOL INC</div>

<form method="POST" autocomplete="off">
    <h2>🔐 Login</h2>
    <input type="text" name="username" placeholder="Username" required autocomplete="username"><br>
    <input type="password" name="password" placeholder="Password" required autocomplete="current-password"><br>
    <select name="role" id="role" onchange="toggleLicenseField()" required>
        <option value="teacher">Teacher</option>
        <option value="admin">Admin</option>
    </select><br>
    <div id="license_div">
        <input type="text" name="license_key" id="license_key" placeholder="Enter License Key (teachers only)">
    </div>
    <button name="login">Login</button><br>
    <a href="create_account.php">Create Account</a><br>
    <?php if ($message) echo "<p class='error'>$message</p>"; ?>
</form>

<script>
    const body = document.body;
    const theme = localStorage.getItem('theme');
    if (theme === 'dark') {
        body.classList.remove('light');
        body.classList.add('dark');
    } else {
        body.classList.remove('dark');
        body.classList.add('light');
    }
    // Initialize license field visibility on page load
    toggleLicenseField();
</script>
</body>
</html>