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

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


    $customer_name = $_GET['customer_name'];

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

    $balanceAmount = 0;
    $totalCreditAmount = 0;
    $totalDebitAmount = 0;

    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));
    $filterReport = " WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo' ";
    if (isset($cat_name) && $cat_name != 'All') {
        if (isset($customer_name) && $customer_name != 'All') {
            $filterReport .= " AND inv.customer_id ='$customer_name'";
        } else {
            $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
            $filterCat = " WHERE category_id = '$cat->id'";
            $cust = CustomerSetup::GetCustomerSetupList($filterCat);
            $custArray = array();
            foreach ($cust AS $custRow) {
                $custArray[] = $custRow->id;
            }
            $customers = implode(',', $custArray);
            $filterReport .= " AND inv.customer_id IN (" . $customers . ")";
        }
    }
    if (isset($invoice_status) && $invoice_status != 'All') {
        $filterReport .= " AND inv.status = '$invoice_status'";
    } else {
        $filterReport .= " AND inv.status not in('Draft', 'Cancel')";
    }
    $filterReport .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.code, pay.customer_id, pay.invoice_reference_code, pay.payment_type, pay.amount,
pay.cheque_bank_name, pay.cheque_number, pay.cheque_payee_name, pay.cheque_date, pay.bank_name, pay.bank_account_number, pay.party_name, pay.from_bank_name,
'', '', '','', '', ''

 from " . TABLE_PAYMENT . " AS pay WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo' AND pay.status <> 'Cancel' ";

    if (isset($cat_name) && $cat_name != 'All') {
        if (isset($customer_name) && $customer_name != 'All') {
            $filterReport .= " AND pay.customer_id ='$customer_name'";
        } else {
            $filterReport .= " AND pay.customer_id IN (" . $customers . ")";
        }
    }

    $filterReport .= " ORDER BY create_date";

//Opening Balance
    $qryDatePrevious = date('Y-m-d', strtotime('-1 day', strtotime($qryDate)));

    $filterReportOpening = " WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryDatePrevious' ";

    if (isset($cat_name) && $cat_name != 'All') {
        if (isset($customer_name) && $customer_name != 'All') {
            $filterReportOpening .= " AND inv.customer_id ='$customer_name'";
        } else {
            $filterReportOpening .= " AND inv.customer_id IN (" . $customers . ")";
        }
    }
    if (isset($invoice_status) && $invoice_status != 'All') {
        $filterReportOpening .= " AND inv.status = '$invoice_status'";
    } else {
        $filterReportOpening .= " AND inv.status not in('Draft', 'Cancel')";
    }
    $filterReportOpening .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.code, pay.customer_id, pay.invoice_reference_code, pay.payment_type, pay.amount,
pay.cheque_bank_name, pay.cheque_number, pay.cheque_payee_name, pay.cheque_date, pay.bank_name, pay.bank_account_number, pay.party_name, pay.from_bank_name,
'', '', '','', '', ''
 from " . TABLE_PAYMENT . " AS pay WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryDatePrevious' AND pay.status <> 'Cancel' ";

    if (isset($cat_name) && $cat_name != 'All') {
        if (isset($customer_name) && $customer_name != 'All') {
            $filterReportOpening .= " AND pay.customer_id ='$customer_name'";
        } else {
            $filterReportOpening .= " AND pay.customer_id IN (" . $customers . ")";
        }
    }
    $filterReportOpening .= " ORDER BY create_date";
    //Opening Balance

    $qryOpening = Invoice::GetInvoicePaymentReportLists($filterReportOpening);
    if ($qryOpening) {
        foreach ($qryOpening as $qeryOpening) {
            if ($qeryOpening->nameTable == 'invoice') {
                $balanceAmount -= $qeryOpening->total_amount;
                $totalCreditAmount += $qeryOpening->total_amount;
            } else {
                $balanceAmount += $qeryOpening->amount;
                $totalDebitAmount += $qeryOpening->amount;
            }
        }
    }

    $invoice = Invoice::GetInvoicePaymentReportLists($filterReport);

    $opBalance = 0;
    $customerIds = array();
    foreach ($invoice as $qery) {
        if (!in_array($qery->customer_id, $customerIds) && $qery->nameTable == 'invoice') {
            $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
            $opBalance += $customer->balance;
            $customerIds[] = $qery->customer_id;
        }
    }
    $balanceAmount -= $opBalance;
    $totalCreditAmount += $opBalance;

    if (!empty($invoice)) {

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

        $pdf = new FPDFWithOutWaterMark('L', 'mm', 'A4');
        $pdf->SetMargins(0, 0, 0);

        $pdf->SetTitle('Category Customer Ledger 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, 'Category Customer Ledger 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', '', 10);
        $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', 'Head', 'Date', 'Inv. / Pay.', 'Customer', 'Status', 'Pay. Type', 'Debit', 'Credit', 'Balance');

        function FancyTable($header, $data, $customer_name, $setx, $totalDebitAmount, $totalCreditAmount, $balanceAmount)
        {
            global $pdf;

            $totalDiscount = 0;
            $productQtyTotal = 0;
            $costPriceTotal = 0;
            $unitPriceTotal = 0;
            $totalProfit = 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);
            // Header
            $wr = array(10, 18, 20, 18, 100, 18, 18, 28, 28, 28);

            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('');
            // Data
            $fill = false;

            $counter = 0;
            $counter_pagebreak = 1;
            if ($data) {
                $countdown = 1;
                foreach ($data AS $row) {
                    $counter++;
                    if ($counter == 1) {
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 9);
                        $pdf->Cell($wr[0], 6, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 6, 'Opening', 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[2], 6, '-', 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 6, '-', 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 6, '-', 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 6, '-', 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 6, '-', 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 6, $totalDebitAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 6, $totalCreditAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[9], 6, $balanceAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Ln();
                        $countdown++;
                        $counter++;
                    }

                    if ($row->nameTable == 'invoice') {
                        $invoiceNumber = $row->code;
                        $balanceAmount -= $row->total_amount;
                        $totalCreditAmount += $row->total_amount;
                        $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);

                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 9);
                        $pdf->Cell($wr[0], 6, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 6, 'Invoice', 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[2], 6, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 6, $row->code, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 6, ucwords(strtolower($customer->name)), 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[5], 6, $row->status, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[6], 6, '-', 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[7], 6, 0, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 6, $row->total_amount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[9], 6, $balanceAmount, 'LRBT', 0, 'R', $fill);
                    }
                    $balanceAmount += intval($row->amount);
                    $totalDebitAmount += intval($row->amount);
                    if ($row->nameTable == 'payment') {
                        $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 9);
                        $pdf->Cell($wr[0], 6, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 6, 'Payment', 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[2], 6, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 6, $row->code, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 6, ucwords(strtolower($customer->name)), 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[5], 6, '-', 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[6], 6, $row->payment_type, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[7], 6, $row->amount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 6, 0, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[9], 6, $balanceAmount, 'LRBT', 0, 'R', $fill);
                    }
                    if ($counter == 23 || ($counter != 23 && ($counter_pagebreak) % 27 == 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();
                    $fill = !$fill;
                    $counter_pagebreak++;
                    $countdown++;
                }
            }
            //$pdf->SetFillColor(255, 204, 0);
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 9);
            $pdf->Cell($wr[0], 6, '', '', 0, 'L');
            $pdf->Cell($wr[1], 6, '', '', 0, 'L');
            $pdf->Cell($wr[2], 6, '', '', 0, 'L');
            $pdf->Cell($wr[3], 6, "", '', 0, 'R');
            $pdf->Cell($wr[4], 6, "", '', 0, 'R');

            $pdf->Cell($wr[5], 6, "", '', 0, 'R');
            $pdf->Cell($wr[6], 6, "Total", 'LRBT', 0, 'R');
            $pdf->Cell($wr[7], 6, $totalDebitAmount, 'LRBT', 0, 'R');
            $pdf->Cell($wr[8], 6, $totalCreditAmount, 'LRBT', 0, 'R', "");
            if ($totalDebitAmount > $totalCreditAmount) {
                $cashType = 'Db';
            } else {
                $cashType = 'Cr';
            }
            $pdf->Cell($wr[9], 6, ($totalCreditAmount - $totalDebitAmount) . ' ' . $cashType, 'LRBT', 0, 'R', "");
        }

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

    $pdf->Output();
    if (ob_get_level() > 0) { ob_end_flush(); }
    exit;
} catch (Exception $e) {
    echo $e->getMessage();
}
?>