<?php
include_once('../includes/config.php');
header('Content-Type: application/json');

try {
    $date = $_GET['date'] ?? date('Y-m-d');
    $range = $_GET['range'] ?? 'today'; // today, 7d, 30d

    $start = $date;
    $end = $date;
    if ($range === '7d') {
        $start = date('Y-m-d', strtotime('-6 days', strtotime($date)));
    } elseif ($range === '30d') {
        $start = date('Y-m-d', strtotime('-29 days', strtotime($date)));
    }

    $statsQuery = "
        SELECT 
            COUNT(*) as orders,
            COALESCE(SUM(TotalAmount),0) as total,
            COALESCE(SUM(PaidAmount),0) as paid,
            COALESCE(SUM(BalanceAmount),0) as balance
        FROM tblpossales
        WHERE SaleDate BETWEEN ? AND ?
    ";
    $stmt = $dbh->prepare($statsQuery);
    $stmt->execute([$start, $end]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $topQuery = "
        SELECT RiceBagName AS ProductName, SUM(psi.Quantity) qty
        FROM tblpossaleitems psi
        JOIN tblpossales ps ON psi.SaleID = ps.ID
        WHERE ps.SaleDate BETWEEN ? AND ?
        GROUP BY ProductID, ProductName
        ORDER BY qty DESC
        LIMIT 5
    ";
    $stmt = $dbh->prepare($topQuery);
    $stmt->execute([$start, $end]);
    $top = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'range' => [$start, $end],
        'stats' => $stats,
        'top_products' => $top
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
