<?php

include_once('../../../classes/manager.class.php');

include_once('../../../fpdf/fpdfreportlogoL.php');
$m = new Manager();

session_start();

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

// Get filters
$datefrom = isset($_GET['datefrom']) ? date('Y-m-d', strtotime($_GET['datefrom'])) : date('Y-m-d', strtotime('-30 days'));
$dateto = isset($_GET['dateto']) ? date('Y-m-d', strtotime($_GET['dateto'])) : date('Y-m-d');
$ingredient_id = isset($_GET['ingredient_id']) ? $_GET['ingredient_id'] : 'All';

$data = ProductionSetup::GetWastageReport($datefrom, $dateto, $ingredient_id);
$datefromDisplay = date('d-m-Y', strtotime($datefrom));
$datetoDisplay = date('d-m-Y', strtotime($dateto));

// Create PDF
$pdf = new FPDF();
  
$pdf->Ln();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 14);
$pdf->Cell(0, 10, 'Ingredient Wastage Report', 0, 1, 'C');

$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 8, "Period: $datefromDisplay to $datetoDisplay", 0, 1, 'C');
$pdf->Ln();
$pdf->Ln();

// Table header
$pdf->SetFont('Arial', 'B', 10);
$pdf->SetFillColor(230, 230, 230);
$pdf->Cell(21, 8, 'S.No', 1, 0, 'C', true);
$pdf->Cell(66, 8, 'Ingredient Name', 1, 0, 'C', true);
$pdf->Cell(42, 8, 'Total Consumed', 1, 0, 'C', true);
//$pdf->Cell(25, 8, 'Wastage %', 1, 0, 'C', true);
$pdf->Cell(51, 8, 'Total Wastage (KG)', 1, 1, 'C', true);

// Table body
$pdf->SetFont('Arial', '', 10);
$counter = 1;
$grandTotalWastage = 0;
$grandTotalConsumed = 0;

foreach ($data as $row) {
    $pdf->Cell(21, 8, $counter++, 1);
    $pdf->Cell(66, 8, $row->ingredient_name, 1);
    $pdf->Cell(42, 8, number_format($row->total_consumed, 3), 1, 0, 'R');
   // $pdf->Cell(25, 8, '13%', 1, 0, 'R');
    $pdf->Cell(51, 8, number_format($row->total_wastage, 3), 1, 1, 'R');
    
    $grandTotalWastage += $row->total_wastage;
    $grandTotalConsumed += $row->total_consumed;
}

// Grand total row
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(21, 8, '', 1);
$pdf->Cell(66, 8, 'Total', 1);
$pdf->Cell(42, 8, number_format($grandTotalConsumed, 3), 1, 0, 'R');
//$pdf->Cell(25, 8, '', 1);
$pdf->Cell(51, 8, number_format($grandTotalWastage, 3), 1, 1, 'R');

$pdf->Output();
?>
