<?php
include_once('../../../classes/manager.class.php');
include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
include_once('../../../fpdf/fpdfreportlogo.php');
session_start();  // Ensure session is started to access session data

$m = new Manager();
try {
    // Validate the date input from the request
    if (!isset($_REQUEST['datefrom']) || empty($_REQUEST['datefrom']) || 
        !isset($_REQUEST['dateto']) || empty($_REQUEST['dateto'])) {
        echo 'Date filter is missing. Please provide a valid date range.';
        exit;
    }

    // Format the input dates to Y-m-d
    $dateFrom = DateTime::createFromFormat('d-m-Y', $_REQUEST['datefrom']);
    $dateTo = DateTime::createFromFormat('d-m-Y', $_REQUEST['dateto']);

    if (!$dateFrom || !$dateTo) {
        echo 'Invalid date format. Please use dd-mm-yyyy.';
        exit;
    }

    // Set the filterReport variable based on the input
    $filterReport = "WHERE DATE_FORMAT(bt.reserved_on,'%Y-%m-%d') >= '" . $dateFrom->format('Y-m-d') . "' 
                     AND DATE_FORMAT(bt.reserved_on,'%Y-%m-%d') <= '" . $dateTo->format('Y-m-d') . "'";
  
  
     $m = new Manager();
    extract($_REQUEST);
    $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);
    define('PROJECT_DISCOUNT', $param_data->is_discount);
    define('PROJECT_TAX', $param_data->is_tax);
  
   // Get the logged-in user's name from the session
    $loggedInUser = $_SESSION['sess_username'];

    // Log the filter report for debugging
    //error_log("Filter Report: " . $filterReport);

   /*    
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', '', 8);
        $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, 'Category Customer Ledger Report', 0, 0, 'C');

        if ($customer_name != 'All') {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 14);
            $pdf->Cell(0, 6, $customer->name, 0, 0, 'C');
        }

        $pdf->Ln();
        $pdf->SetFont('Arial', '', 10);
        $pdf->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');
  */
  
    // Create a new PDF document
    $pdf = new FPDFWithOutWaterMark('P', 'mm', 'A4');
    $pdf->SetMargins(0, 0, 0);
    $pdf->AddPage();
  $pdf->Image(__DIR__ . '/../../../images/logo_left_print.png',10,5,25);
 
        $pdf->Image(__DIR__ . '/../../../images/logo_right_print.png',170,5,25);
    
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->SetTitle('Ingredient Usage Report');
    $pdf->Ln();
	 $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
	$pdf->SetX(10);
	  $pdf->Ln();
	$pdf->SetFont('Arial', 'B', 14);
    // Header
    $pdf->Cell(0, 10, 'Ingredient Usage Report', 0, 1, 'C');
  $pdf->SetFont('Arial', '', 10);
     $pdf->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');
$pdf->Ln();
$pdf->SetFont('Arial', '', 8);
  $pdf->Cell(10, 4, '', 0 ,0,'L');
  $pdf->Cell(135, 4, 'Printed By: '.$loggedInUser, 0 ,0,'L');
$pdf->Cell(50, 4, 'Printed Date: ' . date('d-m-Y h:i A'), 0 ,0,'R');

//$this->Cell(135, 0, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');
$pdf->Ln();
 
    
	

 
  
  function printTableHeader($pdf) {
    $pdf->Ln();
    $pdf->SetX(10);
    // Table headers
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(10, 8, 'S.No', 1);
    $pdf->Cell(40, 8, 'Ingredients', 1);
    $pdf->Cell(25, 8, 'Used Quantity', 1);
    $pdf->Cell(40, 8, 'Value Exclusive STax', 1);
    $pdf->Cell(35, 8, 'Sales Tax Amount', 1);
    $pdf->Cell(35, 8, 'Cost Including STax', 1);
    $pdf->Ln();
  }
printTableHeader($pdf);
  
    // Fetch the ingredient report data
    $ingredientReport = IngredientStock::GetIngredientUsageReport($filterReport);
  
  // Initialize totals
      $totalUsedQuantity = 0;
      $totalValueExclusiveSTax = 0;
      $totalSalesTaxAmount = 0;
      $totalCostIncludingSTax = 0;

    // Check if report data is available
    if ($ingredientReport && count($ingredientReport) > 0) {
        $pdf->SetFont('Arial', '', 10);
        $counter = 0;

        // Populate the table with data
        foreach ($ingredientReport as $row) {
            $counter++;
          // Accumulate totals
            $totalUsedQuantity += $row->total_used_quantity;
            $totalValueExclusiveSTax += $row->total_price;
            $totalSalesTaxAmount += ($row->total_price_after_tax - $row->total_price);
            $totalCostIncludingSTax += $row->total_price_after_tax;
          
           $pdf->SetX(10);
            $pdf->Cell(10, 8, $counter, 1);
            $pdf->Cell(40, 8, $row->ingredient_name, 1);
            $pdf->Cell(25, 8, number_format($row->total_used_quantity, 2), 1,0,'R');
            $pdf->Cell(40, 8, number_format($row->total_price, 2), 1,0, 'R');
            $pdf->Cell(35, 8, number_format(($row->total_price_after_tax - $row->total_price), 2), 1, 0, 'R');
            //$pdf->Cell(35, 10, number_format($row->total_price_after_tax, 2), 1);
            $pdf->Cell(35, 8, number_format($row->total_price_after_tax, 2), 1, 0, 'R');

            $pdf->Ln();
        }
      // Add Total Row
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetX(10);
    $pdf->Cell(10, 8, '', 1); // Empty cell for S.No
    $pdf->Cell(40, 8, 'Totals', 1);
    $pdf->Cell(25, 8, number_format($totalUsedQuantity, 2), 1, 0, 'R');
    $pdf->Cell(40, 8, number_format($totalValueExclusiveSTax, 2), 1, 0, 'R');
    $pdf->Cell(35, 8, number_format($totalSalesTaxAmount, 2), 1, 0, 'R');
    $pdf->Cell(35, 8, number_format($totalCostIncludingSTax, 2), 1, 0, 'R');
    $pdf->Ln();
      
    } else {
        // No data available message
        $pdf->SetFont('Arial', 'I', 10);
        $pdf->Cell(0, 10, 'No data available for the selected date range.', 0, 1, 'C');
    }

    // Output the PDF
    $pdf->Output();
    exit();
} catch (Exception $e) {
    // Handle any errors
    error_log($e->getMessage()); // Log error message
    echo 'An error occurred while generating the report. Please try again later.';
}

?>
