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

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

    // -------------------------------
    // Init / defaults
    // -------------------------------
    $datefrom       = "";
    $dateto         = "";
    $customer_name  = "All";
    $cat_name       = "All";

    $totalProfitPrevious   = 0;
    $totalPaymentsPrevious = 0;
    $costPriceTotal        = 0;
    $unitPriceTotal        = 0;
    $totalDiscount         = 0;
    $totalProfit           = 0;
    $productQtyTotal       = 0;
    $totalPayments         = 0;
    $openingBalance        = 0;

    extract($_REQUEST);

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

    // Keep printable format separate
    $displayDateFrom = date("d-m-Y", strtotime($datefrom));
    $displayDateTo   = date("d-m-Y", strtotime($dateto));

    $qryDate = $datefrom; // already Y-m-d
    $qryTo   = $dateto;   // already Y-m-d

    // Fallbacks if not set
    if (!isset($customer_name) || $customer_name == "") {
        $customer_name = 'All';
    }
    if (!isset($cat_name) || $cat_name == "") {
        $cat_name = 'All';
    }

    // -------------------------------
    // Build filter (same logic as web version)
    // -------------------------------
    $baseWhere = " 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 ($customer_name != '' && $customer_name != 'All') {
        // DETAIL: single customer
        $filterReport  = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                              ON inv.customer_id = cust.id
                           JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr 
                              ON inv.id = invPr.invoice_id ";
        $filterReport .= $baseWhere;

        // Category filter (if selected)
        if ($cat_name != 'All') {
            $filterReport .= " AND cust.category_id = '$cat_name'";
        }

        // Specific customer
        $filterReport .= " AND inv.customer_id = '$customer_name'";

        // Group by invoice
        $filterReport .= " GROUP BY inv.code ";

    } else {
        // SUMMARY: per customer (optionally within a category)
        $filterReport  = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                              ON inv.customer_id = cust.id ";
        $filterReport .= $baseWhere;

        // Category filter (if selected)
        if ($cat_name != 'All') {
            $filterReport .= " AND cust.category_id = '$cat_name'";
        }

        // Group by customer
        $filterReport .= " GROUP BY inv.customer_id ";
    }

    // Final ordering
    $filterReport .= " ORDER BY cust.name, customer_id, create_date, code ";

    if (!empty($filterReport)) {

        $font    = 10;
        $picx    = 100;
        $setx    = 10;
        $multi   = 210;
        $picsetx = 150;
        $w       = array(50, 80, 50, 80);
        $path    = "../../../";

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

        $pdf->SetTitle('Monthly Sales Report');
        $pdf->AddPage();
        $pdf->Ln();
        $pdf->SetFont('Arial', 'B', 14);
        $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(0, 8, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');
        $pdf->Ln();
        $pdf->SetFont('Arial', '', 14);
        $pdf->Cell(0, 6, 'Monthly Sales Report', 0, 0, 'C');

        $pdf->Ln();
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(0, 4, 'For the period of: ' . $displayDateFrom . ' - ' . $displayDateTo, 0, 0, 'C');

        // Show Category (if any)
        if ($cat_name != '' && $cat_name != 'All') {
            $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
            if (!empty($catObj)) {
                $pdf->Ln();
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell(0, 5, 'Category: ' . ucwords($catObj->name), 0, 0, 'C');
            }
        }

        // Show Customer (if any one customer)
        if ($customer_name != '' && $customer_name != 'All') {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            if (!empty($customer)) {
                $pdf->Ln();
                $pdf->SetFont('Arial', '', 12);
                $pdf->Cell(0, 6, ucwords($customer->name), 0, 0, 'C');
            }
        }

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

        if ($customer_name == '' || $customer_name == 'All') {
            $header = array('S.No', 'Customer', '# of Invoice', 'Sale Price', 'Discount', 'Total');
        } else {
            $header = array('S.No', 'Date', 'Invoice #', 'Qty', 'Sale Price', 'Discount', 'Total');
        }

        function FancyTable($header, $filterReport, $setx, $customer_name, $m)
        {
            global $pdf, $unitPriceTotal, $totalDiscount, $totalProfit;

            $productQtyTotal = 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', 9);

            // Column widths for both layouts
            if ($customer_name == '' || $customer_name == 'All') {
                $wr = array(20, 90, 20, 20, 20, 27);
            } else {
                $wr = array(20, 41, 20, 20, 32, 32, 32);
            }

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

            // Color and font restoration
            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetFont('');

            $fill = false;
            $counter_pagebreak = 1;

            if ($customer_name != '' && $customer_name != 'All') {

                // DETAIL: per invoice for a single customer
                $qry = Invoice::GetInvoiceCustomerReportListMonthlySale($filterReport);
                $counter = 0;
                if ($qry) {
                    foreach ($qry as $qery) {
                        $counter++;

                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 8);
                        $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 7, date('Y-m-d h:i A', strtotime($qery->create_date)), 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 7, $qery->code, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 7, $qery->product_qty, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 7, number_format(($qery->total_amount + $qery->discount_price), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, number_format(($qery->discount_price), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 7, number_format($qery->total_amount, 2, '.', ''), 'LRBT', 0, 'R', $fill);

                        $productQtyTotal += $qery->product_qty;
                        $unitPriceTotal  += ($qery->total_amount + $qery->discount_price);
                        $totalDiscount   += $qery->discount_price;
                        $totalProfit     += $qery->total_amount;

                        // Page break handling
                        if ($counter == 38 || ($counter != 38 && ($counter_pagebreak) % 42 == 0)) {
                            $counter_pagebreak = 1;
                            $pdf->AddPage();
                            $pdf->SetX($setx);
                            $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->Ln();
                    //    $fill = !$fill;
                        $counter_pagebreak++;
                    }
                }

            } else {

                // SUMMARY: per customer
                $qry = Invoice::GetInvoiceCustomerReportListMonthlySaleCustomers($filterReport);
                $counter = 0;
                if ($qry) {
                    foreach ($qry as $qery) {
                        $counter++;
                        $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
$pdf->SetX($setx);
$pdf->SetFont('Arial', '', 8);

// --- truncate customer name so it doesn't overflow the column ---
$customerName = $customer->name;
$maxWidth     = $wr[1] - 2; // Small margin inside the cell

if ($pdf->GetStringWidth($customerName) > $maxWidth) {
    // Keep chopping characters until it fits with "..."
    while ($pdf->GetStringWidth($customerName . '...') > $maxWidth && strlen($customerName) > 0) {
        $customerName = substr($customerName, 0, -1);
    }
    $customerName .= '...';
}
// ---------------------------------------------------------------

$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, $qery->total_invoices, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 7, number_format(($qery->total_amount + $qery->discount_price), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 7, number_format(($qery->discount_price), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, number_format($qery->total_amount, 2, '.', ''), 'LRBT', 0, 'R', $fill);

                        $unitPriceTotal  += ($qery->total_amount + $qery->discount_price);
                        $totalDiscount   += $qery->discount_price;
                        $totalProfit     += $qery->total_amount;

                        // Page break handling
                        if ($counter == 38 || ($counter != 38 && ($counter_pagebreak) % 42 == 0)) {
                            $counter_pagebreak = 1;
                            $pdf->AddPage();
                            $pdf->SetX($setx);
                            $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->Ln();
                     //   $fill = !$fill;
                        $counter_pagebreak++;
                    }
                }
            }

            // Total Row
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 9);
            $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');

            if ($customer_name != '' && $customer_name != 'All') {
                $pdf->Cell($wr[3], 7, $productQtyTotal, 'LRB', 0, 'R');
                $pdf->Cell($wr[4], 7, $unitPriceTotal, 'LRB', 0, 'R');
                $pdf->Cell($wr[5], 7, number_format(($totalDiscount), 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[6], 7, number_format(($totalProfit), 2, '.', ''), 'LRB', 0, 'R');
            } else {
                $pdf->Cell($wr[3], 7, $unitPriceTotal, 'LRB', 0, 'R');
                $pdf->Cell($wr[4], 7, number_format(($totalDiscount), 2, '.', ''), 'LRB', 0, 'R');
                $pdf->Cell($wr[5], 7, number_format(($totalProfit), 2, '.', ''), 'LRB', 0, 'R');
            }
        }

        FancyTable($header, $filterReport, $setx, $customer_name, $m);

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

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

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