<?php

include_once('../../../classes/manager.class.php');
include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
//include_once('../../../fpdf/fpdf1.php');
include_once('../../../fpdf/fpdfreportlogoL.php');
$m = new Manager();

$supplier_id = $_GET['supplier_id'] ?? 'All';
$ingredient_id = $_GET['ingredient_id'] ?? 'All';

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

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);

$filterReport = "";

// Apply supplier filter if specified
if ($supplier_id && $supplier_id != 'All') {
    $filterReport .= " AND p.supplier_id = '$supplier_id'";
}

// Apply ingredient filter if specified
if ($ingredient_id && $ingredient_id != 'All') {
    $filterReport .= " AND i.ingredient_id = '$ingredient_id'";
}

// Fetch the data
$data = IngredientStock::GetBalanceStockReport($filterReport);

// Check if the class FPDFWithOutWaterMark already exists
//if (!class_exists('FPDFWithOutWaterMark')) {
class CustomPDF extends FPDFWithOutWaterMark {
    // Function to handle page header (Repeated on each page)
    function Header()
    {
        // Logo
        $this->Image(__DIR__ . '/../../../images/logo_left_print.png', 10, 5, 25); // Adjusted logo size
        $this->Image(__DIR__ . '/../../../images/logo_right_print.png', 257, 5, 25); // Adjusted logo size
        $this->Ln();

        // Title and headers
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 8, PROJECT_NAME, 0, 1, 'C');
          //    $this->Ln();

          // Report Title
        $this->SetFont('Arial', '', 14);
        $this->Cell(0, 10, 'Balance Stock Report (Raw Material)', 0, 1, 'C');
        $this->Ln(5); // Added space before the table header
        $this->SetFont('Arial', '', 8);
        //$this->Cell(10, 4, '', 0 ,0,'L');
      //  $this->Cell(210, 4, 'Printed By: '.$loggedInUser, 0 ,0,'L');
        $this->Cell(230, 4, 'Printed By: ' . $_SESSION['sess_username'], 0, 0, 'L');
        $this->Cell(50, 4, 'Printed Date: ' . date('d-m-Y h:i A'), 0 ,0,'R');
        $this->Ln(5);  // Added some space after printed date

    

        // Table header
        $this->SetFont('Arial', 'B', 8);
        $this->Cell(22, 10, 'Receiving Date', 1);
        $this->Cell(27, 10,  'Reference Number', 1);
        $this->Cell(45, 10, 'Supplier', 1);
        $this->Cell(40, 10, 'Item Name', 1);
        $this->Cell(28, 10, 'Receiving Quantity', 1);
        $this->Cell(25, 10, 'Balance Quantity', 1);
        $this->Cell(19, 10, 'Price Per Kg', 1);
        $this->Cell(20, 10, 'Amount', 1);
        $this->Cell(18, 10, 'Sales Tax %', 1);
        $this->Cell(35, 10, 'Sales Tax Amount', 1);
        $this->Ln();
    }

    // Function to handle footer (Repeated on each page)
    function Footer()
    {
        // Position at 1.5 cm from bottom
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }
}

// Initialize PDF
$loggedInUser = $_SESSION['sess_username'];
$pdf = new CustomPDF('L', 'mm', 'A4');
$pdf->AddPage();

// Table data
$pdf->SetFont('Arial', '', 10);
$currentItem = null;
$groupTotals = [
    'receiving_quantity' => 0,
    'balance_quantity' => 0,
    'amount' => 0,
    'sales_tax_amount' => 0
];
$grandTotals = [
    'receiving_quantity' => 0,
    'balance_quantity' => 0,
    'amount' => 0,
    'sales_tax_amount' => 0
];

if ($data) {
    foreach ($data as $row) {
        $pdf->SetX(10);
        $amount = $row->price_per_kg * $row->balance_quantity;
        $salesTaxAmount = ($amount * $row->s_tax_rate) / 100;

        // Check if we need to print the group total
        if ($currentItem !== $row->item_name) {
            if ($currentItem !== null) {
                // Print totals for the previous group
                $pdf->SetX(10);
                $pdf->SetFont('Arial', 'B', 8);
                $pdf->Cell(134, 10, "Total for {$currentItem}", 1, 0, 'R'); 
                $pdf->Cell(28, 10, number_format($groupTotals['receiving_quantity'], 2), 1,0,'R');
                $pdf->Cell(25, 10, number_format($groupTotals['balance_quantity'], 2), 1,0,'R');
                $pdf->Cell(19, 10, '--', 1,0,'C');
                $pdf->Cell(20, 10, number_format($groupTotals['amount'], 2), 1,0,'R');
                $pdf->Cell(18, 10, '--', 1,0,'C');
                $pdf->Cell(35, 10, number_format($groupTotals['sales_tax_amount'], 2), 1,0,'R');
                $pdf->Ln();

                // Reset group totals
                $groupTotals = [
                    'receiving_quantity' => 0,
                    'balance_quantity' => 0,
                    'amount' => 0,
                    'sales_tax_amount' => 0
                ];
            }
            $currentItem = $row->item_name;
        }

        // Display row data
        $pdf->SetX(10);
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(22, 10, date('d-m-Y', strtotime($row->receiving_date)), 1);
        $pdf->Cell(27, 10, $row->reference_number, 1);
        $pdf->SetFont('Arial', '', 7);
        $pdf->Cell(45, 10, $row->supplier_name, 1);
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(40, 10, $row->item_name, 1);
        $pdf->Cell(28, 10, number_format($row->receiving_quantity, 2), 1,0,'R');
        $pdf->Cell(25, 10, number_format($row->balance_quantity, 2), 1,0,'R');
        $pdf->Cell(19, 10, number_format($row->price_per_kg, 2), 1,0,'R');
        $pdf->Cell(20, 10, number_format($amount, 2), 1,0,'R');
        $pdf->Cell(18, 10, $row->s_tax_rate, 1,0,'R');
        $pdf->Cell(35, 10, number_format($salesTaxAmount, 2), 1,0,'R');
        $pdf->Ln();

        // Update group totals
        $groupTotals['receiving_quantity'] += $row->receiving_quantity;
        $groupTotals['balance_quantity'] += $row->balance_quantity;
        $groupTotals['amount'] += $amount;
        $groupTotals['sales_tax_amount'] += $salesTaxAmount;

        // Update grand totals
        $grandTotals['receiving_quantity'] += $row->receiving_quantity;
        $grandTotals['balance_quantity'] += $row->balance_quantity;
        $grandTotals['amount'] += $amount;
        $grandTotals['sales_tax_amount'] += $salesTaxAmount;
    }

    // Print final group total for the last item
    $pdf->SetX(10);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(134, 10, "Total for {$currentItem}", 1, 0, 'R'); 
    $pdf->Cell(28, 10, number_format($groupTotals['receiving_quantity'], 2), 1,0,'R');
    $pdf->Cell(25, 10, number_format($groupTotals['balance_quantity'], 2), 1,0,'R');
    $pdf->Cell(19, 10, '--', 1,0,'C');
    $pdf->Cell(20, 10, number_format($groupTotals['amount'], 2), 1,0,'R');
    $pdf->Cell(18, 10, '--', 1,0,'C');
    $pdf->Cell(35, 10, number_format($groupTotals['sales_tax_amount'], 2), 1,0,'R');
    $pdf->Ln();

    // Print grand total
    $pdf->SetX(10);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(134, 10, 'Grand Total', 1, 0, 'R'); 
    $pdf->Cell(28, 10, number_format($grandTotals['receiving_quantity'], 2), 1,0,'R');
    $pdf->Cell(25, 10, number_format($grandTotals['balance_quantity'], 2), 1,0,'R');
    $pdf->Cell(19, 10, '--', 1,0,'C');
    $pdf->Cell(20, 10, number_format($grandTotals['amount'], 2), 1,0,'R');
    $pdf->Cell(18, 10, '--', 1,0,'C');
    $pdf->Cell(35, 10, number_format($grandTotals['sales_tax_amount'], 2), 1,0,'R');
    $pdf->Ln();
}

// Output the PDF
$pdf->Output();

?>
