<?php
include 'db.php';
$year = intval($_GET['year'] ?? date('Y'));

// Initialize months
$monthly = [];
for($i=1;$i<=12;$i++) $monthly[$i]=0;

// Get monthly totals
$stmt = $pdo->prepare("SELECT MONTH(inv_date) AS month, SUM(total_price) AS sum_month FROM transactions WHERE terms='Cash' AND YEAR(inv_date)=? GROUP BY MONTH(inv_date)");
$stmt->execute([$year]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $monthly[$row['month']] = floatval($row['sum_month']);
}

// Total year
$total_year = array_sum($monthly);

// Average monthly (only months with data)
$months_with_data = count(array_filter($monthly));
$avg_year = $months_with_data ? $total_year / $months_with_data : 0;

// Last 6 FULL months total & average (month-based, excluding current month)
$last6 = $pdo->prepare("
    SELECT SUM(total_price) AS sum_last6
    FROM transactions
    WHERE terms = 'Cash'
      AND inv_date >= DATE_SUB(
            DATE_FORMAT(CURDATE(), '%Y-%m-01'),
            INTERVAL 6 MONTH
          )
      AND inv_date < DATE_FORMAT(CURDATE(), '%Y-%m-01')
");

$last6->execute();
$total_6month = floatval($last6->fetchColumn());
$avg_6month = $total_6month / 6;


echo json_encode([
    'monthly'=>$monthly,
    'total_year'=>$total_year,
    'avg_year'=>$avg_year,
    'total_6month'=>$total_6month,
    'avg_6month'=>$avg_6month
]);
?>
