<?php

header('Content-Type: application/json');

require_once __DIR__ . '/../../config/config.php';     
require_once __DIR__ . '/../../lib/Auth.php';          
require_once __DIR__ . '/../../includes/functions.php';

$response = ['success' => false, 'errors' => ['general' => 'Terjadi kesalahan server awal.']];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['errors']['general'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("FATAL Error in login_handler.php: PDO object not available or invalid. Check include order in index.php.");
    $response['errors']['general'] = 'Koneksi database tidak siap.';
    echo json_encode($response);
    exit;
}

try {
    $identifier = sanitize_input($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    $errors = [];
    if (empty($identifier)) { $errors['email'] = "Email atau username wajib diisi."; }
    if (empty($password)) { $errors['password'] = "Password wajib diisi."; }

    if (!empty($errors)) {
        $response['errors'] = $errors;
        echo json_encode($response);
        exit;
    }

    $auth = new Auth($pdo);
    $loginResult = $auth->login($identifier, $password);

    if ($loginResult && is_array($loginResult)) { 
        $response = [
            'success' => true,
            'message' => 'Login berhasil! Mengalihkan...',
            'redirectUrl' => ($loginResult['role'] === 'admin') ? base_url('admin/dashboard') : base_url('dashboard')
        ];
    } else {
        $response['errors']['general'] = 'Login gagal. Email/username atau password salah, atau akun tidak aktif.';
    }

} catch (\Throwable $e) { 
    error_log("AJAX Login Handler Exception: " . $e->getMessage());
    $response['errors']['general'] = "Terjadi kesalahan tak terduga saat login.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['errors']['debug'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
