<?php
require_once 'auth.php';
include 'db.php';

$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$remember = isset($_POST['remember']) && $_POST['remember'] == '1';
$redirect = trim((string) ($_POST['redirect'] ?? ''));

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || $email === '' || $password === '') {
    logActivityGuest($conn, 'login_failed', 'Login failed - incomplete request payload');
    header("Location: login.php?error=empty");
    exit();
}

$sql = "SELECT id, fullname, short_name, email, department, password, status, role FROM users WHERE email = ?";
$stmt = mysqli_prepare($conn, $sql);

if (!$stmt) {
    logActivityGuest($conn, 'login_failed', "System error preparing login statement for email: $email");
    header("Location: login.php?error=system");
    exit();
}

mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if ($user = mysqli_fetch_assoc($result)) {
    if (password_verify($password, $user['password'])) {
        if ($user['status'] === 'pending') {
            logActivity($conn, $user['id'], 'login_pending', "Login attempt with pending account: $email");
            header("Location: login.php?error=pending");
            exit();
        }

        if ($user['status'] === 'rejected') {
            logActivity($conn, $user['id'], 'login_rejected', "Login attempt with rejected account: $email");
            header("Location: login.php?error=rejected");
            exit();
        }

        session_regenerate_id(true);

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['fullname'] = $user['fullname'];
        $_SESSION['short_name'] = trim((string) ($user['short_name'] ?? ''));
        $_SESSION['email'] = $user['email'];
        $_SESSION['department'] = $user['department'];
        $_SESSION['logged_in'] = true;
        $_SESSION['role'] = $user['role'];
        $_SESSION['last_activity'] = time();

        $update_last_login = mysqli_prepare($conn, "UPDATE users SET last_login = NOW() WHERE id = ?");
        if ($update_last_login) {
            mysqli_stmt_bind_param($update_last_login, "i", $user['id']);
            mysqli_stmt_execute($update_last_login);
        }

        logActivity($conn, $user['id'], 'login', "User berjaya login ke sistem");

        if ($remember) {
            setcookie("user_email", $email, [
                'expires' => time() + (86400 * 30),
                'path' => '/',
                'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') === '443'),
                'httponly' => true,
                'samesite' => 'Lax',
            ]);
            setcookie("user_password", "", time() - 3600, "/");
        } else {
            setcookie("user_email", "", time() - 3600, "/");
            setcookie("user_password", "", time() - 3600, "/");
        }

        if ($redirect !== '' && strpos($redirect, '://') === false && strpos($redirect, '\\') === false) {
            header("Location: " . ltrim($redirect, '/'));
        } else {
            header("Location: dashboard.php");
        }
        exit();
    }

    logActivity($conn, $user['id'], 'login_failed', "Login failed - wrong password for email: $email");
    header("Location: login.php?error=wrong_password");
    exit();
}

logActivityGuest($conn, 'login_failed', "Login failed - email not found: $email");
header("Location: login.php?error=notfound");
exit();
?>
