<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
$userId = as_int(get_query('user_id'));
require_user($userId);
$startDate = get_query('start_date', date('Y-m-d', strtotime('-6 days')));
$endDate = get_query('end_date', date('Y-m-d'));
$itemName = get_query('item_name');
if (!valid_date($startDate) || !valid_date($endDate)) {
    respond(['success' => false, 'message' => 'Invalid date format. Use YYYY-MM-DD.'], 400);
}
if ($startDate > $endDate) {
    respond(['success' => false, 'message' => 'Start date cannot be later than end date.'], 400);
}
$conn = db();
$sql = "SELECT s.id AS sale_id, s.receipt_no, s.sale_datetime, si.item_name, si.sku, si.quantity, si.price, si.line_total, s.cashier_name, s.total_amount AS sale_total
        FROM sales s
        INNER JOIN sale_items si ON si.sale_id = s.id
        WHERE " . sales_active_where_sql('s') . " AND DATE(s.sale_datetime) BETWEEN ? AND ?";
$params = [$startDate, $endDate];
$types = 'ss';
if ($itemName !== '') {
    $sql .= " AND (si.item_name LIKE ? OR si.sku LIKE ? )";
    $like = '%' . $itemName . '%';
    $params[] = $like;
    $params[] = $like;
    $types .= 'ss';
}
$sql .= " ORDER BY s.sale_datetime DESC, s.id DESC, si.item_name ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
$saleIds = [];
$totalSales = 0.0;
$totalQuantity = 0;
while ($row = $result->fetch_assoc()) {
    $rows[] = [
        'sale_id' => (int)$row['sale_id'],
        'receipt_no' => $row['receipt_no'],
        'sale_datetime' => $row['sale_datetime'],
        'item_name' => $row['item_name'],
        'sku' => $row['sku'],
        'quantity' => (int)$row['quantity'],
        'price' => (float)$row['price'],
        'line_total' => (float)$row['line_total'],
        'cashier_name' => $row['cashier_name'],
        'sale_total' => (float)$row['sale_total'],
    ];
    $saleIds[(int)$row['sale_id']] = true;
    $totalSales += (float)$row['line_total'];
    $totalQuantity += (int)$row['quantity'];
}
respond([
    'success' => true,
    'data' => [
        'summary' => [
            'total_sales' => $totalSales,
            'total_orders' => count($saleIds),
            'total_lines' => count($rows),
            'total_quantity' => $totalQuantity,
            'from_date' => $startDate,
            'to_date' => $endDate,
            'item_name' => $itemName !== '' ? $itemName : null,
            'generated_at' => date('Y-m-d H:i:s'),
        ],
        'rows' => $rows,
    ],
]);
