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

try {

    if (!isset($_REQUEST['monthfrom']) || !isset($_REQUEST['monthto'])) {
        header('location: ../customer_monthly_comparison.php');
        exit;
    }

    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);

    // ✅ Convert incoming dd-mm-YYYY to Y-m-01
    $monthfrom = date("Y-m-01", strtotime($monthfrom));
    $monthto   = date("Y-m-01", strtotime($monthto));

    $setx = 10;

    // ✅ Landscape Legal
    $pdf = new FPDFWithOutWaterMark('L', 'mm', 'legal');
    $pdf->SetMargins(0, 0, 0);

    // ✅ IMPORTANT: Disable auto page break (we handle manually)
    $pdf->SetAutoPageBreak(false);

    $pdf->SetTitle('Customer Monthly Comparison Report');
    $pdf->AddPage();

    // ================= HEADER =================
    $pdf->Ln(5);
    $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 Monthly Comparison Report', 0, 0, 'C');

    $pdf->Ln();
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(0, 5, 'Range: ' . date('M Y', strtotime($monthfrom)) . ' - ' . date('M Y', strtotime($monthto)), 0, 0, 'C');

    $pdf->Ln(8);

    // ✅ Fetch data
    $result = Invoice::GetCustomerMonthlyComparisonReport($monthfrom, $monthto);

    if (!$result) {
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(0, 10, 'No record found.', 0, 0, 'C');
        if (ob_get_length()) { ob_end_clean(); }
        $pdf->Output();
        exit;
    }

    $months = $result["months"];
    $rows   = $result["rows"];

    // ================= BUILD HEADERS =================
    $header = array("S.No", "Customer Name");
    foreach ($months as $mth) {
        $header[] = date("M Y", strtotime($mth . "-01"));
    }
    $header[] = "Total Inv";
    $header[] = "Avg Value";
    $header[] = "Avg Days";
    $header[] = "Total Amount";

    // ================= WIDTH CALCULATION =================
    $usableWidth = 336; // legal landscape usable width when X=10

    $snoW   = 12;
    $custW  = 70;
    $totInvW = 18;
    $avgValW = 24;
    $avgDayW = 18;
    $totalAmtW = 28;

    $fixedWidth = $snoW + $custW + $totInvW + $avgValW + $avgDayW + $totalAmtW;

    $monthsCount = count($months);
    $monthW = 20;

    if ($monthsCount > 0) {
        $remaining = $usableWidth - $fixedWidth;
        $monthW = floor($remaining / $monthsCount);
        if ($monthW < 16) $monthW = 16;
        if ($monthW > 28) $monthW = 28;
    }

    $wr = array();
    $wr[] = $snoW;
    $wr[] = $custW;

    for ($i = 0; $i < $monthsCount; $i++) {
        $wr[] = $monthW;
    }

    $wr[] = $totInvW;
    $wr[] = $avgValW;
    $wr[] = $avgDayW;
    $wr[] = $totalAmtW;

    // ================= TOTALS =================
    $monthTotals = array();
    foreach ($months as $mth) {
        $monthTotals[$mth] = 0;
    }

    $grandTotalInvoices = 0;
    $grandTotalAmount   = 0;

    $repeatDaysSum = 0;
    $repeatDaysCount = 0;

    // ================= HEADER ROW FUNCTION =================
    function PrintHeaderRow($header, $wr, $setx)
    {
        global $pdf;

        $pdf->SetX($setx);
        $pdf->SetFillColor(224, 235, 255);
        $pdf->SetFont('Arial', 'B', 9);

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

    // ✅ Manual page break checker
    function CheckPageBreak($rowHeight, $header, $wr, $setx)
    {
        global $pdf;

        // Page height in landscape legal is 216mm
        // We keep bottom safe margin ~12mm
        $bottomLimit = 204;

        if ($pdf->GetY() + $rowHeight > $bottomLimit) {
            $pdf->AddPage();
            $pdf->Ln(5);
            PrintHeaderRow($header, $wr, $setx);
        }
    }

    // ================= PRINT TABLE =================
    PrintHeaderRow($header, $wr, $setx);

    $fill = false;
    $counter = 0;

    foreach ($rows as $r) {

        // ✅ Before printing each row, check if space exists
        CheckPageBreak(7, $header, $wr, $setx);

        $counter++;

        $pdf->SetX($setx);

        // S.No
        $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);

        // Customer Name (trim to avoid overflow)
        $customerName = $r->customer_name;
        if (strlen($customerName) > 38) {
            $customerName = substr($customerName, 0, 38) . "..";
        }
        $pdf->Cell($wr[1], 7, $customerName, 'LRBT', 0, 'L', $fill);

        // Month-wise counts
        $colIndex = 2;
        foreach ($months as $mth) {
            $col = "cnt_" . str_replace("-", "_", $mth);
            $val = isset($r->$col) ? (int)$r->$col : 0;

            $monthTotals[$mth] += $val;

            $pdf->Cell($wr[$colIndex], 7, $val, 'LRBT', 0, 'C', $fill);
            $colIndex++;
        }

        // Total invoices
        $totalInv = (int)$r->total_invoices;
        $pdf->Cell($wr[$colIndex], 7, $totalInv, 'LRBT', 0, 'C', $fill);
        $colIndex++;

        // Avg order value
        $avgVal = (float)$r->avg_order_value;
        $pdf->Cell($wr[$colIndex], 7, number_format($avgVal, 0, '.', ''), 'LRBT', 0, 'R', $fill);
        $colIndex++;

        // Avg repeat days
        $avgDays = (float)$r->avg_repeat_days;
        $pdf->Cell($wr[$colIndex], 7, number_format($avgDays, 1, '.', ''), 'LRBT', 0, 'C', $fill);
        $colIndex++;

        // Total amount
        $totalAmt = (float)$r->total_amount;
        $pdf->Cell($wr[$colIndex], 7, number_format($totalAmt, 0, '.', ''), 'LRBT', 0, 'R', $fill);

        $pdf->Ln();

        // Totals update
        $grandTotalInvoices += $totalInv;
        $grandTotalAmount += $totalAmt;

        if ($avgDays > 0) {
            $repeatDaysSum += $avgDays;
            $repeatDaysCount++;
        }

        $fill = !$fill;
    }

    // ✅ TOTAL ROW: Ensure it doesn't print half at bottom
    CheckPageBreak(7, $header, $wr, $setx);

    $overallAvgOrderValue = ($grandTotalInvoices > 0) ? ($grandTotalAmount / $grandTotalInvoices) : 0;
    $overallAvgRepeatDays = ($repeatDaysCount > 0) ? ($repeatDaysSum / $repeatDaysCount) : 0;

    $pdf->SetX($setx);
    $pdf->SetFont('Arial', 'B', 9);

    $pdf->Cell($wr[0] + $wr[1], 7, 'TOTAL', 'LRBT', 0, 'R');

    $colIndex = 2;
    foreach ($months as $mth) {
        $pdf->Cell($wr[$colIndex], 7, $monthTotals[$mth], 'LRBT', 0, 'C');
        $colIndex++;
    }

    $pdf->Cell($wr[$colIndex], 7, $grandTotalInvoices, 'LRBT', 0, 'C');
    $colIndex++;

    $pdf->Cell($wr[$colIndex], 7, number_format($overallAvgOrderValue, 0, '.', ''), 'LRBT', 0, 'R');
    $colIndex++;

    $pdf->Cell($wr[$colIndex], 7, number_format($overallAvgRepeatDays, 1, '.', ''), 'LRBT', 0, 'C');
    $colIndex++;

    $pdf->Cell($wr[$colIndex], 7, number_format($grandTotalAmount, 0, '.', ''), 'LRBT', 0, 'R');

    if (ob_get_length()) {
        ob_end_clean();
    }

    $pdf->Output();
    exit;

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