<?php
include "../../config/connect.php";

session_start();

try {
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $search = isset($_GET['search']) ? $_GET['search'] : '';

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

    // Query using PDO
    $query = "
        SELECT * FROM v_ganerate_voucher 
        WHERE id_agen_voucher = :id AND active_time IS NOT NULL 
        AND (voucher LIKE :search OR create_time LIKE :search OR nama_paket LIKE :search)
        ORDER BY nama_paket ASC, create_time DESC, id DESC
        LIMIT :limit OFFSET :offset
    ";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $_SESSION['agen'], PDO::PARAM_INT);
    $stmt->bindValue(':search', "%$search%", 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);

    // Return JSON response
    echo json_encode(['vouchers' => $data]);
} catch (Exception $e) {
    // Handle any errors and return a JSON error response
    echo json_encode(['error' => 'Something went wrong: ' . $e->getMessage()]);
}

?>
