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

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$shiftId = isset($_GET['shift_id']) ? intval($_GET['shift_id']) : null;

$response = [
    'total_sales' => 0,
    'total_items' => 0,
    'average_sale' => 0,
    'total_transactions' => 0,
    'total_expenses' => 0,
    'top_expense_name' => '',
    'top_expense_amount' => 0,
    'hourly_labels' => [],
    'hourly_sales' => []
];

// Sales summary
$querySales = "SELECT 
                SUM(tr.total) AS total_sales,
                COUNT(DISTINCT tr.trans_id) AS total_transactions,
                SUM(s.quantity) AS total_items,
                AVG(tr.total) AS average_sale
              FROM transaction_receipts tr
              JOIN sales s ON tr.trans_id = s.trans_id
              WHERE DATE(tr.seller_date) = '$date'";

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

$resultSales = $conn->query($querySales);
if ($row = $resultSales->fetch_assoc()) {
    $response['total_sales'] = floatval($row['total_sales'] ?: 0);
    $response['total_items'] = intval($row['total_items'] ?: 0);
    $response['average_sale'] = floatval($row['average_sale'] ?: 0);
    $response['total_transactions'] = intval($row['total_transactions'] ?: 0);
}

// Expenses summary
$queryExpenses = "SELECT 
                    SUM(expense_amount) AS total_expenses,
                    expense_name,
                    MAX(expense_amount) AS top_expense_amount
                  FROM expenses
                  WHERE date_incurred = '$date'";

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

$queryExpenses .= " GROUP BY expense_name ORDER BY top_expense_amount DESC LIMIT 1";

$resultExpenses = $conn->query($queryExpenses);
if ($row = $resultExpenses->fetch_assoc()) {
    $response['total_expenses'] = floatval($row['total_expenses'] ?: 0);
    $response['top_expense_name'] = $row['expense_name'] ?: '';
    $response['top_expense_amount'] = floatval($row['top_expense_amount'] ?: 0);
}

// Hourly sales data
for ($hour = 0; $hour < 24; $hour++) {
    $hourStart = sprintf('%02d:00:00', $hour);
    $hourEnd = sprintf('%02d:59:59', $hour);
    
    $queryHourly = "SELECT SUM(total) AS hourly_total
                    FROM transaction_receipts
                    WHERE DATE(seller_date) = '$date'
                    AND TIME(seller_date) BETWEEN '$hourStart' AND '$hourEnd'";
    
    if ($shiftId) {
        $queryHourly .= " AND shift_id = $shiftId";
    }
    
    $resultHourly = $conn->query($queryHourly);
    $hourlyTotal = $resultHourly->fetch_assoc()['hourly_total'] ?: 0;
    
    $response['hourly_labels'][] = sprintf('%02d:00', $hour);
    $response['hourly_sales'][] = floatval($hourlyTotal);
}

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