<?php
function generateLicenseKey($length = 16) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        if ($i > 0 && $i % 4 == 0) $key .= '-';
        $key .= $characters[random_int(0, strlen($characters) - 1)];
    }
    return $key;
}

$generatedKey = '';
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $schoolCode = $_POST['school_code'] ?? '';
    $validUntil = $_POST['valid_until'] ?? '';
    $userLimit = intval($_POST['user_limit'] ?? 1);

    if (!empty($schoolCode) && !empty($validUntil) && $userLimit > 0) {
        $generatedKey = generateLicenseKey();

        // Connect to DB
        $conn = new mysqli("localhost", "root", "", "school_checkin");
        if ($conn->connect_error) {
            die("Connection failed.");
        }

        // Deactivate old keys for this school
        $stmtUpdate = $conn->prepare("UPDATE license_keys SET is_active = 0 WHERE school_code = ?");
        $stmtUpdate->bind_param("s", $schoolCode);
        $stmtUpdate->execute();
        $stmtUpdate->close();

        // Insert new key
        $stmt = $conn->prepare("INSERT INTO license_keys (school_code, license_key, valid_until, is_active, user_limit) VALUES (?, ?, ?, 1, ?)");
        $stmt->bind_param("sssi", $schoolCode, $generatedKey, $validUntil, $userLimit);
        if ($stmt->execute()) {
            $message = "✅ License generated and saved to database!";
        } else {
            $message = "❌ Error saving license: " . $stmt->error;
            $generatedKey = '';
        }
        $stmt->close();
        $conn->close();
    } else {
        $message = "❌ Please fill all fields correctly.";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>License Key Generator</title>
    <style>
        body { font-family: Arial; background: #f4f4f4; padding: 40px; text-align: center; }
        form { display: inline-block; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 0 10px #ccc; }
        input, button { padding: 10px; margin: 10px 0; width: 100%; }
        .key { font-size: 20px; color: green; margin-top: 20px; }
        .message { font-size: 16px; color: #444; margin-top: 10px; }
    </style>
</head>
<body>
    <h2>🔐 License Key Generator</h2>
    <form method="POST">
        <input type="text" name="school_code" placeholder="School Code (e.g. SDAESI)" required>
        <input type="date" name="valid_until" required>
        <input type="number" name="user_limit" placeholder="User Limit" min="1" value="1" required>
        <button type="submit">Generate License</button>
        <?php if (!empty($message)): ?>
            <div class="message"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>
        <?php if (!empty($generatedKey)): ?>
            <div class="key">Generated Key: <strong><?= htmlspecialchars($generatedKey) ?></strong></div>
        <?php endif; ?>
    </form>
</body>
</html>