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

$id_agen_voucher = isset($_GET['id']) ? intval($_GET['id']) : 0;
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 25;
$search = isset($_GET['search']) ? $_GET['search'] : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

if ($id_agen_voucher > 0) {
    $data_voucher = [];

    $sql = "SELECT voucher, harga, create_time, active_time, expaired_time
            FROM ganerate_voucher
            WHERE id_agen_voucher = :id_agen_voucher";

    if ($start_date) {
        $sql .= " AND create_time >= :start_date";
    }
    if ($end_date) {
        $sql .= " AND create_time <= :end_date";
    }

    if ($search) {
        $sql .= " AND (
            voucher LIKE :search OR
            DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') LIKE :search OR
            DATE_FORMAT(active_time, '%Y-%m-%d %H:%i:%s') LIKE :search OR
            DATE_FORMAT(expaired_time, '%Y-%m-%d %H:%i:%s') LIKE :search
        )";
    }

    $sql .= " ORDER BY create_time DESC LIMIT :offset, :limit";

    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':id_agen_voucher', $id_agen_voucher, PDO::PARAM_INT);

    if ($start_date) {
        $stmt->bindValue(':start_date', $start_date, PDO::PARAM_STR);
    }
    if ($end_date) {
        $stmt->bindValue(':end_date', $end_date, PDO::PARAM_STR);
    }

    if ($search) {
        $searchTerm = '%' . $search . '%';
        $stmt->bindValue(':search', $searchTerm, PDO::PARAM_STR);
    }

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

    $stmt->execute();
    $data_voucher = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($data_voucher as &$voucher) {
        foreach ($voucher as $key => &$value) {
            if (is_null($value)) {
                $value = '-';
            }
        }
    }

    header('Content-Type: application/json');
    echo json_encode(['data' => $data_voucher]);
} else {
    echo json_encode(['error' => 'Invalid parameters']);
}
?>
