<?php
include 'includes/auth.php';
include 'db.php';
require 'dompdf/vendor/autoload.php'; // Make sure Dompdf and PhpSpreadsheet are installed via Composer

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

// Get export type
$type = $_GET['type'] ?? 'pdf';
$type = strtolower($type);

// Optional: filter by date range
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$where = "WHERE s.archived=0 ";
if($start_date && $end_date){
    $where .= " AND DATE(s.sale_date) BETWEEN '$start_date' AND '$end_date' ";
}

// Fetch sales data
$sql = "
SELECT s.*, GROUP_CONCAT(p.name SEPARATOR ', ') AS products
FROM sales s
JOIN sale_items si ON s.id = si.sale_id
JOIN products p ON si.product_id = p.id
$where
GROUP BY s.id
ORDER BY s.sale_date DESC
";

$result = $conn->query($sql);

// --- PDF Export ---
if($type == 'pdf'){
    $html = '<h3 style="text-align:center;">Sales Report</h3>';
    $html .= '<table border="1" cellpadding="5" cellspacing="0" width="100%">';
    $html .= '<tr style="background:#000;color:#fff;">
                <th>Sale ID</th>
                <th>Date</th>
                <th>Products</th>
                <th>Payment Method</th>
                <th>Discount</th>
                <th>VAT</th>
                <th>Total</th>
              </tr>';

    while($row = $result->fetch_assoc()){
        $html .= "<tr>
                    <td>{$row['id']}</td>
                    <td>{$row['sale_date']}</td>
                    <td>{$row['products']}</td>
                    <td>{$row['payment_method']}</td>
                    <td>".number_format($row['discount'],2)."</td>
                    <td>".number_format($row['vat_total'],2)."</td>
                    <td>".number_format($row['total'],2)."</td>
                  </tr>";
    }
    $html .= '</table>';

    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->render();
    $dompdf->stream("sales_report.pdf", ["Attachment" => true]);
    exit;
}

// --- Excel Export ---
elseif($type == 'excel'){
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('Sales Report');

    // Headers
    $headers = ['Sale ID', 'Date', 'Products', 'Payment Method', 'Discount', 'VAT', 'Total'];
    $sheet->fromArray($headers, NULL, 'A1');

    // Data
    $row_num = 2;
    while($row = $result->fetch_assoc()){
        $sheet->setCellValue("A$row_num", $row['id']);
        $sheet->setCellValue("B$row_num", $row['sale_date']);
        $sheet->setCellValue("C$row_num", $row['products']);
        $sheet->setCellValue("D$row_num", $row['payment_method']);
        $sheet->setCellValue("E$row_num", $row['discount']);
        $sheet->setCellValue("F$row_num", $row['vat_total']);
        $sheet->setCellValue("G$row_num", $row['total']);
        $row_num++;
    }

    $writer = new Xlsx($spreadsheet);
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="sales_report.xlsx"');
    header('Cache-Control: max-age=0');
    $writer->save('php://output');
    exit;
}
else{
    echo "Invalid export type";
}
