<?php
include_once('../../../classes/manager.class.php');
include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
include_once('../../../fpdf/fpdfreportlogoL.php');

$m = new Manager();

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

$loggedInUser = $_SESSION['sess_username'];
$datefrom = isset($_GET['datefrom']) ? $_GET['datefrom'] : date('Y-m-d', strtotime("-30 days"));
$dateto = isset($_GET['dateto']) ? $_GET['dateto'] : date('Y-m-d');


$supplier_id = $_GET['supplier_id'] ?? 'All';
$ingredient_id = $_GET['ingredient_id'] ?? 'All';
error_log("Ingredient ID: " . $ingredient_id);
error_log("supplier_id ID: " . $supplier_id);

// Fetch supplier and ingredient names
//$supplierName = $supplier_id !== 'All' ? SupplierSetup::GetSupplierNameById($supplier_id) : 'All Suppliers';
//$ingredientName = $ingredient_id !== 'All' ? IngSetup::GetIngredientNameById($ingredient_id) : 'All Ingredients';


$dateFromFormatted = date('Y-m-d', strtotime($datefrom));
$dateToFormatted = date('Y-m-d', strtotime($dateto));

$data = IngredientStock::GetRawMaterialStockRegisterTest($dateFromFormatted, $dateToFormatted, $_GET['supplier_id'], $_GET['ingredient_id']);
$openingBalance = $data['opening_balance'];
$transactions = $data['transactions'];

// Get supplier and ingredient names
$supplierName = isset($_GET['supplier_id']) ? SupplierSetup::GetSupplierSetupById($_GET['supplier_id'])->name : 'All Suppliers';
$ingredientName = isset($_GET['ingredient_id']) ? IngSetup::GetIngSetupById($_GET['ingredient_id'])->name : 'All Ingredients';
error_log("GET['ingredient_id'])->name  SUPname: " . $_GET['supplier_id'])->name;
error_log("GET['ingredient_id'])->name  name: " . $_GET['ingredient_id'])->name ;

error_log("Ingredient name: " . $ingredient_id);
error_log("supplierName: " . $supplierName);

class CustomPDF extends FPDFWithOutWaterMark {
    function Header() {
        $this->Image(__DIR__ . '/../../../images/logo_left_print.png', 10, 5, 35);
        $this->Image(__DIR__ . '/../../../images/logo_right_print.png', 257, 5, 25);

        $this->SetFont('Arial', 'B', 15);
        $this->Cell(0, 10, 'Raw Material Stock Register', 0, 1, 'C');
        
        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($GLOBALS['datefrom'])) . ' - ' . date('d-m-Y', strtotime($GLOBALS['dateto'])), 0, 1, 'C');
        $this->Cell(0, 4, 'Supplier: ' . $supplierName, 0, 1, 'C');
        $this->Cell(0, 4, 'Ingredient: ' . $ingredientName, 0, 1, 'C');
        $this->Cell(225, 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);

        $this->SetFont('Arial', 'B', 8);
        $this->SetFillColor(180, 180, 180);
        $this->Cell(16, 10, 'Date', 1, 0, 'C', true);
        $this->Cell(32, 10, 'Invoice No.', 1, 0, 'C', true);
        $this->Cell(55, 10, 'Supplier / Finish Product', 1, 0, 'C', true);
        $this->Cell(30, 10, 'Receiving Qty (Dr.)', 1, 0, 'R', true);
        $this->Cell(25, 10, 'Issue Qty (Cr.)', 1, 0, 'R', true);
        $this->Cell(20, 10, 'Balance Qty', 1, 0, 'R', true);
        $this->Cell(20, 10, 'Price Per Kg', 1, 0, 'R', true);
        $this->Cell(30, 10, 'Exc. S.Tax Amount', 1, 0, 'R', true);
        $this->Cell(24, 10, 'Sales Tax (%)', 1, 0, 'R', true);
        $this->Cell(26, 10, 'Sales Tax Amount', 1, 1, 'R', true);

        $this->SetFont('Arial', '', 8);
        $this->SetTextColor(0, 0, 0);
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }

    function AddPageWithHeader() {
        $this->AddPage();
        $this->Header();
    }
}

$pdf = new CustomPDF('L', 'mm', 'A4');
$pdf->AddPage();

/*$grandTotalReceivingQty = 0;
$grandTotalIssueQty = 0;
$grandTotalBalanceQty = 0;
$grandTotalAmount = 0;
$grandTotalSalesTax = 0;

foreach ($openingBalance as $ingredientOpening) {
    $ingredientName = $ingredientOpening->ingredient_name;
    $pdf->Cell(0, 10, 'Ingredient: ' . $ingredientName, 1, 1, 'L');

    // Ingredient totals for the current ingredient
    $ingredientTotalReceivingQty = 0;
    $ingredientTotalIssueQty = 0;
    $ingredientTotalBalanceQty = 0;
    $ingredientTotalAmount = 0;
    $ingredientTotalSalesTax = 0;


*/


    $grandTotalReceivingQty = $grandTotalIssueQty = $grandTotalBalanceQty = $grandTotalAmount = $grandTotalSalesTaxAmount = $grandTotalOpeningQty = 0;

    // Collect all unique ingredient IDs and names from both opening balances and transactions
    $ingredients = [];
    // Add ingredients from opening balances
    foreach ($openingBalance as $ingredientOpening) {
        $ingredients[$ingredientOpening->ingredient_id] = $ingredientOpening->ingredient_name;
    }
    // Add ingredients from transactions
    foreach ($transactions as $row) {
        if (!isset($ingredients[$row->ingredient_id])) {
            $ingredients[$row->ingredient_id] = $row->ingredient_name;  // Assuming ingredient_name is available in transactions
        }
    }
    // Process each ingredient, regardless of having an opening balance
    foreach ($ingredients as $ingredientId => $ingredientName) {
        // Find opening balance for this ingredient, or set default zero values
        $ingredientOpening = array_values(array_filter($openingBalance, function($i) use ($ingredientId) {
    return $i->ingredient_id == $ingredientId;
}))[0] ?? (object)[
    'opening_balance_qty' => 0,
    'opening_balance_amount' => 0,
    'ingredient_name' => $ingredientName
];
          $grandTotalOpeningQty += $ingredientOpening->opening_balance_qty;

        // Initialize totals for each ingredient
        $totalReceivingQty = $totalIssueQty = $totalBalanceQty = $totalAmount = $totalSalesTaxAmount = 0;
    // Handle opening balance
  //  if (isset($ingredientOpening->opening_balance_qty) && $ingredientOpening->opening_balance_qty >= 0.00) {
        $pdf->SetFont('Arial', 'B', 8);
       $pdf->Cell(278, 10, 'Ingredient : ' . $ingredientName, 1, 1, 'L'); 
        
       
       
       $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetFillColor(200, 200, 200);
      	$pdf->Cell(103, 10, 'Opening Balance: ' . number_format($ingredientOpening->opening_balance_qty, 6), 1, 0, 'R', true);
       	$pdf->Cell(30, 10, '', 1, 0, 'R', true);
        $pdf->Cell(25, 10, '', 1, 0, 'R', true);
        $pdf->Cell(20, 10, '', 1, 0, 'R', true);
        $pdf->Cell(20, 10, '', 1, 0, 'R', true);
        $pdf->Cell(30, 10, number_format($ingredientOpening->opening_balance_amount, 2), 1, 0, 'R', true);
        $pdf->Cell(24, 10, number_format($transactions[0]->s_tax_rate ?? 0, 2), 1, 0, 'R', true);
        $pdf->Cell(26, 10, number_format(($transactions[0]->s_tax_rate * $ingredientOpening->opening_balance_amount) / 100, 2), 1, 1, 'R', true);
   // }

    // Initialize balance and amount with opening values
    $balanceQty = $ingredientOpening->opening_balance_qty;
    $balanceAmount = $ingredientOpening->opening_balance_amount;

    foreach ($transactions as $row) {
        //if ($row->ingredient_id != $ingredientOpening->ingredient_id) continue;
        if ($row->ingredient_id != $ingredientId) continue; // Skip if ingredient does not match

        // Update balance and amount for this transaction
        $balanceQty += $row->receiving_quantity - $row->issue_quantity;
        $balanceAmount += ($row->receiving_quantity - $row->issue_quantity) * $row->price_per_kg;
      //  $salesTaxAmount = ($row->s_tax_rate * $balanceAmount) / 100;
      
          
            // Accumulate totals for the ingredient
         	$totalReceivingQty += $row->receiving_quantity;
            $totalIssueQty += $row->issue_quantity;
      		$totalOpeningQty = $ingredientOpening->opening_balance_qty;
          
     
        //    $totalAmount = $balanceAmount;
        //    $totalSalesTaxAmount = ($row->s_tax_rate * $balanceAmount) / 100;

        // Print transaction details
        $pdf->Cell(16, 10, date('d-m-Y', strtotime($row->transaction_date)), 1);
        $pdf->Cell(32, 10, $row->purchase_invoice_no, 1);
        $pdf->Cell(55, 10, $row->supplier_name ?? $row->finish_product, 1);
        $pdf->Cell(30, 10, number_format($row->receiving_quantity, 6), 1, 0, 'R');
        $pdf->Cell(25, 10, number_format($row->issue_quantity, 6), 1, 0, 'R');
        $pdf->Cell(20, 10, number_format($balanceQty, 6), 1, 0, 'R');
        $pdf->Cell(20, 10, number_format($row->price_per_kg, 2), 1, 0, 'R');
        $pdf->Cell(30, 10, number_format($balanceAmount, 2), 1, 0, 'R');
        $pdf->Cell(24, 10, number_format($row->s_tax_rate, 2), 1, 0, 'R');
        $pdf->Cell(26, 10, number_format(($row->s_tax_rate * $balanceAmount) / 100, 2), 1, 1, 'R');
    }
        // Update ingredient totals
        $ingredientTotalReceivingQty += $row->receiving_quantity;
        $ingredientTotalIssueQty += $row->issue_quantity;
        $ingredientTotalBalanceQty = $balanceQty;
        $ingredientTotalAmount = $balanceAmount;
        $ingredientTotalSalesTax += $salesTaxAmount;
         // Check if there's no receive or issue activity
    if ($totalReceivingQty == 0 && $totalIssueQty == 0) {
        // Use opening figures as closing figures when there is no activity
        $totalAmount = $ingredientOpening->opening_balance_amount;
        $totalSalesTaxAmount = ($transactions[0]->s_tax_rate * $totalAmount) / 100;
    } else {
        // Calculate the closing figures based on activity
        $totalAmount = $balanceAmount;
        $totalSalesTaxAmount = ($transactions[0]->s_tax_rate * $balanceAmount) / 100;
    }
  
  
  
    // Print ingredient totals
    $pdf->Cell(103, 10, 'Total for ' . $ingredientName . '   - Opening Qty.: ' . number_format($ingredientOpening->opening_balance_qty, 6), 1, 0, 'R', true);
    $pdf->Cell(30, 10, number_format($totalReceivingQty, 6), 1, 0, 'R', true);
    $pdf->Cell(25, 10, number_format($totalIssueQty, 6), 1, 0, 'R', true);
     

    $pdf->Cell(20, 10, number_format($balanceQty, 6), 1, 0, 'R', true);
   $pdf->Cell(20, 10, '', 1, 0, 'R', true);
    $pdf->Cell(30, 10, number_format($totalAmount, 2), 1, 0, 'R', true);
    $pdf->Cell(24, 10, '', 1, 0, 'R', true);
    $pdf->Cell(26, 10, number_format($totalSalesTaxAmount, 2), 1, 1, 'R', true);

    // Update grand totals
      //	$grandTotalOpeningQty += $totalOpeningQty;
    	$grandTotalReceivingQty += $totalReceivingQty;
        $grandTotalIssueQty += $totalIssueQty;
        $grandTotalBalanceQty += $balanceQty;
        $grandTotalAmount += $totalAmount;
        $grandTotalSalesTaxAmount += $totalSalesTaxAmount;
}

$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(103, 10, 'Grand Total  -  Opening Qty:  ' . number_format($grandTotalOpeningQty, 6), 1, 0, 'R', true);
$pdf->Cell(30, 10, number_format($grandTotalReceivingQty, 6), 1, 0, 'R', true);
$pdf->Cell(25, 10, number_format($grandTotalIssueQty, 6), 1, 0, 'R', true);
$pdf->Cell(20, 10, number_format($grandTotalBalanceQty, 6), 1, 0, 'R', true);
$pdf->Cell(20, 10, '', 1, 0, 'R', true);
$pdf->Cell(30, 10, number_format($grandTotalAmount, 2), 1, 0, 'R', true);
$pdf->Cell(24, 10, '', 1, 0, 'R', true);
$pdf->Cell(26, 10, number_format($grandTotalSalesTaxAmount, 2), 1, 1, 'R', true);

$pdf->Output();

?>