<?php
// Include database configuration
include('../../config/database.php');
session_start();

// Initialize variables
$username = $password = '';
$errors = [];

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate input
    if (empty($username)) $errors[] = "Username is required";
    if (empty($password)) $errors[] = "Password is required";

    // Check for errors
    if (count($errors) == 0) {
        // Fetch admin from the database
        $sql = "SELECT * FROM admin WHERE username = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows == 1) {
                $row = $result->fetch_assoc();
                // Verify password
                if (password_verify($password, $row['password'])) {
                    // Store admin information in session
                    $_SESSION['admin_id'] = $row['id'];
                    $_SESSION['admin_username'] = $row['username'];
                    header("Location: assign.php"); // Change to the appropriate page
                    exit();
                } else {
                    $errors[] = "Invalid password.";
                }
            } else {
                $errors[] = "Invalid username.";
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Unable to prepare statement.";
        }
    }
}

$conn->close();
?>

<?php include('../../includes/header.php'); ?>
<div class="container mt-5 d-flex justify-content-center">
    <div class="card" style="width: 50%;">
        <div class="card-body">
            <h1 class="mb-4 text-center">Admin Login</h1>

            <?php if (!empty($errors)) : ?>
                <div class="alert alert-danger">
                    <?php foreach ($errors as $error) : ?>
                        <p><?php echo $error; ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="login.php">
                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>">
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" class="form-control" id="password" name="password">
                </div>
                <button type="submit" class="btn btn-black" style="background-color: #2c2b7c; color: #fff; border-radius: 0;">Login</button>
            </form>
        </div>
    </div>
</div>
<?php include('../../includes/footer.php'); ?>
