<?php
session_start();
require_once('../config.php');

$error = '';
$requested_role = isset($_GET['role']) ? $_GET['role'] : '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $email = trim($_POST['email']);
    $password = $_POST['password'];

    try {

        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $error = "Invalid email or password.";
        } else {
            // Check password - handle both hashed (new) and plain text (old database entries)
            $password_matches = password_verify($password, $user['password']);
            
            // Fallback for direct database entries with plain text passwords
            if (!$password_matches && $password === $user['password']) {
                $password_matches = true;
                // Proactively hash the plain text password for better security next time
                $new_hash = password_hash($password, PASSWORD_DEFAULT);
                $update_stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                $update_stmt->execute([$new_hash, $user['id']]);
            }

            if (!$password_matches) {
                $error = "Invalid email or password.";
            } else {

                if (!empty($requested_role) && $user['role'] !== $requested_role) {
                    $error = "Access denied.";
                }
                elseif ($user['status'] !== 'accepted') {
                    $error = "Your account is not approved yet.";
                }
                else {

                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['role'] = $user['role'];

                    // All roles go to dashboard.php which handles role-specific views
                    header("Location: dashboard.php");
                    exit();
                }
            }
        }

    } catch (PDOException $e) {
        $error = "Database error.";
    }
}

include('../header/header.php');
?>

<div class="container py-5 min-vh-100 d-flex align-items-center">
    <div class="row w-100 justify-content-center">
        <div class="col-md-5 col-lg-4">
            <div class="card glass-card border-0 p-4 animate__animated animate__fadeInUp">
                <div class="text-center mb-4">
                    <img src="../images/logo.png" alt="Logo" class="rounded-circle shadow-sm mb-3" style="height: 80px;">
                    <h3 class="fw-bold">
                        <?php echo !empty($requested_role) ? ucfirst($requested_role) . " Login" : "Login"; ?>
                    </h3>
                    <p class="text-muted small">Enter your credentials to access your account</p>
                </div>

                <?php if ($error): ?>
                    <div class="alert alert-danger border-0 shadow-sm mb-4">
                        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
                    </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label fw-medium small">Email Address</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 rounded-start-3"><i class="fas fa-envelope text-muted"></i></span>
                            <input type="email" name="email" class="form-control bg-light border-start-0 rounded-end-3" placeholder="name@example.com" required>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-medium small">Password</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 rounded-start-3"><i class="fas fa-lock text-muted"></i></span>
                            <input type="password" name="password" class="form-control bg-light border-start-0 rounded-end-3" placeholder="••••••••" required>
                        </div>
                    </div>

                    <button class="btn btn-primary w-100 py-3 shadow-sm mb-3">
                        <i class="fas fa-sign-in-alt me-2"></i> Login
                    </button>
                </form>

                <div class="text-center mt-2">
                    <p class="small text-muted mb-0">Don't have an account? <a href="signup.php" class="text-primary fw-bold text-decoration-none">Sign up here</a></p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('../footer/footer.php'); ?>