<?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 = "";
    $customer_name = "All";
    $cat_name = "All";
    $mart_type = "All";

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

    extract($_REQUEST);

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

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

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

    /*
     * This file is only for detail print.
     * If customer is not selected, redirect back.
     */
    if ($customer_name == "" || $customer_name == "All") {
        header('location: ' . PROJECT_ADMIN_URL . 'report/monthly_sale.php');
        exit;
    }

    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 for DETAIL report only:
     * - Specific customer
     * - Invoice-wise rows
     * - Category filter through customer_setup.category_id
     * - Customer type filter through customer_setup.is_mart
     * - Exclude Draft and Cancel invoices
     */

    $filterReport = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                        ON inv.customer_id = cust.id ";

    $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') ";

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

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

    $filterReport .= " AND inv.customer_id = '$customer_name' ";
    $filterReport .= " GROUP BY inv.id ";
    $filterReport .= " ORDER BY cust.name, inv.customer_id, inv.create_date, inv.code ";

    if (!empty($filterReport)) {

        $font = 10;
        $picx = 100;
        $setx = 8;
        $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 Detail 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', '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, 'Monthly Sales Detail 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 ($cat_name != 'All') {
            $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
            if (!empty($catObj)) {
                $pdf->Ln();
                $pdf->SetFont('Arial', 'B', 10);
                $pdf->Cell(0, 5, $catObj->name . ' - Category', 0, 0, 'C');
            }
        }

        if ($mart_type != 'All') {
            $pdf->Ln();
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell(0, 5, $mart_type . ' Customers', 0, 0, 'C');
        }

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

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

        $pdf->SetX($setx);

        $header = array('S.No', 'Date', 'Invoice #', 'Qty', 'Carton', 'Sale Price', 'Discount', 'Total');

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

            $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', 8);

            /*
             * Detail report column widths.
             * Total width approx 200 mm, suitable for portrait legal page.
             */
            $wr = array(12, 38, 24, 22, 22, 28, 26, 28);

            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);
            $pdf->SetFont('');

            $fill = false;
            $counter_pagebreak = 1;

            $qry = Invoice::GetInvoiceCustomerReportListMonthlySale($filterReport);
            $counter = 0;

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

                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', 'B', 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, number_format($qery->product_qty, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[4], 7, number_format($qery->carton_qty, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[5], 7, number_format(($qery->total_amount + $qery->discount_price), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[6], 7, number_format(($qery->discount_price), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[7], 7, number_format($qery->total_amount, 2, '.', ''), 'LRBT', 0, 'R', $fill);

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

                    if ($counter == 38 || ($counter != 38 && ($counter_pagebreak) % 42 == 0)) {
                        $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();
                    } else {
                        $pdf->Ln();
                    }

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

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

            $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($productQtyTotal, 2, '.', ''), 'LRB', 0, 'R');
            $pdf->Cell($wr[4], 7, number_format($cartonQtyTotal, 2, '.', ''), 'LRB', 0, 'R');
            $pdf->Cell($wr[5], 7, number_format($unitPriceTotal, 2, '.', ''), 'LRB', 0, 'R');
            $pdf->Cell($wr[6], 7, number_format($totalDiscount, 2, '.', ''), 'LRB', 0, 'R');
            $pdf->Cell($wr[7], 7, number_format($totalProfit, 2, '.', ''), 'LRB', 0, 'R');
        }

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

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

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

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