<?php
require_once './shikanisha.kts.php';

$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : null;
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : null;
$shiftId = isset($_GET['shift_id']) ? intval($_GET['shift_id']) : null;

$query = "SELECT 
            expense_name,
            expense_amount,
            date_incurred,
            shift_id
          FROM expenses
          WHERE 1=1";

if ($dateFrom && $dateTo) {
    $query .= " AND date_incurred BETWEEN '$dateFrom' AND '$dateTo'";
} elseif ($dateFrom) {
    $query .= " AND date_incurred >= '$dateFrom'";
} elseif ($dateTo) {
    $query .= " AND date_incurred <= '$dateTo'";
}

if ($shiftId) {
    $query .= " AND shift_id = $shiftId";
}

$query .= " ORDER BY date_incurred DESC";

$result = $conn->query($query);
$data = [];

while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

header('Content-Type: application/json');
echo json_encode($data);
?>