<?php
// Aktifkan error reporting untuk debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Koneksi database
include '../config/connect.php';

try {
    // Parameter dari DataTable
    $start = isset($_GET['start']) ? (int)$_GET['start'] : 0;
    $length = isset($_GET['length']) ? (int)$_GET['length'] : 10;
    $idSv = isset($_GET['idsv']) ? $_GET['idsv'] : '';
    $draw = isset($_GET['draw']) ? (int)$_GET['draw'] : 1;
    $searchValue = $_GET['search']['value'] ?? '';
    $orderColumnIndex = $_GET['order'][0]['column'] ?? 0;
    $orderColumnName = $_GET['columns'][$orderColumnIndex]['data'] ?? 'id';
    $orderDirection = ($_GET['order'][0]['dir'] ?? 'asc') === 'asc' ? 'ASC' : 'DESC';

    // Query utama
    $sql = "SELECT * FROM v_tagihan WHERE $idSv status = 'lunas'";
    $params = [];

    // Filter pencarian
    if (!empty($searchValue)) {
        $sql .= " AND (nama LIKE :search OR akun LIKE :search OR alamat LIKE :search OR verifikasi_tagihan LIKE :search OR tanggal_bayar LIKE :search OR nama_server LIKE :search OR nomor_whatsapp LIKE :search OR nama_paket LIKE :search OR jenis_layanan LIKE :search OR pelunas LIKE :search OR catatan LIKE :search OR keterangan LIKE :search)";
        $params[':search'] = "%$searchValue%";
    }

    // Ambil total data tanpa filter
    $totalQuery = "SELECT COUNT(*) FROM v_tagihan WHERE status = 'lunas'";
    $totalData = $pdo->query($totalQuery)->fetchColumn();

    // Ambil total data setelah filter
    $totalFilteredQuery = "SELECT COUNT(*) FROM ($sql) AS filtered";
    $totalFilteredStmt = $pdo->prepare($totalFilteredQuery);
    foreach ($params as $key => $value) {
        $totalFilteredStmt->bindValue($key, $value);
    }
    $totalFilteredStmt->execute();
    $totalFiltered = $totalFilteredStmt->fetchColumn();

    // Tambahkan pengurutan dan paginasi
    $sql .= " ORDER BY $orderColumnName $orderDirection LIMIT :start, :length";
    $stmt = $pdo->prepare($sql);

    // Bind parameter pencarian
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }

    // Bind limit dan offset
    $stmt->bindValue(':start', $start, PDO::PARAM_INT);
    $stmt->bindValue(':length', $length, PDO::PARAM_INT);

    // Eksekusi query data
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format JSON untuk DataTable
    $response = [
        'draw' => $draw,
        'recordsTotal' => $totalData,
        'recordsFiltered' => $totalFiltered,
        'data' => $data
    ];

    // Output JSON
    header('Content-Type: application/json');
    echo json_encode($response);
} catch (Exception $e) {
    // Tangani error dan kirimkan pesan dalam format JSON
    header('Content-Type: application/json');
    echo json_encode([
        'error' => true,
        'message' => $e->getMessage()
    ]);
}
?>
