<?php
ob_start();
error_reporting(0);
ini_set('display_errors', '0');

include('../../../classes/manager.class.php');
include('../../../fpdf/fpdf1.php');

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

$m = new Manager();

/* ============ GET FILTERS (same as your frontend) ============ */
$datefrom      = isset($_GET['datefrom']) ? $_GET['datefrom'] : date('d-m-Y', strtotime("-30 days"));
$dateto        = isset($_GET['dateto']) ? $_GET['dateto'] : date('d-m-Y');
$cat_type      = isset($_GET['cat_type']) ? $_GET['cat_type'] : 'All';
$cat_name      = isset($_GET['cat_name']) ? $_GET['cat_name'] : 'All';
$customer_name = isset($_GET['customer_name']) ? $_GET['customer_name'] : 'All';

$qryTo = date("Y-m-d", strtotime($dateto));

/* ============ SAME FILTER LOGIC (Type/Category) ============ */
$catType = "";

if ($cat_type !== 'All' && $cat_type !== '') {
    $catType .= " AND cs.is_mart = '$cat_type'";
} else {
    if ($cat_name != 'All' && $cat_name != '') {
        $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);

        if (!empty($cat) && !empty($cat->id)) {
            $cust = CustomerSetup::GetCustomerSetupList(" WHERE category_id = '$cat->id' ");

            $custArray = array();
            if ($cust) {
                foreach ($cust as $custRow) {
                    $custArray[] = $custRow->id;
                }
            }

            if (!empty($custArray)) {
                $customers = implode(',', $custArray);
                $catType .= " AND cs.id IN ($customers)";
            } else {
                $catType .= " AND cs.id IN (0)";
            }
        }
    }
}

/* ============ FETCH DATA ============ */
/*
    Make sure this method exists in Invoice class:
    Invoice::GetCustomerBalanceSummaryReport($dateTo, $catCondition, $customerId)
*/
$rows = Invoice::GetCustomerBalanceSummaryReport($qryTo, $catType, $customer_name);

/* ============ PDF CLASS (same pattern as your reference) ============ */
class PDF extends FPDF
{
    function Header()
    {
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 10, 'Customer Balance Summary Report', 0, 1, 'C');

        $this->SetFont('Arial', '', 10);
        $from = isset($_GET['datefrom']) ? $_GET['datefrom'] : '';
        $to   = isset($_GET['dateto']) ? $_GET['dateto'] : '';
        $this->Cell(0, 5, "From: $from To: $to", 0, 1, 'C');

        $this->Ln(4);

        // Table Header (Portrait A4 width usable ~190)
        $this->SetFont('Arial', 'B', 8);
        $this->Cell(10, 7, 'S.No', 1, 0, 'C');
        $this->Cell(78, 7, 'Customer', 1, 0, 'L');
        $this->Cell(24, 7, 'Last Inv', 1, 0, 'C');
        $this->Cell(24, 7, 'Last Pay', 1, 0, 'C');
        $this->Cell(24, 7, 'Pay Amt', 1, 0, 'R');
        $this->Cell(30, 7, 'Balance', 1, 1, 'R');
    }

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

/* ============ BUILD PDF (Portrait) ============ */
$pdf = new PDF('P', 'mm', 'A4');
$pdf->SetAutoPageBreak(true, 12);
$pdf->SetMargins(10, 10, 10);
$pdf->AddPage();
$pdf->SetFont('Arial', '', 8);

$counter = 1;
$grandBalance = 0;

if ($rows) {
    foreach ($rows as $r) {

        $lastInv = (!empty($r->last_invoice_date)) ? date('d-m-Y', strtotime($r->last_invoice_date)) : '-';
        $lastPay = (!empty($r->last_payment_date)) ? date('d-m-Y', strtotime($r->last_payment_date)) : '-';
        $lastPayAmt = (!empty($r->last_payment_amount)) ? (float)$r->last_payment_amount : 0;

        $bal = (float)$r->remaining_balance;
        $grandBalance += $bal;

        // trim customer name to avoid overflow
        $custName = $r->customer_name;
        if (strlen($custName) > 45) $custName = substr($custName, 0, 45) . '..';

        $pdf->Cell(10, 7, $counter, 1, 0, 'C');
        $pdf->Cell(78, 7, $custName, 1, 0, 'L');
        $pdf->Cell(24, 7, $lastInv, 1, 0, 'C');
        $pdf->Cell(24, 7, $lastPay, 1, 0, 'C');
        $pdf->Cell(24, 7, number_format($lastPayAmt, 2), 1, 0, 'R');
        $pdf->Cell(30, 7, number_format($bal, 2), 1, 1, 'R');

        $counter++;
    }

    // Grand Total row
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(160, 8, 'Grand Total', 1, 0, 'R'); // 10+78+24+24+24 = 160
    $pdf->Cell(30, 8, number_format($grandBalance, 2), 1, 1, 'R');

} else {
    $pdf->Cell(190, 8, 'No record found.', 1, 1, 'C');
}

if (ob_get_length()) { ob_end_clean(); }
$pdf->Output();
exit;