<?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;

// Get expense categories for pie chart
$query = "SELECT 
            expense_name,
            SUM(expense_amount) AS total_amount
          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 .= " GROUP BY expense_name ORDER BY total_amount DESC LIMIT 6";

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

while ($row = $result->fetch_assoc()) {
    $labels[] = $row['expense_name'];
    $data[] = floatval($row['total_amount']);
}

$response = [
    'labels' => $labels,
    'data' => $data
];

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