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

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()) {
    http_response_code(401);
    $response['message'] = 'Sesi Anda telah berakhir. Silakan login kembali.';
    echo json_encode($response);
    exit;
}

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

try {
    $userId = $_SESSION['user_id'];

    $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 10, 'min_range' => 5, 'max_range' => 50]]);
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
    $type = $_GET['type'] ?? 'all';
    $category = $_GET['category'] ?? 'all';
    $referenceId = sanitize_input($_GET['reference_id'] ?? '');
    $sortBy = $_GET['sort_by'] ?? 'bl.created_at';
    $sortType = $_GET['sort_type'] ?? 'DESC';

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

    $allowedSortColumns = ['bl.created_at', 'bl.type', 'bl.category', 'bl.amount'];
    $allowedSortTypes = ['ASC', 'DESC'];
    if (!in_array($sortBy, $allowedSortColumns)) { $sortBy = 'bl.created_at'; }
    if (!in_array(strtoupper($sortType), $allowedSortTypes)) { $sortType = 'DESC'; }

    $sqlSelect = "SELECT bl.id, bl.type, bl.category, bl.amount, bl.balance_after, bl.description, bl.reference_id, bl.created_at ";
    $sqlFrom = "FROM balance_logs bl ";
    $sqlWhereBase = "WHERE bl.user_id = :user_id ";
    $params = [':user_id' => $userId];
    $whereClauses = [];

    if ($type !== 'all' && in_array($type, ['credit', 'debit'])) {
        $whereClauses[] = "bl.type = :type";
        $params[':type'] = $type;
    }
    if ($category !== 'all' && in_array($category, ['deposit', 'order_placement', 'order_refund', 'admin_adjustment', 'other'])) {
        $whereClauses[] = "bl.category = :category";
        $params[':category'] = $category;
    }
    if (!empty($referenceId)) {
        $whereClauses[] = "bl.reference_id LIKE :reference_id";
        $params[':reference_id'] = '%' . $referenceId . '%';
    }

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

    $totalItems = 0;
    $totalPages = 1;
    $sqlCount = "SELECT COUNT(bl.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') {
            $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("User Get Balance History DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("User Get Balance History 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;
?>
