<?php
include_once('../../../fpdf/fpdfreportlogo.php');
include_once('../../../classes/manager.class.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');
$supplier_id = isset($_GET['supplier_id']) ? $_GET['supplier_id'] : 'All';
$category_id = isset($_GET['category_id']) ? $_GET['category_id'] : 'All';
$payment_type = isset($_GET['payment_type']) ? $_GET['payment_type'] : 'All';

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

// Filters
$filter = "WHERE date BETWEEN '$dateFromFormatted' AND '$dateToFormatted'";
if ($supplier_id != 'All') $filter .= " AND supplier_id = '$supplier_id'";
if ($category_id != 'All') $filter .= " AND category_id = '$category_id'";
if ($payment_type != 'All') $filter .= " AND payment_type = '$payment_type'";

// Data fetch
$data = ExpenseTaxSetup::GetExpenseTaxSetupList($filter);
$categories = ExpenseTaxCategorySetup::GetExpenseTaxCategorySetupList("ORDER BY parent_id, id");

$categoryMap = [];
foreach ($categories as $cat) {
    $categoryMap[$cat->id] = $cat;
}

// Grouping
$grouped = [];
foreach ($data as $row) {
    $cat = isset($categoryMap[$row->category_id]) ? $categoryMap[$row->category_id]->parent_id : 0;
    $grouped[$cat][$row->category_id][] = $row;
}

// FPDF setup
class PDF extends FPDF
{
    var $datefrom, $dateto;

    function Header()
    {
        $this->Image(__DIR__ . '/../../../images/logo_left_print.png',10,6,30);
        $this->Image(__DIR__ . '/../../../images/logo_right_print.png',265,6,30);
        $this->SetFont('Arial','B',12);
        $this->Cell(0,10,'Summary Expense Report',0,1,'C');
        $this->SetFont('Arial','',10);
        $this->Cell(0,8,"Period: {$this->datefrom} to {$this->dateto}",0,1,'C');
        $this->Ln(5);
        $this->SetFont('Arial','B',9);
        $this->SetFillColor(230,230,230);
        $this->Cell(25,7,'Date',1,0,'C',true);
        $this->Cell(30,7,'Invoice No.',1,0,'C',true);
        $this->Cell(45,7,'Category',1,0,'C',true);
        $this->Cell(97,7,'Supplier',1,0,'C',true);
        $this->Cell(25,7,'Cartons',1,0,'C',true);
        $this->Cell(25,7,'Rate',1,0,'C',true);
        $this->Cell(30,7,'Amount',1,1,'C',true);
    }
}

$pdf = new PDF('L','mm','A4');
$pdf->datefrom = $datefrom;
$pdf->dateto = $dateto;
$pdf->AddPage();
$pdf->SetFont('Arial','',9);

$grandTotal = 0;
ksort($grouped);

foreach ($grouped as $parentId => $subcats) {
    ksort($subcats);
    $parentName = isset($categoryMap[$parentId]) ? $categoryMap[$parentId]->name : 'Uncategorized';
    $parentTotal = 0;

    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(0,7,"Category: $parentName",1,1);

    foreach ($subcats as $subId => $entries) {
        usort($entries, function ($a, $b) {
            return strtotime($a->date) - strtotime($b->date);
        });

        $subName = isset($categoryMap[$subId]) ? $categoryMap[$subId]->name : 'Unknown';
        $subTotal = 0;

        $pdf->SetFont('Arial','B',8);
        $pdf->Cell(0,6,"Sub-Category: $subName",1,1);

       /* foreach ($entries as $e) {
            $supplierObj = SupplierSetup::GetSupplierSetupById($e->supplier_id);
            $supplier = ($supplierObj && isset($supplierObj->name)) ? $supplierObj->name : '';
            $subTotal += $e->amount;
        */
       foreach ($entries as $e) {
                   if (!empty($e->supplier_id)) {
                        $supplierObj = SupplierSetup::GetSupplierSetupById($e->supplier_id);
                        $displayName = ($supplierObj && isset($supplierObj->name)) ? $supplierObj->name : '';
                    } else {
                        $displayName = $e->paid_to ?? '';
                    }

            $subTotal += $e->amount;
      
      
            $pdf->SetFont('Arial','',8);
            $pdf->Cell(25,6,date('d-m-Y',strtotime($e->date)),1);
            $pdf->Cell(30,6,$e->bill_no,1);
            $pdf->Cell(45,6,$subName,1);
           // $pdf->Cell(97,6,$supplier,1);
            $pdf->Cell(97,6,$displayName,1);
            $pdf->Cell(25,6,$e->carton,1,0,'R');
            $pdf->Cell(25,6,number_format($e->rate,2),1,0,'R');
            $pdf->Cell(30,6,number_format($e->amount,2),1,1,'R');
        }

        $pdf->SetFont('Arial','B',8);
        $pdf->Cell(247,6,"Total - $subName",1,0,'R');
        $pdf->Cell(30,6,number_format($subTotal,2),1,1,'R');
        $parentTotal += $subTotal;
    }

    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(247,6,"Sub Total - $parentName",1,0,'R');
    $pdf->Cell(30,6,number_format($parentTotal,2),1,1,'R');
    $grandTotal += $parentTotal;
}

// Grand Total
$pdf->Ln(2);
$pdf->SetFont('Arial','B',10);
$pdf->Cell(247,7,"Grand Total",1,0,'R');
$pdf->Cell(30,7,number_format($grandTotal,2),1,1,'R');

$pdf->Output();
