<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

ob_start();

function respond(int $status_code, array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($status_code);
    echo json_encode($payload);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    respond(204, []);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, [
        'success' => false,
        'message' => 'Method tidak dibenarkan.',
    ]);
}

require_once __DIR__ . '/../db.php';

$raw = file_get_contents('php://input');
$payload = json_decode($raw ?: '', true);

if (!is_array($payload)) {
    $payload = $_POST;
}

$email = strtolower(trim((string) ($payload['email'] ?? '')));
$password = (string) ($payload['password'] ?? '');

if ($email === '' || $password === '') {
    respond(422, [
        'success' => false,
        'message' => 'Sila masukkan emel dan kata laluan.',
    ]);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    respond(422, [
        'success' => false,
        'message' => 'Format emel tidak sah.',
    ]);
}

$stmt = mysqli_prepare(
    $conn,
    'SELECT id, fullname, short_name, ic_number, email, department, password, status, role, position, signature_path, profile_photo, last_login
     FROM users
     WHERE email = ?
     LIMIT 1'
);

if (!$stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa menyediakan login.',
    ]);
}

mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = $result ? mysqli_fetch_assoc($result) : null;

if (!$user || !password_verify($password, (string) $user['password'])) {
    if ($user) {
        logActivity($conn, (int) $user['id'], 'mobile_login_failed', "Mobile login failed - wrong password for email: {$email}");
    } else {
        logActivityGuest($conn, 'mobile_login_failed', "Mobile login failed - email not found: {$email}");
    }

    respond(401, [
        'success' => false,
        'message' => 'Emel atau kata laluan tidak tepat.',
    ]);
}

$status = (string) ($user['status'] ?? '');
if ($status === 'pending') {
    logActivity($conn, (int) $user['id'], 'mobile_login_pending', "Mobile login attempt with pending account: {$email}");
    respond(403, [
        'success' => false,
        'message' => 'Akaun anda masih menunggu kelulusan pentadbir.',
    ]);
}

if ($status === 'rejected') {
    logActivity($conn, (int) $user['id'], 'mobile_login_rejected', "Mobile login attempt with rejected account: {$email}");
    respond(403, [
        'success' => false,
        'message' => 'Akaun anda telah ditolak. Sila hubungi pentadbir sistem.',
    ]);
}

if ($status !== 'approved') {
    respond(403, [
        'success' => false,
        'message' => 'Status akaun tidak aktif.',
    ]);
}

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

logActivity($conn, (int) $user['id'], 'mobile_login', 'User berjaya login melalui aplikasi mobile');

respond(200, [
    'success' => true,
    'message' => 'Login berjaya.',
    'user' => [
        'id' => (int) $user['id'],
        'fullname' => (string) ($user['fullname'] ?? ''),
        'shortName' => (string) ($user['short_name'] ?? ''),
        'identityCard' => (string) ($user['ic_number'] ?? ''),
        'email' => (string) ($user['email'] ?? ''),
        'department' => (string) ($user['department'] ?? ''),
        'role' => (string) ($user['role'] ?? 'user'),
        'position' => (string) ($user['position'] ?? ''),
        'signaturePath' => (string) ($user['signature_path'] ?? ''),
        'profileImage' => (string) ($user['profile_photo'] ?? ''),
    ],
]);
