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

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 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_deposit_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' => 100]]);
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
    $status = $_GET['status'] ?? 'all';
    $sortBy = $_GET['sort_by'] ?? 'd.created_at';
    $sortType = $_GET['sort_type'] ?? 'DESC';
    $searchKeyword = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? ''; // Untuk deposit_id
    $dateStart = $_GET['date_start'] ?? '';
    $dateEnd = $_GET['date_end'] ?? '';

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

    $allowedSortColumns = ['d.created_at', 'd.deposit_id', 'dm.name', 'd.amount', 'd.received_amount', 'd.status'];
    if (!in_array($sortBy, $allowedSortColumns)) {
        $sortBy = 'd.created_at';
    }
    $allowedSortTypes = ['ASC', 'DESC'];
    if (!in_array(strtoupper($sortType), $allowedSortTypes)) {
        $sortType = 'DESC';
    }

    $sqlSelect = "SELECT d.id, d.deposit_id, d.paydisini_unique_code, d.amount, d.bonus, d.received_amount, d.status, d.created_at, d.updated_at, dm.name as method_name, dm.logo_url as method_logo ";
    $sqlFrom = "FROM deposits d JOIN deposit_methods dm ON d.deposit_method_id = dm.id ";
    $sqlWhereBase = "WHERE d.user_id = :user_id ";
    $params = [':user_id' => $userId];
    $whereClauses = [];

    if ($status !== 'all') {
        $validStatuses = ['pending', 'processing', 'success', 'failed', 'expired', 'canceled']; // Sesuaikan dengan status Anda
        if (in_array($status, $validStatuses)) {
            $whereClauses[] = "d.status = :status";
            $params[':status'] = $status;
        }
    }

    if (!empty($searchKeyword)) {
        $whereClauses[] = "d.deposit_id LIKE :search_keyword";
        $params[':search_keyword'] = '%' . $searchKeyword . '%';
    }

    if (!empty($dateStart) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateStart)) {
        $whereClauses[] = "DATE(d.created_at) >= :date_start";
        $params[':date_start'] = $dateStart;
    }
    if (!empty($dateEnd) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateEnd)) {
        $whereClauses[] = "DATE(d.created_at) <= :date_end";
        $params[':date_end'] = $dateEnd;
    }

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

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

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

    $deposits = [];
    $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();
    $deposits = $stmtData->fetchAll(PDO::FETCH_ASSOC);

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

} catch (\PDOException $e) {
    error_log("AJAX Get Deposit History DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat memuat riwayat deposit.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("AJAX Get Deposit 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;
?>
