<?php
include('connectioni.php');

if (isset($_POST['year'])) {
    $selectedYear = intval($_POST['year']);
    
    // Generate monthly sales data for the selected year
    $sqlMonthlySales = "
        SELECT 
            MONTH(STR_TO_DATE(SDATE, '%Y-%m-%d')) AS month,
            SUM(GRAND_TOT) AS total
        FROM s_salma
        WHERE 
            YEAR(STR_TO_DATE(SDATE, '%Y-%m-%d')) = $selectedYear
            AND (CANCELL != '1' OR CANCELL IS NULL)
        GROUP BY month
        ORDER BY month
    ";
    
    $resultMonthlySales = mysqli_query($dbinv, $sqlMonthlySales);
    
    // Initialize an array with 12 months = 0
    $monthlySales = array_fill(1, 12, 0.0);
    
    while ($row = mysqli_fetch_assoc($resultMonthlySales)) {
        $monthNum = intval($row['month']);
        $monthlySales[$monthNum] = floatval($row['total']);
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode([
        'monthlySales' => array_values($monthlySales),
        'year' => $selectedYear
    ]);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Year parameter is required']);
}
?>
