<?php
error_reporting(E_ALL);
ini_set('display_errors', '0'); // Turn off error display to avoid output conflicts

try {
    if (!isset($_REQUEST['datefrom'])) {
        header('location: ../invoice.php');
        exit;
    }

    include_once('../../../classes/manager.class.php');
    include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');  // Ensure this uses spl_autoload_register
    include_once('../../../fpdf/fpdf1.php');

    $m = new Manager();
    extract($_REQUEST);

    // Configuration
    $param_data = ControlConfifguration::GetConfiguration();
    define('PROJECT_NAME', $param_data->name);
    define('PROJECT_ADDRESS', $param_data->address);
    define('PROJECT_TEL', $param_data->contact);
    define('PROJECT_EMAIL', $param_data->email);
    define('PROJECT_WEBSITE', $param_data->website);
    define('PROJECT_COLOR', $param_data->color);

    // Date filtering
    if ($datefrom == "") {
        $datefrom = date('Y-m-d', strtotime("-30 days"));
    } else {
        $datefrom = date("Y-m-d", strtotime($datefrom));
    }
    if ($dateto == "") {
        $dateto = date('Y-m-d');
    } else {
        $dateto = date("Y-m-d", strtotime($dateto));
    }
    
    $qryDate = date("Y-m-d", strtotime($datefrom));
    $qryTo = date("Y-m-d", strtotime($dateto));

    $filterReport = "WHERE DATE_FORMAT(bt.reserved_on,'%Y-%m-%d') >= '$qryDate' 
                     AND DATE_FORMAT(bt.reserved_on,'%Y-%m-%d') <= '$qryTo'";

    $ingredientReport = IngredientStock::GetIngredientUsageReport($filterReport);

    if (!empty($ingredientReport)) {

        ob_start();  // Start output buffering to prevent premature output
        
        $pdf = new FPDFWithOutWaterMark('P', 'mm', 'legal');
        $pdf->SetMargins(0, 0, 0);
        $pdf->AddPage();
        $pdf->Ln();

        // Title and headers
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $pdf->SetFont('Arial', '', 8);
        $pdf->Ln();
        $pdf->Cell(0, 8, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');
        $pdf->Ln();
        $pdf->SetFont('Arial', '', 14);
        $pdf->Cell(0, 6, 'Ingredient Usage Report', 0, 0, 'C');
        $pdf->Ln();
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(0, 4, 'For the period of: ' . $datefrom . ' - ' . $dateto, 0, 0, 'C');
        $pdf->Ln();
        $pdf->Ln();

        $header = ['S.No', 'Ingredient', 'Used Quantity'];

        // Table creation
        FancyTable($header, $ingredientReport, $setx = 10);

        $pdf->Output();
        ob_end_flush();  // Flush the buffer and send the PDF output
        exit;
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }
    
} catch (Exception $e) {
    echo $e->getMessage();
}
?>
