<?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'];
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);

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

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

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

$pdf->Image(__DIR__ . '/../../../images/logo_left_print.png',10,5,30);
 
        $pdf->Image(__DIR__ . '/../../../images/logo_right_print.png',257,5,30);
// Set font for the report title
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');

$pdf->Ln();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 10, 'Raw Material Stock Register Summary', 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(227, 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();
$pdf->Ln();

// Column headers
$pdf->SetFont('Arial', 'B', 7);
$pdf->Cell(40, 10, 'Items (Ingredient Name)', 1, 0, 'C');
$pdf->Cell(40,10, 'Opening Amount Excl. Sales Tax', 1, 0, 'C');
$pdf->Cell(30, 10, 'Opening Sales Tax', 1, 0, 'C');
$pdf->Cell(22, 10, 'Opening Qty', 1, 0, 'C');
$pdf->Cell(30, 10, 'Receive Qty', 1, 0, 'C');
$pdf->Cell(25, 10, 'Issue Qty', 1, 0, 'C');
$pdf->Cell(25, 10, 'Balance Qty', 1, 0, 'C');
$pdf->Cell(35, 10, 'Closing Amount Excl. S.Tax', 1, 0, 'C');
$pdf->Cell(32, 10, 'Closing Sales Tax Amount', 1, 1, 'C');
// Create instance of FPDF
//$pdf = new PDF();

$pdf->SetFont('Arial', '', 7);

$datefrom = $_GET['datefrom'] ?? date('Y-m-d', strtotime("-30 days"));
$dateto = $_GET['dateto'] ?? date('Y-m-d');
$supplier_id = $_GET['supplier_id'] ?? 'All';
$ingredient_id = $_GET['ingredient_id'] ?? 'All';

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

// Fetch data using your existing method
$data = IngredientStock::GetRawMaterialStockRegisterTest($dateFromFormatted, $dateToFormatted, $supplier_id, $ingredient_id);

$openingBalance = $data['opening_balance'];
$transactions = $data['transactions'];

$grandTotalReceivingQty = $grandTotalIssueQty = $grandTotalBalanceQty = $grandTotalAmount = $grandTotalSalesTaxAmount = 0;
$grandOpeningBalanceAmount = 0;
$grandOpeningBalanceTaxAmount = 0;
$grandOpeningQuantity = 0;
$grandTotalReceivingQty = 0;
$grandTotalIssueQty = 0;
$grandTotalBalanceQty = 0;
$grandTotalAmount = 0;
$grandTotalSalesTaxAmount = 0;

$ingredients = [];
foreach ($openingBalance as $ingredientOpening) {
    $ingredients[$ingredientOpening->ingredient_id] = $ingredientOpening->ingredient_name;
}
foreach ($transactions as $row) {
    if (!isset($ingredients[$row->ingredient_id])) {
        $ingredients[$row->ingredient_id] = $row->ingredient_name;
    }
}
 asort($ingredients);

foreach ($ingredients as $ingredientId => $ingredientName) {
    $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
    ];

    $totalReceivingQty = $totalIssueQty = $totalBalanceQty = $totalAmount = $totalSalesTaxAmount = 0;
    $balanceQty = $ingredientOpening->opening_balance_qty;
    $balanceAmount = $ingredientOpening->opening_balance_amount;

    foreach ($transactions as $row) {
        if ($row->ingredient_id != $ingredientId) continue;

       

        $totalReceivingQty += $row->receiving_quantity;
        $totalIssueQty += $row->issue_quantity;
       $balanceQty += $row->receiving_quantity - $row->issue_quantity;
        $balanceAmount += ($row->receiving_quantity - $row->issue_quantity) * $row->price_per_kg;
       } //  $totalAmount = $balanceAmount;
        
      //$totalSalesTaxAmount = ($row->s_tax_rate * $balanceAmount) / 100;
    
      // 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;
       // Fix: Get the tax rate from the last transaction for this ingredient
$taxRate = 0;
foreach ($transactions as $row) {
    if ($row->ingredient_id == $ingredientId && isset($row->s_tax_rate)) {
        $taxRate = $row->s_tax_rate; // Use the last available tax rate for this ingredient
    }
}

// Apply tax only if the tax rate is greater than 0
$totalSalesTaxAmount = ($taxRate > 0) ? ($taxRate * $balanceAmount) / 100 : 0;
    }
    
    $totalIngredientOpeningBalance = $ingredientOpening->opening_balance_amount;
  	$totalOpeningBalanceTaxAmount = ($transactions[0]->s_tax_rate * $totalIngredientOpeningBalance) / 100;
  	$totalIngredientOpening = $ingredientOpening->opening_balance_qty;
  
  // Hide rows where Opening Qty = 0 AND Receive Qty = 0 AND Issue Qty = 0
$EPS = 1e-9;
if (
    abs((float)$totalIngredientOpening) < $EPS &&
    abs((float)$totalReceivingQty)     < $EPS &&
    abs((float)$totalIssueQty)         < $EPS
) {
    continue; // skip printing and skip accumulating totals
}

    
     // Output each row to PDF
    $pdf->Cell(40, 8, $ingredientName, 1);
    $pdf->Cell(40, 8, number_format( $totalIngredientOpeningBalance, 2), 1, 0, 'R');
    $pdf->Cell(30, 8, number_format($totalOpeningBalanceTaxAmount, 2), 1, 0, 'R');
    $pdf->Cell(22, 8, number_format($totalIngredientOpening, 6), 1, 0, 'R');
    $pdf->Cell(30, 8, number_format($totalReceivingQty, 6), 1, 0, 'R');
    $pdf->Cell(25, 8, number_format($totalIssueQty, 6), 1, 0, 'R');
    $pdf->Cell(25, 8, number_format($balanceQty, 6), 1, 0, 'R');
    $pdf->Cell(35, 8, number_format($totalAmount, 2), 1, 0, 'R');
    $pdf->Cell(32, 8, number_format($totalSalesTaxAmount, 2), 1, 1, 'R');
    
   
    $grandOpeningBalanceAmount += $totalIngredientOpeningBalance;
  	$grandOpeningBalanceTaxAmount += $totalOpeningBalanceTaxAmount;
  	$grandOpeningQuantity += $totalIngredientOpening;
    $grandTotalReceivingQty += $totalReceivingQty;
    $grandTotalIssueQty += $totalIssueQty;
    $grandTotalBalanceQty += $balanceQty;
    $grandTotalAmount += $totalAmount;
    $grandTotalSalesTaxAmount += $totalSalesTaxAmount;
    $grandTotalingredientOpening += $ingredientOpening->opening_balance_qty;
}

// Grand total row
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(40, 8, 'Grand Total', 1);
$pdf->Cell(40, 8, number_format($grandOpeningBalanceAmount, 2), 1, 0, 'R');
$pdf->Cell(30, 8, number_format($grandOpeningBalanceTaxAmount, 2), 1, 0, 'R');
$pdf->Cell(22, 8, number_format($grandOpeningQuantity, 6), 1 , 0, 'R');
$pdf->Cell(30, 8, number_format($grandTotalReceivingQty, 6), 1, 0, 'R');
$pdf->Cell(25, 8, number_format($grandTotalIssueQty, 6), 1, 0, 'R');
$pdf->Cell(25, 8, number_format($grandTotalBalanceQty, 6), 1, 0, 'R');
$pdf->Cell(35, 8, number_format($grandTotalAmount, 2), 1, 0, 'R');
$pdf->Cell(32, 8, number_format($grandTotalSalesTaxAmount, 2), 1, 1, 'R');

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