<?php
//require('../../fpdf/fpdf.php');
//include("../../classes/manager.class.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($datefrom) && $datefrom ? date("d-m-Y", strtotime($datefrom)) : date('d-m-Y', strtotime("-30 days"));
$dateto = isset($dateto) && $dateto ? date("d-m-Y", strtotime($dateto)) : date('d-m-Y');

$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'];
$taxRate = 18;

$products = [];
foreach ($openingBalance as $ob) {
    $products[$ob->{'Product ID'}] = $ob->{'Product Name'};
}
foreach ($transactions as $tr) {
    if (!isset($products[$tr->{'Product ID'}])) {
        $products[$tr->{'Product ID'}] = $tr->{'Product Name'};
    }
}
asort($products);

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', 16);
$this->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $this->Ln();

        $this->SetFont('Arial','B',12);
        $this->Cell(0,10,'Summary Stock Register (Finish Material)',0,1,'C');
        $this->SetFont('Arial','',10);
        $this->Cell(0,10,"Period: $datefrom to $dateto",0,1,'C');
        $this->Ln(2);
        $this->SetFont('Arial','B',8);
        $this->SetFillColor(200,220,255);
        $this->Cell(55,6,'Product Name',1,0,'L',true);
        $this->Cell(45,6,'Opening Amount (Excl. S.Tax)',1,0,'R',true);
        $this->Cell(22,6,'Opening STax',1,0,'R',true);
        $this->Cell(22,6,'Opening Qty',1,0,'R',true);
        $this->Cell(22,6,'Receive Qty',1,0,'R',true);
        $this->Cell(22,6,'Issue Qty',1,0,'R',true);
        $this->Cell(22,6,'Balance Qty',1,0,'R',true);
        $this->Cell(45,6,'Closing Amount (Excl. S.Tax)',1,0,'R',true);
        $this->Cell(20,6,'Closing STax',1,1,'R',true);
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial','I',8);
        $printedBy = isset($_SESSION['sess_username']) ? $_SESSION['sess_username'] : 'Unknown';
        $this->Cell(0,10,'Printed By: '.$printedBy.' - Page '.$this->PageNo(),0,0,'C');
    }
}

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

$totals = [
    'openingAmount' => 0, 'openingTax' => 0, 'openingQty' => 0,
    'receiveQty' => 0, 'issueQty' => 0,
    'closingQty' => 0, 'closingAmount' => 0, 'closingTax' => 0
];

foreach ($products as $productId => $productName) {
    $ob = null;
    foreach ($openingBalance as $item) {
        if ($item->{'Product ID'} == $productId) {
            $ob = $item;
            break;
        }
    }

    $openingQty = $ob ? $ob->{'Opening Balance Quantity'} : 0;
    $openingAmount = $ob ? $ob->{'Opening Balance Value'} : 0;
    $openingSalesTax = ($openingAmount * $taxRate) / 100;

    $productTransactions = [];
    foreach ($transactions as $row) {
        if ($row->{'Product ID'} == $productId) {
            $productTransactions[] = $row;
        }
    }

    $receiveQty = 0;
    $issueQty = 0;
    $closingQty = $openingQty;
    $closingAmount = $openingAmount;

    foreach ($productTransactions as $row) {
        $dr = $row->{'Receiving Quantity (Dr.)'};
        $cr = $row->{'Issue Quantity (Cr.)'};
        $cost = $row->{'Cost Per Unit'};
        $receiveQty += $dr;
        $issueQty += $cr;
        $closingQty += ($dr - $cr);
        $closingAmount = $closingQty * $cost;
    }

    $closingSalesTax = ($closingAmount * $taxRate) / 100;

    $pdf->Cell(55,6,$productName,1,0,'L');
    $pdf->Cell(45,6,number_format($openingAmount,2),1,0,'R');
    $pdf->Cell(22,6,number_format($openingSalesTax,2),1,0,'R');
    $pdf->Cell(22,6,number_format($openingQty,6),1,0,'R');
    $pdf->Cell(22,6,number_format($receiveQty,6),1,0,'R');
    $pdf->Cell(22,6,number_format($issueQty,6),1,0,'R');
    $pdf->Cell(22,6,number_format($closingQty,6),1,0,'R');
    $pdf->Cell(45,6,number_format($closingAmount,2),1,0,'R');
    $pdf->Cell(20,6,number_format($closingSalesTax,2),1,1,'R');

    $totals['openingAmount'] += $openingAmount;
    $totals['openingTax'] += $openingSalesTax;
    $totals['openingQty'] += $openingQty;
    $totals['receiveQty'] += $receiveQty;
    $totals['issueQty'] += $issueQty;
    $totals['closingQty'] += $closingQty;
    $totals['closingAmount'] += $closingAmount;
    $totals['closingTax'] += $closingSalesTax;
}

$pdf->SetFont('Arial','B',8);
$pdf->Cell(55,6,'Grand Total',1,0,'L');
$pdf->Cell(45,6,number_format($totals['openingAmount'],2),1,0,'R');
$pdf->Cell(22,6,number_format($totals['openingTax'],2),1,0,'R');
$pdf->Cell(22,6,number_format($totals['openingQty'],6),1,0,'R');
$pdf->Cell(22,6,number_format($totals['receiveQty'],6),1,0,'R');
$pdf->Cell(22,6,number_format($totals['issueQty'],6),1,0,'R');
$pdf->Cell(22,6,number_format($totals['closingQty'],6),1,0,'R');
$pdf->Cell(45,6,number_format($totals['closingAmount'],2),1,0,'R');
$pdf->Cell(20,6,number_format($totals['closingTax'],2),1,1,'R');

$pdf->Output();
