<?php
session_start();
require_once 'includes/User.php';
require_once 'includes/db_config.php';

$err = '';

if (User::isLoggedIn()) { 
    header("Location: /allura/home.php"); 
    exit(); 
}

if (isset($_SESSION['staff_id'])) {
    header('Location: /allura/delivery/dashboard.php');
    exit;
}

if (isset($_SESSION['laundry_staff_id'])) {
    header('Location: /allura/laundry/dashboard.php');
    exit;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $em = $_POST["email"] ?? '';
    $pw = $_POST["password"] ?? '';
    
    if (empty($em) || empty($pw)) {
        $err = "Please fill in all fields";
    } else {
        $u = new User();
        $res = $u->login($em, $pw);
        
        if ($res['success']) {
            if ($res['role'] === 'admin') { 
                header("Location: /allura/admin/admin.php"); 
            } else { 
                header("Location: /allura/home.php"); 
            }
            exit();
        } else {
            try {
                $pdo = getDBConnection();
                
                $stmt = $pdo->prepare("SELECT id, name, email, password, status FROM delivery_staff WHERE email = ?");
                $stmt->execute([$em]);
                $staff = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($staff && password_verify($pw, $staff['password'])) {
                    $_SESSION['staff_id'] = $staff['id'];
                    $_SESSION['staff_name'] = $staff['name'];
                    $_SESSION['staff_email'] = $staff['email'];
                    $_SESSION['staff_status'] = $staff['status'];
                    
                    $stmt = $pdo->prepare("UPDATE delivery_staff SET last_login = NOW() WHERE id = ?");
                    $stmt->execute([$staff['id']]);
                    
                    header('Location: /allura/delivery/dashboard.php');
                    exit;
                }
                
                $stmt = $pdo->prepare("SELECT id, name, email, password, status FROM laundry_staff WHERE email = ?");
                $stmt->execute([$em]);
                $laundry = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($laundry && password_verify($pw, $laundry['password'])) {
                    $_SESSION['laundry_staff_id'] = $laundry['id'];
                    $_SESSION['laundry_staff_name'] = $laundry['name'];
                    $_SESSION['laundry_staff_email'] = $laundry['email'];
                    $_SESSION['laundry_staff_status'] = $laundry['status'];
                    
                    $stmt = $pdo->prepare("UPDATE laundry_staff SET last_login = NOW() WHERE id = ?");
                    $stmt->execute([$laundry['id']]);
                    
                    header('Location: /allura/laundry/dashboard.php');
                    exit;
                }
                
                $err = "Invalid email or password";
            } catch (PDOException $e) {
                $err = "Database connection error";
            }
        }
    }
}

$reg = isset($_GET['registered']) && $_GET['registered'] == 1;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login - Allura Dry Clean</title>
    <?php include 'includes/header.php'; ?>
</head>
<body>
    <div class="login-box">
        <h2>Login</h2>
        
        <?php if ($reg): ?>
            <p class="success-message">Registration successful! Please login.</p>
        <?php endif; ?>
        
        <?php if (!empty($err)): ?>
            <p class="error-message"><?php echo htmlspecialchars($err); ?></p>
        <?php endif; ?>
        
        <form method="POST" action="">
            <input type="email" name="email" placeholder="Enter your email" required><br>
            <input type="password" name="password" placeholder="Enter your password" required><br>
            <button type="submit" class="btn">Login</button>
        </form>
        
        <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee;">
            <p class="register-text">
                Don't have an account? 
                <a href="/allura/register.php">Register here</a>
            </p>
        </div>
    </div>
    <?php include 'includes/footer.php'; ?>
</body>
</html>