<?php
session_start();
require_once '../includes/db.php';
require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if (!isset($_SESSION['username'])) exit;

$start = $_GET['start'];
$end   = $_GET['end'];
$branch = $_GET['branch'] ?? null;

$sql = "
SELECT 
    DATE(b.in_date) AS report_date,
    SUM(b.bill_total) AS revenue
FROM bills b
WHERE b.in_date BETWEEN ? AND ?
AND b.status != 'Cancelled'
";

$params = [$start, $end];

if ($branch && $branch !== 'all') {
    $sql .= " AND b.branch_id = ? ";
    $params[] = $branch;
}

$sql .= " GROUP BY DATE(b.in_date) ORDER BY report_date ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Create Excel */
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

$sheet->setCellValue('A1', 'Date');
$sheet->setCellValue('B1', 'Revenue');

$row = 2;
foreach ($data as $r) {
    $sheet->setCellValue("A$row", $r['report_date']);
    $sheet->setCellValue("B$row", $r['revenue']);
    $row++;
}

$filename = "Financial_Report_$start_to_$end.xlsx";

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename=\"$filename\"");
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
