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

$m = new Manager();

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

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

$data = ProductionSetup::GetStockRegister($dateFromFormatted, $dateToFormatted, $product_id);
$openingBalance = $data['opening_balance'];
$transactions = $data['ledger'];

class PDF extends FPDF
{
    function Header()
    {
        global $datefrom, $dateto;
       $this->Image(__DIR__ . '/../../../images/logo_left_print.png',10,5,30);
 
        $this->Image(__DIR__ . '/../../../images/logo_right_print.png',257,5,30);
      
        $this->SetFont('Arial','B',12);
        $this->Cell(0,10,'Stock Register (Finish Material)',0,1,'C');
        $this->SetFont('Arial','',10);
        $this->Cell(0,10,"Period: $datefrom to $dateto",0,1,'C');
        $this->Ln(5);
        $this->SetFont('Arial','B',8);
        $this->SetFillColor(230,230,230);
        $this->Cell(20,6,'Date',1,0,'C',true);
        $this->Cell(25,6,'Invoice No.',1,0,'C',true);
        $this->Cell(25,6,'Batch No.',1,0,'C',true);
        $this->Cell(40,6,'Receiving Quantity (Dr.)',1,0,'C',true);
        $this->Cell(40,6,'Issue Quantity (Cr.)',1,0,'C',true);
        $this->Cell(25,6,'Balance Qty',1,0,'C',true);
        $this->Cell(20,6,'Price/Kg',1,0,'C',true);
        $this->Cell(30,6,'Exclusive S.Tax',1,0,'C',true);
        $this->Cell(20,6,'Sales Tax %',1,0,'C',true);
        $this->Cell(32,6,'Sales Tax Amount',1,1,'C',true);
    }
}

$pdf = new PDF();
$pdf->AddPage('L');
$pdf->SetFont('Arial','',8);

$taxRate = 18;
$products = [];
foreach ($openingBalance as $o) $products[$o->{'Product ID'}] = $o->{'Product Name'};
foreach ($transactions as $t) $products[$t->{'Product ID'}] = $t->{'Product Name'};
asort($products);

// Initialize Grand Totals
$grandTotalReceivingQty = 0;
$grandTotalIssueQty = 0;
$grandTotalBalanceQty = 0;
$grandTotalAmount = 0;
$grandTotalSalesTax = 0;

foreach ($products as $productId => $productName) {
    $pdf->SetFont('Arial','B',8);
    $pdf->Cell(0,6,"Product: $productName",1,1);

    $opening = null;
    foreach ($openingBalance as $i) {
        if ($i->{'Product ID'} == $productId) {
            $opening = $i;
            break;
        }
    }
    if (!$opening) {
        $opening = (object)[
            'Opening Balance Quantity' => 0,
            'Opening Balance Value' => 0,
            'Weighted Average Cost Per Unit' => 0,
            'Product Name' => ''
        ];
    }

    $balanceQty = $opening->{'Opening Balance Quantity'};
    $balanceAmount = $opening->{'Opening Balance Value'};

    $pdf->SetFont('Arial','',8);
    //$pdf->Cell(20,6,'',1);
    $pdf->Cell(70,6,'Opening Balance',1);
   // $pdf->Cell(25,6,'',1);
    $pdf->Cell(40,6,number_format($balanceQty,6),1,0,'R');
    $pdf->Cell(40,6,'',1);
    $pdf->Cell(25,6,number_format($balanceQty,6),1,0,'R');
    $pdf->Cell(20,6,number_format($opening->{'Weighted Average Cost Per Unit'},2),1,0,'R');
    $pdf->Cell(30,6,number_format($balanceAmount,2),1,0,'R');
    $pdf->Cell(20,6,number_format($taxRate,2),1,0,'R');
    $pdf->Cell(32,6,number_format(($balanceAmount * $taxRate) / 100,2),1,1,'R');

    $totalReceivingQty = 0;
    $totalIssueQty = 0;

    foreach ($transactions as $row) {
        if ($row->{'Product ID'} != $productId) continue;
        $balanceQty += $row->{'Receiving Quantity (Dr.)'} - $row->{'Issue Quantity (Cr.)'};
        $balanceAmount = $balanceQty * $row->{'Cost Per Unit'};
        $totalReceivingQty += $row->{'Receiving Quantity (Dr.)'};
        $totalIssueQty += $row->{'Issue Quantity (Cr.)'};
        $salesTaxAmount = ($balanceAmount * $taxRate) / 100;

        $pdf->Cell(20,6,date('d-m-Y',strtotime($row->{'Transaction Date'})),1);
        $pdf->Cell(25,6,$row->{'Invoice Number'},1);
        $pdf->Cell(25,6,$row->{'Batch Number'},1);
        $pdf->Cell(40,6,number_format($row->{'Receiving Quantity (Dr.)'},6),1,0,'R');
        $pdf->Cell(40,6,number_format($row->{'Issue Quantity (Cr.)'},6),1,0,'R');
        $pdf->Cell(25,6,number_format($balanceQty,6),1,0,'R');
        $pdf->Cell(20,6,number_format($row->{'Cost Per Unit'},2),1,0,'R');
        $pdf->Cell(30,6,number_format($balanceAmount,2),1,0,'R');
        $pdf->Cell(20,6,number_format($taxRate,2),1,0,'R');
        $pdf->Cell(32,6,number_format($salesTaxAmount,2),1,1,'R');
    }

    $finalAmount = $balanceAmount;
    $finalSalesTax = ($balanceAmount * $taxRate) / 100;

    $pdf->SetFont('Arial','B',8);
    $pdf->Cell(70,6,"Total: $productName",1);
    $pdf->Cell(40,6,number_format($totalReceivingQty,6),1,0,'R');
    $pdf->Cell(40,6,number_format($totalIssueQty,6),1,0,'R');
    $pdf->Cell(25,6,number_format($balanceQty,6),1,0,'R');
    $pdf->Cell(20,6,'',1);
    $pdf->Cell(30,6,number_format($finalAmount,2),1,0,'R');
    $pdf->Cell(20,6,number_format($taxRate,2),1,0,'R');
    $pdf->Cell(32,6,number_format($finalSalesTax,2),1,1,'R');

    // Add to Grand Totals
    $grandTotalReceivingQty += $totalReceivingQty;
    $grandTotalIssueQty += $totalIssueQty;
    $grandTotalBalanceQty += $balanceQty;
    $grandTotalAmount += $finalAmount;
    $grandTotalSalesTax += $finalSalesTax;
}

// Grand Total Row
$pdf->Ln(5);
$pdf->SetFont('Arial','B',9);
$pdf->Cell(70,6,"GRAND TOTAL",1);
$pdf->Cell(40,6,number_format($grandTotalReceivingQty,6),1,0,'R');
$pdf->Cell(40,6,number_format($grandTotalIssueQty,6),1,0,'R');
$pdf->Cell(25,6,number_format($grandTotalBalanceQty,6),1,0,'R');
$pdf->Cell(20,6,'',1);
$pdf->Cell(30,6,number_format($grandTotalAmount,2),1,0,'R');
$pdf->Cell(20,6,number_format($taxRate,2),1,0,'R');
$pdf->Cell(32,6,number_format($grandTotalSalesTax,2),1,1,'R');

$pdf->Output();
