<?php
error_reporting('E_ALL');
ini_set('display_errors', '1');

try {

    if (!isset($_REQUEST['datefrom'])) {
        header('location: ../customer_sales_segregation.php');
        exit;
    }

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

    $m = new Manager();
    extract($_REQUEST);

    // ---- Project Config ----
    $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);

    // ---- Inputs ----
    $datefrom = isset($datefrom) ? $datefrom : "";
    $dateto   = isset($dateto) ? $dateto : "";
    $category_id = isset($category_id) ? $category_id : "All";

    if ($datefrom == "") {
        $datefrom = date('Y-m-d', strtotime("-30 days"));
    } else {
        $datefrom = date("Y-m-d", strtotime($datefrom));
    }
    if ($dateto == "") {
        $dateto = date('Y-m-d');
    } else {
        $dateto = date("Y-m-d", strtotime($dateto));
    }

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

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

    // ---- Optional Category Title ----
    $catTitle = "";
    if ($category_id != '' && $category_id != 'All') {
        $rowCat = $db->query_first("SELECT name FROM customer_category WHERE id='" . $category_id . "' LIMIT 1");
        if (!empty($rowCat) && !empty($rowCat['name'])) {
            $catTitle = $rowCat['name'];
        }
    }

    // ---- Filter for Segregation Method ----
    $filterReport = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust ON inv.customer_id = cust.id
        WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate'
          AND DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo'
          AND inv.status not in('Draft', 'Cancel') ";

    if ($category_id != '' && $category_id != 'All') {
        $filterReport .= " AND cust.category_id = '" . $category_id . "' ";
    }

    $filterReport .= " GROUP BY inv.customer_id ";

    // ---- Fetch Segregation Rows ----
    $rows = Invoice::GetCustomerSalesSegregationReport($filterReport);

    // ---- Buckets order ----
    $bucketOrder = array(
        'Up to 10,000',
        '10,001 to 20,000',
        '20,001 to 30,000',
        '30,001 to 50,000',
        '50,001 to 100,000',
        '100,001 to 200,000',
        '200,001 to 300,000',
        '300,001 to 400,000',
        '400,001 to 500,000',
        'Above 500,000'
    );

    // ---- Group rows by slab ----
    $bucketed = array();
    foreach ($bucketOrder as $b) { $bucketed[$b] = array(); }

    $grandTotal = 0;
    if ($rows) {
        foreach ($rows as $r) {
            $slab = $r->sales_slab;
            if (!isset($bucketed[$slab])) $bucketed[$slab] = array();
            $bucketed[$slab][] = $r;
            $grandTotal += (float)$r->total_amount;
        }
    }

    // ---- PDF Setup ----
    $setx = 10;
    $bottomMargin = 15; // keep consistent spacing from bottom
    $rowH = 7;

    $pdf = new FPDFWithOutWaterMark('P', 'mm', 'legal');
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetAutoPageBreak(false); // we do manual breaks for consistent header repeats
    $pdf->SetTitle('Customer Sales Segregation Report');
    $pdf->AddPage();

    // ---- Helper: prevent overlap by truncating text to fit width ----
    function FitText($text, $width)
    {
        global $pdf;
        $text = trim((string)$text);
        $text = preg_replace("/\s+/", " ", $text);

        if ($pdf->GetStringWidth($text) <= $width) return $text;

        $ellipsis = '...';
        $maxWidth = $width - $pdf->GetStringWidth($ellipsis);
        if ($maxWidth <= 0) return '';

        $len = strlen($text);
        while ($len > 0 && $pdf->GetStringWidth(substr($text, 0, $len)) > $maxWidth) {
            $len--;
        }
        return substr($text, 0, max(0, $len)) . $ellipsis;
    }

    // ---- Helper: page height / available bottom ----
    function PageBottomY()
    {
        global $pdf, $bottomMargin;
        // FPDF uses $pdf->h as page height in mm
        return ($pdf->h - $bottomMargin);
    }

    // ---- Helper: ensure space (prevents “half blank” pages) ----
    function EnsureSpace($needH)
    {
        global $pdf, $setx;
        if ($pdf->GetY() + $needH > PageBottomY()) {
            $pdf->AddPage();
        }
    }

    // ---- Header ----
    $pdf->Ln();
    $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 Sales Segregation Report', 0, 0, 'C');

    $pdf->Ln();
    $pdf->Ln();
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');

    if ($catTitle != "") {
        $pdf->Ln();
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(0, 6, ucwords($catTitle), 0, 0, 'C');
    }

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

    // ---- Columns (NO GST/NTN) + your requested sizing ----
    $header = array('S.No', 'Customer', 'Invoice', 'Location', 'Contact', 'Total');

    // Total width = 196mm
    $wr = array(
        15, // S.No
        66, // Customer
        16, // Invoice (reduced)
        40, // Location
        38, // Contact (increased)
        21  // Total
    );

    function PrintTableHeader($header, $wr, $setx)
    {
        global $pdf;
        $pdf->SetX($setx);
        $pdf->SetFillColor(224, 235, 255);
        $pdf->SetTextColor(0);
        $pdf->SetDrawColor(128, 0, 0);
        $pdf->SetLineWidth(.1);
        $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('');
    }

    // ---- Render each slab with Y-based page breaking (no blank half pages) ----
    foreach ($bucketOrder as $bucketName) {

        $list = $bucketed[$bucketName];
        $bucketTotal = 0;
        if (!empty($list)) {
            foreach ($list as $x) { $bucketTotal += (float)$x->total_amount; }
        }

        // Before slab title, ensure we can fit: title(8) + header(7) + 1 row(7) + total row(7) + spacing
        EnsureSpace(8 + 7 + $rowH + 7 + 6);

        // slab title
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(0, 8, $bucketName . "   (Customers: " . count($list) . ")", 0, 1, 'L');
        $pdf->SetFont('Arial', '', 9);

        // table header
        PrintTableHeader($header, $wr, $setx);

        $fill = false;
        $counter = 0;

        if (!empty($list)) {

            foreach ($list as $r) {
                $counter++;

                // ensure we have space for one row; if not, new page + header again
                if ($pdf->GetY() + $rowH > PageBottomY()) {
                    $pdf->AddPage();
                    PrintTableHeader($header, $wr, $setx);
                }

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

                $customer = FitText($r->customer_name, $wr[1] - 2);
                $location = FitText($r->location,      $wr[3] - 2);
                $contact  = FitText($r->contact,       $wr[4] - 2);

                $pdf->Cell($wr[0], $rowH, $counter, 'LRBT', 0, 'C', $fill);
                $pdf->Cell($wr[1], $rowH, $customer, 'LRBT', 0, 'L', $fill);
                $pdf->Cell($wr[2], $rowH, (int)$r->total_invoices, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[3], $rowH, $location, 'LRBT', 0, 'L', $fill);
                $pdf->Cell($wr[4], $rowH, $contact,  'LRBT', 0, 'L', $fill);
                $pdf->Cell($wr[5], $rowH, number_format($r->total_amount, 2, '.', ''), 'LRBT', 0, 'R', $fill);

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

        } else {
            // ensure space for "No Record"
            if ($pdf->GetY() + $rowH > PageBottomY()) {
                $pdf->AddPage();
                PrintTableHeader($header, $wr, $setx);
            }
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 9);
            $pdf->Cell(array_sum($wr), $rowH, 'No Record', 1, 1, 'C', false);
        }

        // Bucket total row - ensure space
        if ($pdf->GetY() + $rowH > PageBottomY()) {
            $pdf->AddPage();
            PrintTableHeader($header, $wr, $setx);
        }

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

        $pdf->Cell($wr[0] + $wr[1] + $wr[2] + $wr[3] + $wr[4], $rowH, 'Bucket Total', 'LRB', 0, 'R');
        $pdf->Cell($wr[5], $rowH, number_format($bucketTotal, 2, '.', ''), 'LRB', 0, 'R');
        $pdf->Ln();
        $pdf->Ln(4);
    }

    // ---- Grand Total (ensure space) ----
    EnsureSpace(10);

    $pdf->SetX($setx);
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(0, 8, 'Grand Total: ' . number_format($grandTotal, 2, '.', ''), 0, 1, 'L');

    $pdf->Output();
    ob_end_flush();
    exit;

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