<?php
ob_start(); // ✅ Prevent "Some data has already been output" issues
error_reporting(0);
ini_set('display_errors', '0');

try {

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

    $m = new Manager();
    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);

    // ================= PDF Settings =================
    $setx = 10;

    $pdf = new FPDFWithOutWaterMark('P', 'mm', 'legal');
    $pdf->SetMargins(0, 0, 0);

    $pdf->SetTitle('Customer Pending Balance Report');
    $pdf->AddPage();
    $pdf->Ln();

    // ================= Header =================
    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');

    $pdf->SetX($setx);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(0, 8, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');

    $pdf->Ln();
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 6, 'Customer Pending Balance Report', 0, 0, 'C');

    $pdf->Ln();
    $pdf->Ln();
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(0, 4, 'Sorted by Highest Balance to Lowest', 0, 0, 'C');

    $pdf->Ln();
    $pdf->Ln();

    // ================= Table Header =================
    $pdf->SetX($setx);

    $header = array(
        'S.No',
        'Customer',
        'Invoices',
        'Last Payment',
        'Days',
        'Balance'
    );

    function FancyTablePendingBalance($header, $setx)
    {
        global $pdf;

        // Totals
        $totalBalance = 0;
        $totalPendingInvoices = 0;

        // Colors, line width and bold font
        $pdf->SetFillColor(224, 235, 255);
        $pdf->SetTextColor(0);
        $pdf->SetDrawColor(128, 0, 0);
        $pdf->SetLineWidth(.1);
        $pdf->SetFont('Arial', 'B', 10);

        // Column widths (Legal Portrait friendly)
        $wr = array(12, 75, 20, 30, 20, 30);

        // Header
        for ($i = 0; $i < count($header); $i++) {
            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
        }
        $pdf->Ln();

        // Font restore
        $pdf->SetFont('Arial', 'B', 9);
        $fill = false;

        // Page break tracking (same style)
        $counter_pagebreak = 1;

        // Fetch Data
        $rows = Invoice::GetCustomerPendingBalanceReport();

        $counter = 0;
        if ($rows) {
            foreach ($rows as $r) {
                $counter++;

                $totalBalance += (float)$r->balance;
                $totalPendingInvoices += (int)$r->pending_invoices;

                $pdf->SetX($setx);

                $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                $pdf->Cell($wr[1], 7, $r->customer_name, 'LRBT', 0, 'L', $fill);
                $pdf->Cell($wr[2], 7, $r->pending_invoices, 'LRBT', 0, 'C', $fill);
                $pdf->Cell($wr[3], 7, number_format($r->last_payment_amount, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[4], 7, $r->days_since_last_payment, 'LRBT', 0, 'C', $fill);
                $pdf->Cell($wr[5], 7, number_format($r->balance, 2, '.', ''), 'LRBT', 0, 'R', $fill);

                // Page Break Logic
                if ($counter == 38 || ($counter != 38 && ($counter_pagebreak) % 42 == 0)) {
                    $counter_pagebreak = 1;
                    $pdf->AddPage();

                    $pdf->Ln(5);
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', 'B', 10);
                    for ($i = 0; $i < count($header); $i++) {
                        $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    }
                    $pdf->Ln();
                    $pdf->SetFont('Arial', 'B', 9);
                }

                $pdf->Ln();
                $fill = !$fill;
                $counter_pagebreak++;
            }

            // ================= TOTAL ROW =================
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 10);

            $pdf->Cell($wr[0], 7, '', 'LRBT', 0, 'C');
            $pdf->Cell($wr[1], 7, 'TOTAL', 'LRBT', 0, 'R');
            $pdf->Cell($wr[2], 7, $totalPendingInvoices, 'LRBT', 0, 'C');
            $pdf->Cell($wr[3], 7, '', 'LRBT', 0, 'R');
            $pdf->Cell($wr[4], 7, '', 'LRBT', 0, 'C');
            $pdf->Cell($wr[5], 7, number_format($totalBalance, 2, '.', ''), 'LRBT', 0, 'R');

        } else {

            // No data row
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell(array_sum($wr), 8, 'No pending balances found.', 1, 0, 'C', false);
        }
    }

    FancyTablePendingBalance($header, $setx);

    // ✅ Clean buffer before output
    if (ob_get_length()) {
        ob_end_clean();
    }

    $pdf->Output();
    exit;

} catch (Exception $e) {
    if (ob_get_length()) {
        ob_end_clean();
    }
    echo $e->getMessage();
}
?>
