<?php
// Include necessary libraries for export
require_once '../libs/PhpSpreadsheet/src/PhpSpreadsheet/Spreadsheet.php';
require_once '../libs/PhpSpreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php';
require_once '../libs/tcpdf/tcpdf.php';

// Instantiate TCPDF class directly


session_start();
include('../config/db.php');

// Fetch report data (you already have this logic in your code)
$report_type = isset($_POST['report_type']) ? $_POST['report_type'] : 'daily';

// Define the queries (You already have these in your code)
switch ($report_type) {
    case 'daily':
        $sales_query = "SELECT DATE(sale_date) AS sale_date, SUM(total) AS total_sales, SUM(profit) AS total_profit, SUM(discount) AS total_discount FROM sales GROUP BY DATE(sale_date)";
        break;
    case 'weekly':
        $sales_query = "SELECT YEARWEEK(sale_date) AS sale_date, SUM(total) AS total_sales, SUM(profit) AS total_profit, SUM(discount) AS total_discount FROM sales GROUP BY YEARWEEK(sale_date)";
        break;
    case 'monthly':
        $sales_query = "SELECT DATE_FORMAT(sale_date, '%Y-%m') AS sale_date, SUM(total) AS total_sales, SUM(profit) AS total_profit, SUM(discount) AS total_discount FROM sales GROUP BY DATE_FORMAT(sale_date, '%Y-%m')";
        break;
    case 'yearly':
        $sales_query = "SELECT YEAR(sale_date) AS sale_date, SUM(total) AS total_sales, SUM(profit) AS total_profit, SUM(discount) AS total_discount FROM sales GROUP BY YEAR(sale_date)";
        break;
}

// Fetch sales data
$sales_stmt = $pdo->query($sales_query);
$sales_data = $sales_stmt->fetchAll(PDO::FETCH_ASSOC);


// Export as PDF
if (isset($_POST['export_pdf'])) {
    $pdf = new TCPDF();
    $pdf->AddPage();
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Cell(0, 10, 'Sales Report', 0, 1, 'C');

    // Add table headers
    $pdf->Cell(40, 10, 'Sale Date', 1, 0, 'C');
    $pdf->Cell(40, 10, 'Total Sales', 1, 0, 'C');
    $pdf->Cell(40, 10, 'Total Profit', 1, 0, 'C');
    $pdf->Cell(40, 10, 'Total Discount', 1, 1, 'C');

    // Add table data
    foreach ($sales_data as $data) {
        $pdf->Cell(40, 10, $data['sale_date'], 1, 0, 'C');
        $pdf->Cell(40, 10, format_currency($data['total_sales']), 1, 0, 'C');
        $pdf->Cell(40, 10, format_currency($data['total_profit']), 1, 0, 'C');
        $pdf->Cell(40, 10, format_currency($data['total_discount']), 1, 1, 'C');
    }

    // Output the PDF
    $pdf->Output('report.pdf', 'D');
    exit();
}
?>
