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

try {

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

    include_once('../../../classes/manager.class.php');
    include_once('../../../classes/PHPMailer/PHPMailerAutoload.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);
    define('PROJECT_DISCOUNT', $param_data->is_discount);
    define('PROJECT_TAX', $param_data->is_tax);

    $datefrom = "";
    $dateto = "";
    $cat_name = array("All");
    $mart_type = "All";

    extract($_REQUEST);

    /*
     * Normalize category input.
     * Frontend sends cat_name[] for multiple categories.
     */
    if (!isset($cat_name) || $cat_name == "") {
        $cat_name = array("All");
    }

    if (!is_array($cat_name)) {
        $cat_name = array($cat_name);
    }

    if (!isset($mart_type) || $mart_type == "") {
        $mart_type = "All";
    }

    /*
     * Date handling
     */
    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));

    /*
     * Build report filter
     * Same as frontend:
     * - Date range
     * - Exclude Draft and Cancel invoices
     * - Multiple customer category filter
     * - Customer type filter
     */
    $filterReport = "
        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')
    ";

    /*
     * Multiple category filter
     */
    if (!in_array('All', $cat_name)) {
        $catIds = array();

        foreach ($cat_name as $catId) {
            $catId = intval($catId);
            if ($catId > 0) {
                $catIds[] = $catId;
            }
        }

        if (!empty($catIds)) {
            $filterReport .= " AND cust.category_id IN (" . implode(",", $catIds) . ") ";
        }
    }

    /*
     * Customer type filter
     */
    if ($mart_type == 'Mart') {
        $filterReport .= " AND cust.is_mart = '1' ";
    } elseif ($mart_type == 'Wholesaler') {
        $filterReport .= " AND cust.is_mart = '0' ";
    }

    /*
     * Customer-wise summary
     */
    $filterReport .= "
        GROUP BY inv.customer_id
        ORDER BY cust.name ASC
    ";

    if (!empty($filterReport)) {

        /*
         * Keep table inside portrait legal page.
         * Legal width in portrait = approx 216mm.
         * With SetX(5), table width 205mm fits safely.
         */
        $setx = 5;

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

        $pdf->SetTitle('Multi Category Monthly Sales Report');
        $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, 'Multi Category Monthly Sales 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'
        );

        /*
         * Selected category names intentionally removed.
         * Do not print selected categories in PDF header.
         */

        /*
         * Customer type heading
         */
        if ($mart_type != 'All') {
            $pdf->Ln();
            $pdf->SetFont('Arial', 'B', 9);
            $pdf->Cell(0, 5, $mart_type . ' Customers', 0, 0, 'C');
        }

        $pdf->Ln(6);

        if (PROJECT_DISCOUNT == 1) {
            $header = array('S.No', 'Customer', 'Category', '# Invoice', 'Qty', 'Carton', 'Sale Price', 'Discount', 'Total');
        } else {
            $header = array('S.No', 'Customer', 'Category', '# Invoice', 'Qty', 'Carton', 'Sale Price', 'Total');
        }

        function FancyTableMultiCategory($header, $filterReport, $setx)
        {
            global $pdf;

            $totalInvoiceCount = 0;
            $productQtyTotal = 0;
            $cartonQtyTotal = 0;
            $unitPriceTotal = 0;
            $totalDiscount = 0;
            $totalProfit = 0;

            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetDrawColor(128, 0, 0);
            $pdf->SetLineWidth(.1);
            $pdf->SetFont('Arial', 'B', 6.5);

            /*
             * Column widths adjusted to keep Total column inside the page.
             *
             * PROJECT_DISCOUNT = 1:
             * Total width = 205mm
             * SetX = 5
             * End position = 210mm, safe for portrait legal width.
             */
            if (PROJECT_DISCOUNT == 1) {
                $wr = array(
                    8,   // S.No
                    52,  // Customer
                    31,  // Category
                    14,  // # Invoice
                    17,  // Qty
                    17,  // Carton
                    22,  // Sale Price
                    20,  // Discount
                    24   // Total
                );
            } else {
                /*
                 * Total width = 205mm
                 */
                $wr = array(
                    8,   // S.No
                    58,  // Customer
                    34,  // Category
                    15,  // # Invoice
                    18,  // Qty
                    18,  // Carton
                    27,  // Sale Price
                    27   // Total
                );
            }

            /*
             * Print table header
             */
            $pdf->SetX($setx);

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

            $pdf->Ln();

            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);

            $fill = false;
            $counter_pagebreak = 1;

            /*
             * Fetch report data
             */
            $qry = Invoice::GetInvoiceCustomerReportListMonthlySaleMultiCategory($filterReport);
            $counter = 0;

            if ($qry) {
                foreach ($qry as $qery) {
                    $counter++;

                    $salePrice = $qery->sale_price;
                    $discountAmount = $qery->total_discount;
                    $netTotal = $qery->total_amount;

                    $customerName = $qery->customer_name;
                    $categoryName = $qery->category_name;

                    /*
                     * Trim long names to avoid overlapping in portrait PDF.
                     */
                    if (strlen($customerName) > 31) {
                        $customerName = substr($customerName, 0, 28) . '...';
                    }

                    if (strlen($categoryName) > 19) {
                        $categoryName = substr($categoryName, 0, 16) . '...';
                    }

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

                    if (PROJECT_DISCOUNT == 1) {

                        $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 7, $customerName, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 7, $categoryName, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[3], 7, $qery->total_invoices, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 7, number_format($qery->product_qty, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, number_format($qery->carton_qty, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 7, number_format($salePrice, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 7, number_format($discountAmount, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 7, number_format($netTotal, 2, '.', ''), 'LRBT', 0, 'R', $fill);

                    } else {

                        $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 7, $customerName, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 7, $categoryName, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[3], 7, $qery->total_invoices, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 7, number_format($qery->product_qty, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, number_format($qery->carton_qty, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 7, number_format($salePrice, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 7, number_format($netTotal, 2, '.', ''), 'LRBT', 0, 'R', $fill);

                    }

                    $totalInvoiceCount += $qery->total_invoices;
                    $productQtyTotal += $qery->product_qty;
                    $cartonQtyTotal += $qery->carton_qty;
                    $unitPriceTotal += $salePrice;
                    $totalDiscount += $discountAmount;
                    $totalProfit += $netTotal;

                    /*
                     * Page break.
                     */
                    if ($counter == 40 || ($counter != 40 && ($counter_pagebreak) % 43 == 0)) {

                        $counter_pagebreak = 1;
                        $pdf->AddPage();

                        $pdf->SetX($setx);
                        $pdf->SetFillColor(224, 235, 255);
                        $pdf->SetTextColor(0);
                        $pdf->SetDrawColor(128, 0, 0);
                        $pdf->SetLineWidth(.1);
                        $pdf->SetFont('Arial', 'B', 6.5);

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

                        $pdf->Ln();

                    } else {
                        $pdf->Ln();
                    }

                  //  $fill = !$fill;
                    $counter_pagebreak++;
                }
            }

            /*
             * Total row
             */
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 8);

            if (PROJECT_DISCOUNT == 1) {

                $pdf->Cell($wr[0], 7, '', 'LB', 0, 'L');
                $pdf->Cell($wr[1], 7, '', 'LB', 0, 'L');
                $pdf->Cell($wr[2], 7, 'Total', 'LRB', 0, 'L');
                $pdf->Cell($wr[3], 7, number_format($totalInvoiceCount, 0, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[4], 7, number_format($productQtyTotal, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[5], 7, number_format($cartonQtyTotal, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[6], 7, number_format($unitPriceTotal, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[7], 7, number_format($totalDiscount, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[8], 7, number_format($totalProfit, 2, '.', ''), 'LRB', 0, 'R');

            } else {

                $pdf->Cell($wr[0], 7, '', 'LB', 0, 'L');
                $pdf->Cell($wr[1], 7, '', 'LB', 0, 'L');
                $pdf->Cell($wr[2], 7, 'Total', 'LRB', 0, 'L');
                $pdf->Cell($wr[3], 7, number_format($totalInvoiceCount, 0, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[4], 7, number_format($productQtyTotal, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[5], 7, number_format($cartonQtyTotal, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[6], 7, number_format($unitPriceTotal, 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[7], 7, number_format($totalProfit, 2, '.', ''), 'LRB', 0, 'R');

            }
        }

        FancyTableMultiCategory($header, $filterReport, $setx);

    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

    $pdf->Output();
    if (ob_get_level() > 0) { ob_end_flush(); }
    exit;

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