<?php
session_start();
require_once '../includes/config.php'; // Your DB connection file

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

    if (empty($email) || empty($password)) {
        $_SESSION['message'] = "Email and Password are required.";
        header("Location: login.php");
        exit;
    }

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

    if ($user) {
        if (password_verify($password, $user['password'])) {
            // Password correct, start session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['last_activity'] = time();

            // Redirect based on role
            switch ($user['role']) {
                case 'admin':
                    header("Location: ../admin/dashboard.php");
                    break;
                case 'controller':
                    header("Location: ../controller/dashboard.php");
                    break;
                case 'HR':
                    header("Location: ../hr/dashboard.php");
                    break;
                case 'supervisor':
                    header("Location: ../supervisor/dashboard.php");
                    break;
                case 'officer':
                    header("Location: ../officer/dashboard.php");
                    break;
                default:
                    $_SESSION['message'] = "Role not recognized.";
                    header("Location: login.php");
                    break;
            }
            exit;

        } else {
            // Password incorrect
            $_SESSION['message'] = "Incorrect password.";
            header("Location: login.php");
            exit;
        }
    } else {
        // User not found
        $_SESSION['message'] = "No user found with this email.";
        header("Location: login.php");
        exit;
    }
} else {
    $_SESSION['message'] = "Invalid request.";
    header("Location: login.php");
    exit;
}
?>
