<?php
// load_data.php
include '../config/connect.php';

$offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
$limit = 15; // Jumlah data per permintaan
$search = isset($_GET['search']) ? $_GET['search'] : '';
$startDate = ($_GET['start_date'] != '') ? $_GET['start_date'].' 00:00:00' : '';
$endDate = ($_GET['end_date'] != '') ? $_GET['end_date'].' 23:59:59' : '';
$id_data_server = isset($_GET['ids']) ? $_GET['ids'] : '';

// Siapkan query SQL
$query = "SELECT id, nama_server, start_time, keterangan, pemasukan, pengeluaran, status, metode_pembayaran, bukti_pembayaran, nama FROM v_transaksi WHERE 1=1 AND id_data_server IN ($id_data_server)";

// Tambahkan kondisi pencarian
if (!empty($search)) {
    $query .= " AND (nama_server LIKE :search OR start_time LIKE :search OR keterangan LIKE :search OR pemasukan LIKE :search OR pengeluaran LIKE :search OR metode_pembayaran LIKE :search OR status LIKE :search)";
}

// Tambahkan kondisi untuk filter tanggal
if (!empty($startDate)) {
    $query .= " AND start_time >= :startDate";
}
if (!empty($endDate)) {
    $query .= " AND start_time <= :endDate";
}

$query .= " ORDER BY start_time DESC, id DESC LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($query);

// Bind parameter pencarian
if (!empty($search)) {
    $stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}

// Bind parameter filter tanggal
if (!empty($startDate)) {
    $stmt->bindValue(':startDate', $startDate, PDO::PARAM_STR);
}
if (!empty($endDate)) {
    $stmt->bindValue(':endDate', $endDate, PDO::PARAM_STR);
}

$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totalRows = $stmt->rowCount();

echo json_encode(['data' => $data, 'total' => $totalRows]);
?>
