<?php
header('Content-Type: application/json');
$response = ['success' => false, 'logs' => [], 'pagination' => null, 'message' => 'Gagal memuat data log masuk.'];

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

if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    $response['message'] = 'Akses ditolak.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in get_admin_login_logs.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

try {
    $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 15, 'min_range' => 5, 'max_range' => 100]]);
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
    $status = $_GET['status'] ?? 'all';
    $userIdFilter = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
    $ipAddressFilter = sanitize_input($_GET['ip_address'] ?? '');
    $sortBy = $_GET['sort_by'] ?? 'll.login_at';
    $sortType = $_GET['sort_type'] ?? 'DESC';
    $searchColumn = $_GET['search_column'] ?? 'll.id';
    $searchKeyword = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';

    $offset = ($page - 1) * $limit;

    $allowedSortColumns = ['ll.login_at', 'll.id', 'u.username', 'll.username_attempt', 'll.ip_address', 'll.status'];
    $allowedSortTypes = ['ASC', 'DESC'];
    if (!in_array($sortBy, $allowedSortColumns)) { $sortBy = 'll.login_at'; }
    if (!in_array(strtoupper($sortType), $allowedSortTypes)) { $sortType = 'DESC'; }
    
    $allowedSearchColumns = ['ll.id', 'u.username', 'll.username_attempt', 'll.ip_address', 'll.user_agent', 'll.location_info'];
    if (!in_array($searchColumn, $allowedSearchColumns)) { $searchColumn = 'll.id'; }


    $sqlSelect = "SELECT ll.id, ll.user_id, IFNULL(u.username, '[N/A]') as username, ll.username_attempt, ll.ip_address, 
                         ll.user_agent, ll.device_type, ll.browser_name, ll.platform_name, ll.location_info, ll.status, ll.login_at ";
    $sqlFrom = "FROM login_logs ll LEFT JOIN users u ON ll.user_id = u.id ";
    $sqlWhereBase = "WHERE 1=1 ";
    $params = [];
    $whereClauses = [];

    if ($status !== 'all' && in_array($status, ['success', 'failed_password', 'failed_username', 'admin_impersonate_start', 'admin_impersonate_end'])) {
        $whereClauses[] = "ll.status = :status";
        $params[':status'] = $status;
    }
    if ($userIdFilter) {
        $whereClauses[] = "ll.user_id = :user_id_filter";
        $params[':user_id_filter'] = $userIdFilter;
    }
    if (!empty($ipAddressFilter)) {
        $whereClauses[] = "ll.ip_address = :ip_address_filter";
        $params[':ip_address_filter'] = $ipAddressFilter;
    }
    if (!empty($searchKeyword)) {
        if ($searchColumn === 'll.id') {
             if (is_numeric($searchKeyword)) {
                $whereClauses[] = $searchColumn . " = :search_keyword_id";
                $params[':search_keyword_id'] = (int)$searchKeyword;
            } else { $whereClauses[] = "1=0"; } // No result if not numeric for ID
        } else {
            $whereClauses[] = $searchColumn . " LIKE :search_keyword_like";
            $params[':search_keyword_like'] = '%' . $searchKeyword . '%';
        }
    }

    $sqlWhere = $sqlWhereBase . (!empty($whereClauses) ? " AND " . implode(" AND ", $whereClauses) : "");

    $totalItems = 0;
    $totalPages = 1;
    $sqlCount = "SELECT COUNT(ll.id) " . $sqlFrom . $sqlWhere;
    $stmtCount = $pdo->prepare($sqlCount);
    $stmtCount->execute($params);
    $totalItems = (int)$stmtCount->fetchColumn();
    $totalPages = $totalItems > 0 ? ceil($totalItems / $limit) : 1;

    if ($page > $totalPages && $totalPages > 0) {
        $page = $totalPages;
        $offset = ($page - 1) * $limit;
    } elseif ($page < 1) {
        $page = 1;
        $offset = 0;
    }

    $logs = [];
    $sqlData = $sqlSelect . $sqlFrom . $sqlWhere . " ORDER BY {$sortBy} {$sortType} LIMIT :limit OFFSET :offset";
    $stmtData = $pdo->prepare($sqlData);

    foreach ($params as $key => &$value) {
        if ($key === ':user_id_filter' || $key === ':search_keyword_id') {
            $stmtData->bindValue($key, $value, PDO::PARAM_INT);
        } else {
            $stmtData->bindValue($key, $value);
        }
    }
    unset($value);

    $stmtData->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmtData->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmtData->execute();
    $logs = $stmtData->fetchAll(PDO::FETCH_ASSOC);

    $response['success'] = true;
    $response['logs'] = $logs;
    $response['pagination'] = [
        'totalItems' => $totalItems,
        'totalPages' => $totalPages,
        'currentPage' => $page,
        'limit' => $limit,
        'offset' => $offset
    ];
    unset($response['message']);

} catch (\PDOException $e) {
    error_log("Admin Get Login Logs DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("Admin Get Login Logs General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
