<?php
require 'includes/db_connect.php';
require_once 'includes/session.php';

$error = '';

if (isset($_POST['login'])) {

    $email = strtolower(trim($_POST['email']));
    $password = md5($_POST['password']); // matches your current DB

    // Prepare query
    $stmt = $conn->prepare("SELECT id, email FROM admin WHERE email = ? AND password = ?");
    $stmt->bind_param("ss", $email, $password);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {

        $admin = $result->fetch_assoc();

        // ✅ SET SESSIONS ONLY ON SUCCESS
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_email'] = $admin['email'];

        header("Location: dashboard.php");
        exit;

    } else {
        $error = "❌ Invalid email or password";
    }
}
?>

<?php include 'includes/header.php'; ?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-4">

            <?php if (!empty($error)) : ?>
                <div class="alert alert-danger text-center">
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <div class="card shadow">
                <div class="card-header text-center text-white" style="background-color: orange;">
                    <h5>Admin Login</h5>
                </div>
                <div class="card-body">
                    <form method="POST" autocomplete="off">
                        <div class="mb-3">
                            <label>Email</label>
                            <input type="email" name="email" class="form-control" required />
                        </div>
                        <div class="mb-3">
                            <label>Password</label>
                            <input type="password" name="password" class="form-control" required />
                        </div>
                        <button type="submit" name="login" class="btn w-100" style="background-color: orange; color: white;">
                            Login
                        </button>
                    </form>
                </div>
            </div>

        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
