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

    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'  AND inv.status not in('Draft', 'Cancel') ";
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    }
    $filterReport .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.customer_id, pay.amount,
'', '', '','', pay.status

 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($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND pay.customer_id ='$customer_name'";
    }
    $filterReport .= " ORDER BY customer_id";
    //Opening Balance

    $invoice = Invoice::GetInvoicePaymentReportListsForOwner($filterReport);
    if (!empty($invoice)) {

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

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

        $pdf->SetTitle('Payment 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, 'Customer Payment 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', '', 7);
        $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);
        if ($customer_name == '' || $customer_name == 'All') {
            $header = array('S.No', 'Customer', 'Opening', 'Debit', 'Credit', 'Balance');
        } else {
            $header = array('S.No', 'Customer', 'Opening', 'Debit', 'Credit', 'Balance');
        }

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

            $subbalanceAmount = 0;
            $subtotalCreditAmount = 0;
            $subtotalDebitAmount = 0;
            $previousbalanceAmounttotal = 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', 10);
            // Header
            if ($customer_name == '' || $customer_name == 'All') {
                $wr = array(15, 90, 20, 25, 25, 25);
            } else {
                $wr = array(15, 90, 20, 25, 25, 25);
            }
            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;
            $count = 0;
            $counter_pagebreak = 1;
            if ($data) {
                $countdown = 1;
                foreach ($data AS $row) {
                    $customerids[] = $row->customer_id;
                    $counter++;
                    $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'  AND inv.status not in('Draft', 'Cancel') ";
                    $filterReportOpening .= " AND inv.customer_id ='$row->customer_id'";
                    $filterReportOpening .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.customer_id  AS customer_id, pay.amount,
'', '', '','', ''
 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' ";
                    $filterReportOpening .= " AND pay.customer_id ='$row->customer_id'";
                    $filterReportOpening .= " ORDER BY create_date";
                    $qryOpening = Invoice::GetInvoicePaymentReportListsForOwner($filterReportOpening);
                    $previoustotalDebitAmount = 0;
                    $previoustotalCreditAmount = 0;
                    $previousbalanceAmount = 0;
                    if ($qryOpening) {
                        foreach ($qryOpening as $qeryOpening) {
                            if ($qeryOpening->nameTable == 'invoice') {
                                $previousbalanceAmount += $qeryOpening->total_amount;
                                $previoustotalCreditAmount -= $qeryOpening->total_amount;
                            } else {
                                $previousbalanceAmount -= $qeryOpening->amount;
                                $previoustotalDebitAmount -= $qeryOpening->amount;
                            }
                        }
                    }
                    if ($row->nameTable == 'invoice') {
                        $balanceAmount -= $row->total_amount;
                        $totalCreditAmount += $row->total_amount;
                        $subbalanceAmount -= $row->total_amount;
                        $subtotalCreditAmount += $row->total_amount;
                    }
                    $balanceAmount += $row->amount;
                    $totalDebitAmount += $row->amount;
                    $subbalanceAmount += $row->amount;
                    $subtotalDebitAmount += $row->amount;
                    if ((isset($data[$counter]->customer_id) && $data[$counter]->customer_id != $row->customer_id) || count($data) == 1 || $counter == count($data)) {
                        $count++;
                        $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                        $previousbalanceAmount += $customer->balance;
                        $previoustotalCreditAmount -= $customer->balance;
                        $previousbalanceAmounttotal += $previousbalanceAmount;
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 10);
                        $pdf->Cell($wr[0], 6, $count, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 6, $customer->name, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 6, $previousbalanceAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 6, $subtotalDebitAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 6, $subtotalCreditAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 6, ($subtotalCreditAmount - $subtotalDebitAmount) + $previousbalanceAmount, 'LRBT', 0, 'R', $fill);

                        $subbalanceAmount = 0;
                        $subtotalCreditAmount = 0;
                        $subtotalDebitAmount = 0;

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

                    if ($countdown == 38 || ($countdown != 38 && ($counter_pagebreak) % 42 == 0)) {
                        $countdown++;
                        $counter_pagebreak = 1;
                        $pdf->AddPage();
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', 'B', 10);
                        for ($i = 0; $i < count($header); $i++)
                            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);

                        $pdf->Ln();
                    }

                }
            }
            $customersfilter = " WHERE status = 'active'";
            $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
            if ($customers) {
                foreach ($customers AS $customersRow) {
                    if (!in_array($customersRow->id, $customerids)) {
                        $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'  AND inv.status not in('Draft', 'Cancel') ";
                        $filterReportOpening .= " AND inv.customer_id ='$customersRow->id'";
                        $filterReportOpening .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.customer_id  AS customer_id, pay.amount,
'', '', '','', ''
 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' ";
                        $filterReportOpening .= " AND pay.customer_id ='$customersRow->id'";
                        $filterReportOpening .= " ORDER BY create_date";
                        $qryOpening = Invoice::GetInvoicePaymentReportListsForOwner($filterReportOpening);
                        $previoustotalDebitAmount = 0;
                        $previoustotalCreditAmount = 0;
                        $previousbalanceAmount = 0;

                        $customer = CustomerSetup::GetCustomerSetupById($customersRow->id);
                        if ($qryOpening) {
                            foreach ($qryOpening as $qeryOpening) {
                                if ($qeryOpening->nameTable == 'invoice') {
                                    $previousbalanceAmount += $qeryOpening->total_amount;
                                    $previoustotalCreditAmount -= $qeryOpening->total_amount;
                                } else {
                                    $previousbalanceAmount -= $qeryOpening->amount;
                                    $previoustotalDebitAmount += $qeryOpening->amount;
                                }
                            }
                        }
                        $previousbalanceAmount += $customer->balance;
                        $previoustotalCreditAmount -= $customer->balance;
                        $count++;
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 10);
                        $pdf->Cell($wr[0], 6, $count, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 6, $customer->name, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 6, $previousbalanceAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[3], 6, $subtotalDebitAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 6, $subtotalCreditAmount, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 6, ($subtotalCreditAmount - $subtotalDebitAmount) + $previousbalanceAmount, 'LRBT', 0, 'R', $fill);

                        $previousbalanceAmounttotal += $previousbalanceAmount;
                        $subbalanceAmount = 0;
                        $subtotalCreditAmount = 0;
                        $subtotalDebitAmount = 0;


                        if ($countdown == 38 || ($countdown != 38 && ($counter_pagebreak) % 42 == 0)) {
                            $countdown++;
                            $counter_pagebreak = 1;
                            $pdf->AddPage();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', 'B', 10);
                            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', '', 10);
            $pdf->Cell($wr[0], 6, "", 'LBT', 0, 'R');
            $pdf->Cell($wr[1], 6, "Total", 'RBT', 0, 'R');
            $pdf->Cell($wr[2], 6, $previousbalanceAmounttotal, 'LRBT', 0, 'R');
            $pdf->Cell($wr[3], 6, $totalDebitAmount, 'LRBT', 0, 'R');
            $pdf->Cell($wr[4], 6, $totalCreditAmount, 'LRBT', 0, 'R');
            $pdf->Cell($wr[5], 6, ($totalCreditAmount + $previousbalanceAmounttotal) - $totalDebitAmount .($totalDebitAmount > $totalCreditAmount ? "Db" : "Cr"), 'LRBT', 0, 'R');

        }

        FancyTable($header, $invoice, $customer_name, $qryDate, $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();
}
?>