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

$status = isset($_GET['status']) ? $_GET['status'] : 'all';
$search = isset($_GET['search']) ? $_GET['search'] : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

$sql = "SELECT a.*, u.actual_name AS unit_name 
        FROM audit_adjustments a
        LEFT JOIN units u ON a.unit_id = u.id
        WHERE 1";

$params = [];

if($status !== 'all'){
    $sql .= " AND adjustment_type = ?";
    $params[] = $status;
}

if(!empty($search)){
    $sql .= " AND (product_name LIKE ? OR voucher_no LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if(!empty($start_date) && !empty($end_date)){
    $sql .= " AND DATE(a.created_at) BETWEEN ? AND ?";
    $params[] = $start_date;
    $params[] = $end_date;
}

$sql .= " ORDER BY a.created_at DESC";

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($data);
?>
