<?php
// register_admin.php
// This page allows for the registration of new administrators.
// In a production environment, access to this page should be highly restricted.

// Ensure the session is started only once.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Optional: Add a very strong security check here in a real application.
// For a prototype, we're making it accessible for initial setup.
// Example: Only allow if no admins exist, or if a master key is provided.
// if (isset($_SESSION['loggedin']) && $_SESSION['user_role'] !== 'admin') {
//     header("Location: index.php?page=dashboard");
//     exit();
// }

// Include the database connection file.
require_once 'config/database.php';

$message = ''; // Message to display for success or error feedback.
$is_error = false; // Flag for message styling.

// Initialize form fields for sticky form behavior.
$username = '';
$email = '';
$full_name = '';

// Handle form submission.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $role = 'admin'; // <--- Explicitly set role to 'admin' for this page

    // --- Input Validation ---
    if (empty($username) || empty($email) || empty($full_name) || empty($password) || empty($confirm_password)) {
        $message = "Please fill in all required fields.";
        $is_error = true;
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Invalid email format.";
        $is_error = true;
    } elseif ($password !== $confirm_password) {
        $message = "Passwords do not match.";
        $is_error = true;
    } elseif (strlen($password) < 6) { // Minimum password length
        $message = "Password must be at least 6 characters long.";
        $is_error = true;
    } else {
        // --- Check for existing username or email ---
        try {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            if ($stmt->fetch()) {
                $message = "Username or email already exists. Please choose a different one.";
                $is_error = true;
            } else {
                // --- Hash the password before storing ---
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                // --- Insert admin into database ---
                $stmt = $pdo->prepare("INSERT INTO users (username, password, email, full_name, role) VALUES (?, ?, ?, ?, ?)");
                if ($stmt->execute([$username, $hashed_password, $email, $full_name, $role])) {
                    $message = "Administrator '<strong>" . htmlspecialchars($full_name) . "</strong>' registered successfully!";
                    $is_error = false;
                    // Clear form fields on success.
                    $username = '';
                    $email = '';
                    $full_name = '';
                    // Passwords are not pre-filled, so no need to clear.
                } else {
                    $message = "Error registering administrator. Please try again.";
                    $is_error = true;
                }
            }
        } catch (PDOException $e) {
            $message = "Database error: " . $e->getMessage();
            $is_error = true;
        }
    }
}
?>

<div class="bg-white p-8 rounded-lg shadow-md w-full max-w-lg">
    <h2 class="text-2xl font-bold mb-6 text-center text-gray-800">Register New Administrator</h2>

    <?php if (!empty($message)): ?>
        <div class="mb-4 p-3 rounded-md text-center
            <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <form action="index.php?page=register_admin" method="POST" class="space-y-4">
        <!-- Username Input Field -->
        <div>
            <label for="username" class="block text-gray-700 text-sm font-semibold mb-2">Username:</label>
            <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500">
        </div>
        <!-- Email Input Field -->
        <div>
            <label for="email" class="block text-gray-700 text-sm font-semibold mb-2">Email:</label>
            <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500">
        </div>
        <!-- Full Name Input Field -->
        <div>
            <label for="full_name" class="block text-gray-700 text-sm font-semibold mb-2">Full Name:</label>
            <input type="text" id="full_name" name="full_name" value="<?php echo htmlspecialchars($full_name); ?>" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500">
        </div>
        <!-- Password Field -->
        <div>
            <label for="password" class="block text-gray-700 text-sm font-semibold mb-2">Password:</label>
            <input type="password" id="password" name="password" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500">
        </div>
        <!-- Confirm Password Field -->
        <div>
            <label for="confirm_password" class="block text-gray-700 text-sm font-semibold mb-2">Confirm Password:</label>
            <input type="password" id="confirm_password" name="confirm_password" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500">
        </div>
        <!-- Submit Button -->
        <button type="submit"
                class="w-full py-2 px-4 bg-red-600 text-white font-semibold rounded-md hover:bg-red-700 transition duration-300">Register Administrator</button>
    </form>

    <p class="mt-6 text-center text-gray-600">
        <a href="index.php?page=home" class="text-blue-600 hover:underline">Back to Home</a>
    </p>
</div>
