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

    // Configuration Parameters
    $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);

    // Date Range
    $datefrom = isset($datefrom) ? date("Y-m-d", strtotime($datefrom)) : date('Y-m-d', strtotime("-30 days"));
    $dateto = isset($dateto) ? date("Y-m-d", strtotime($dateto)) : date('Y-m-d');

    // Query Filters
    $qryDate = date("Y-m-d", strtotime($datefrom));
    $qryTo = date("Y-m-d", strtotime($dateto));
    $filterReport = " LEFT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id 
                      INNER JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.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')";

    // Filter by Customer Category (cat_type)
    if (isset($cat_type) && $cat_type != 'All') {
        $filterReport .= " AND cs.is_mart = '$cat_type'";
    }

    // Filter by Customer Name
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    }

    // Filter by Status
    if (isset($status) && $status != 'All') {
        $filterReport .= " AND inv.status ='$status'";
    }

    $filterReport .= " GROUP BY inv.id";
    $filterReport .= " ORDER BY cs.name ASC, inv.code";

    // Fetch Invoice Data
    $invoice = Invoice::GetInvoiceReportList($filterReport);

    if (!empty($invoice)) {
        $font = 10;
        $setx = 10;
        $wr = array(10, 20, 15, 35, 15, 15, 15, 15, 15, 15,22);

        $pdf = new FPDFWithOutWaterMark('P', 'mm', 'A4');
        $pdf->SetMargins(0, 0, 0);
        $pdf->SetTitle('Invoice Status Category Report');
        $pdf->AddPage();
        $pdf->Ln();
        $pdf->SetFont('Arial', 'B', 16);
        $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, 'Invoice Status Report', 0, 0, 'C');

        if ($customer_name != 'All') {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 14);
            $pdf->Cell(0, 6, $customer->name, 0, 0, 'C');
        }

        $pdf->Ln();
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');
        $pdf->Ln();
        $pdf->Ln();
        $pdf->SetX($setx);
        $header = array('S.No', 'Date', 'Invoice', 'Customer', 'Status', 'Price', 'Discount', 'Sub Total', 'Payment', 'Balance','Days Passed');

        function FancyTable($header, $data, $product_id, $setx, $customer_name)
        {
            global $pdf;

            $totalDiscount = 0;
            $productQtyTotal = 0;
            $costPriceTotal = 0;
            $unitPriceTotal = 0;
            $totalProfit = 0;
            $PayTotal = 0;
            $BalTotal = 0;

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

            // Header
            $wr = array(10, 20, 15, 35, 15, 15, 15, 15, 15, 15,22);
            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 = 1;
            $counter_pagebreak = 1;
            $totalAmount = 0;

            if ($data) {
                foreach ($data as $row) {
                    $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                    $discount_price = $row->discount_price + intval($row->add_discount_price);
                    $invoiceDate = strtotime($row->create_date);
                    $currentDate = strtotime(date('Y-m-d'));
                    $daysPassed = floor(($currentDate - $invoiceDate) / (60 * 60 * 24));

                    $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', strtotime($row->create_date)), 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[2], 7, $row->code, 'LRBT', 0, 'L', $fill);
                    $pdf->SetFont('Arial', '', 7);
                    $pdf->Cell($wr[3], 7, strlen($customer->name) > 100 ? substr($customer->name, 0, 100) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                    $pdf->SetFont('Arial', '', 8);

                    if ($product_id == 'All' || $product_id == '') {
                        $productsQtys = 0;
                        $productsUnitCostPrice = 0;
                        $productsUnitSalePrice = 0;

                        $filterProducts = " WHERE invoice_id = '$row->invoice_id'";
                        $productSetup = Invoice::GetInvoiceProducts($filterProducts);

                        if ($productSetup) {
                            foreach ($productSetup as $productSetupRows) {
                              
                              
                              
                                $product = ProductSetup::GetProductSetupById($productSetupRows->product_id);
                                $productsQtys += $productSetupRows->product_qty;
                                $productsUnitCostPrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_cost_price), 2, '.', '');
                                $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_sale_price), 2, '.', '');
                            }
                        }

                        $subtotal = $productsUnitSalePrice - $productsUnitCostPrice;
                        $subtotal -= $discount_price;
                        $totalDiscount += $discount_price;
                        $productQtyTotal += $productsQtys;
                        $costPriceTotal += $productsUnitCostPrice;
                        $unitPriceTotal += $productsUnitSalePrice;
                        $totalProfit += $subtotal;

                        $filterPayment = " WHERE invoice_reference_code = '$row->invoice_id' AND status <> 'Cancel'";
                        $paymentData = Payment::GetPaymentList($filterPayment);
                        $pyBalance = 0;
                        foreach ($paymentData as $paymentDataRow) {
                            $pyBalance += $paymentDataRow->amount;
                        }
                        $PayTotal += $pyBalance;
                        $totBal = ($productsUnitSalePrice - $discount_price) - $pyBalance;
                        $BalTotal += $totBal;

                        $pdf->Cell($wr[4], 7, ($pyBalance < $row->total_amount && $pyBalance != 0) ? "Partial Pd" : $row->status, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, number_format(($productsUnitSalePrice), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 7, number_format(($discount_price), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 7, number_format(($productsUnitSalePrice - $discount_price), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 7, number_format($pyBalance, 0, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[9], 7, number_format($totBal, 0, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[10], 7, $daysPassed, 'LRBT', 0, 'R', $fill);
                    }

                    if ($counter == 33) {
                        $counter_pagebreak = 1;
                        $pdf->AddPage();
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', 'B', 8);
                        for ($i = 0; $i < count($header); $i++) {
                            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                        }
                    }

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

            // Totals
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 8);
            $pdf->Cell($wr[0], 7, '', '', 0, 'L');
            $pdf->Cell($wr[1], 7, '', '', 0, 'L');
            $pdf->Cell($wr[2], 7, '', '', 0, 'L');
            $pdf->Cell($wr[3], 7, '', '', 0, 'L');
            $pdf->Cell($wr[4], 7, "Total", 'LRBT', 0, 'R');
            $pdf->Cell($wr[5], 7, $unitPriceTotal, 'LRBT', 0, 'R');
            $pdf->Cell($wr[6], 7, number_format(($totalDiscount), 0, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[7], 7, number_format(($unitPriceTotal - $totalDiscount), 0, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[8], 7, number_format(($PayTotal), 0, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[9], 7, number_format(($BalTotal), 0, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[10], 7, '-', 'LRBT', 0, 'R');
        }

        FancyTable($header, $invoice, $product_id, $setx, $customer_name);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

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

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