<?php
include 'config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Join with agencies table to check status
    $stmt = $conn->prepare("SELECT u.*, a.status as agency_status FROM users u JOIN agencies a ON u.agency_id = a.id WHERE u.email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        
        if (password_verify($password, $user['password'])) {
            
            // BLOCK LOGIN IF SUSPENDED
            if ($user['agency_status'] == 'Suspended') {
                header("Location: login.php?error=Your account is suspended. Please contact the administrator.");
                exit();
            }

            $_SESSION['user_id'] = $user['id'];
            $_SESSION['agency_id'] = $user['agency_id'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['user_name'] = $user['name'];

            header("Location: dashboard.php");
            exit();
        } else {
            header("Location: login.php?error=Incorrect Password");
        }
    } else {
        header("Location: login.php?error=User Not Found");
    }
}
?>