<?php
// summary_report_ajax.php — returns JSON for the summary report

require 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');

$department = trim($_GET['department'] ?? '');
$year       = filter_input(INPUT_GET, 'year', FILTER_VALIDATE_INT);

if (!$year) {
    echo json_encode(['error' => 'Invalid year']);
    exit;
}

// ── Monthly totals ───────────────────────────────────────────
$whereClause = 'WHERE YEAR(inv_date) = :year';
$params      = ['year' => $year];

if ($department !== '') {
    $whereClause .= ' AND department = :dept';
    $params['dept'] = $department;
}

$stmt = $pdo->prepare("
    SELECT MONTH(inv_date) AS month, SUM(total_price) AS total
    FROM transactions
    $whereClause
    GROUP BY MONTH(inv_date)
");
$stmt->execute($params);

$monthlyTotals = array_fill(1, 12, 0.0);
foreach ($stmt->fetchAll() as $row) {
    $monthlyTotals[(int)$row['month']] = (float)$row['total'];
}

// ── Grand total & average ────────────────────────────────────
$grandTotal = array_sum($monthlyTotals);
$currentYear  = (int)date('Y');
$currentMonth = (int)date('n');
$divisor      = ($year === $currentYear) ? $currentMonth : 12;
$averageMonthly = $divisor > 0 ? $grandTotal / $divisor : 0;

// ── Previous 6-month average ─────────────────────────────────
$prevParams = ['dept' => $department];
$prevDeptClause = $department !== '' ? 'AND department = :dept' : '';
if ($department === '') $prevParams = [];

$prevStmt = $pdo->prepare("
    SELECT COALESCE(SUM(total_price), 0)
    FROM transactions
    WHERE inv_date >= DATE_SUB(DATE_FORMAT(CURDATE(), '%Y-%m-01'), INTERVAL 6 MONTH)
      AND inv_date <  DATE_FORMAT(CURDATE(), '%Y-%m-01')
      $prevDeptClause
");
$prevStmt->execute($prevParams);
$prevSixTotal   = (float)$prevStmt->fetchColumn();
$prevSixAvg     = round($prevSixTotal / 6, 2);

echo json_encode([
    'monthly'         => $monthlyTotals,
    'grand_total'     => round($grandTotal, 2),
    'average_monthly' => round($averageMonthly, 2),
    'prev_six_avg'    => $prevSixAvg,
]);
