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

    if (!isset($_REQUEST['datefrom'])) {
        header('location: ../customer.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(pur.lastupdated,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(pur.lastupdated,'%Y-%m-%d')<='$qryTo' ";

    if (isset($category_name) && $category_name != 'All') {
        $filterPurhcaseCat = " WHERE parent_id = '$category_name' ";
        $purchaseCat = PurchaseCategorySetup::GetPurchaseCategorySetupList($filterPurhcaseCat);
        if($purchaseCat){
            foreach($purchaseCat AS $purchaseCatRow){
                $purchaseCategory[] = $purchaseCatRow->id;
            }
            $purchaseCategoryString = implode("','", $purchaseCategory);
            $filterReport .= " AND pur.category_id IN ('".$purchaseCategoryString."')";
        }
    }

    $filterReport .= " UNION SELECT '' AS catname, id,'' AS descr, '' AS purchaseamount, create_date AS purchasedate, 'payment' AS nameTable,
                code , supplier_id, payment_type, amount, cheque_bank_name,
		cheque_number, cheque_payee_name, cheque_date, bank_name, bank_account_number, party_name, from_bank_name, create_date, description
		FROM " . TABLE_PURPAYMENT . " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' AND
		DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel' ";

    if (isset($category_name) && $category_name != 'All') {
        $filterReport .= " AND supplier_id ='$category_name'";
    }
    $filterReport .= " ORDER BY purchasedate";

//PreviousRecord
    $qryDatePrevious = date('Y-m-d', strtotime('-1 day', strtotime($qryDate)));
    $filterReportPrevious = " WHERE DATE_FORMAT(pur.lastupdated,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(pur.lastupdated,'%Y-%m-%d')<='$qryDatePrevious' ";

    if (isset($category_name) && $category_name != 'All') {
        if($purchaseCategoryString){
            $filterReportPrevious .= " AND pur.category_id IN ('".$purchaseCategoryString."')";
        }
    }
    $filterReportPrevious .= " UNION SELECT '' AS catname, id,'' AS descr, '' AS purchaseamount, create_date AS purchasedate, 'payment' AS nameTable,
                code , supplier_id, payment_type, amount, cheque_bank_name,
		cheque_number, cheque_payee_name, cheque_date, bank_name, bank_account_number, party_name, from_bank_name, create_date, description
		FROM " . TABLE_PURPAYMENT . "
		WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='2016-01-01' AND
		DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryDatePrevious' AND status <> 'Cancel' ";

    if (isset($category_name) && $category_name != 'All') {
        $filterReportPrevious .= " AND supplier_id ='$category_name'";
    }
    $filterReportPrevious .= " ORDER BY purchasedate";
//Previous Record

    $qryPrevious = Purpayment::GetPurpaymentListWithPayment($filterReportPrevious);
    //print_r($qryPrevious);
    if($qryPrevious){
        foreach($qryPrevious AS $qryPreviousRow){
            //echo $qryPreviousRow->purchaseamount." - ".$qryPreviousRow->amount."<br>";
            if ($qryPreviousRow->nameTable == 'purchase') {
                $totalPayablePrevious += $qryPreviousRow->purchaseamount;
            } else if($qryPreviousRow->nameTable == 'payment') {
                $totalPaymentsPrevious += $qryPreviousRow->amount;
            }
        }
        $openingBalance = number_format(($totalPayablePrevious - $totalPaymentsPrevious), 2, '.', '');
    }

    $qry = Purpayment::GetPurpaymentListWithPayment($filterReport);
    if (!empty($qry)) {

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

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

        $pdf->SetTitle('Purchase 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, 'Purchase Payment Report', 0, 0, 'C');

        if ($customer_name != 'All') {
            $filterPurhcaseCategory = " WHERE id = '$category_name' ";
            $purchaseCategory = PurchaseCategorySetup::GetPurchaseCategorySetupList($filterPurhcaseCategory);
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 14);
            $pdf->Cell(0, 6, $purchaseCategory[0]->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', 'Purchases', 'Type', 'Description', 'Detail', 'Payable', 'Paid', 'Balance');
//        $filterProductInvoice = " WHERE invoice_id = '$invoice_id'";
//        $productData = Invoice::GetInvoiceProducts($filterProductInvoice);

            function FancyTable($header, $data, $openingBalance, $product_id, $customer_name,  $setx)
            {
                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(.3);
                $pdf->SetFont('Arial', 'B', 9);
                // Header
                $wr = array(10, 15, 20, 15, 71, 71, 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 = 2;
                $counter_pagebreak = 1;
                $totalpayable = 0;
                $totalpaid = 0;
                if($data){
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 7);
                    $pdf->Cell($wr[0], 7, '1', 'LRBT', 0, 'C', $fill);
                    $pdf->Cell($wr[1], 7, '-', 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[2], 7, '-', 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[3], 7, '-', 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[4], 7, 'Opening', 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[5], 7, '-', 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[6], 7, '-', 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[7], 7, '-', 'LRBT', 0, 'R', $fill);
                    $pdf->Cell($wr[8], 7, number_format(($openingBalance)), 'LRBT', 0, 'R', $fill);
                    $pdf->Ln();

                    foreach ($data AS $row) {
                        if ($row->nameTable == 'purchase') {
                            $totalpayable += $row->purchaseamount;

                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 7);
                            $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                            $pdf->Cell($wr[1], 7, date('Y-m-d', strtotime($row->purchasedate)), 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[2], 7, $row->catname, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[3], 7, $row->nameTable, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[4], 7, strlen($row->descr) > 42 ? substr($row->descr,0,42)."..." : $row->descr, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[5], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[6], 7, number_format(($row->purchaseamount), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[7], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[8], 7, number_format(($openingBalance + ($totalpayable - $totalpaid))), 'LRBT', 0, 'R', $fill);
                        }
                        else if ($row->nameTable == 'payment') {
                            $bank = BankSetup::GetBankSetupById($row->bank_name);
                            $purCat = PurchaseCategorySetup::GetPurchaseCategorySetupById($row->supplier_id);
                            $totalpaid += $row->amount;

                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 7);
                            $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                            $pdf->Cell($wr[1], 7, date('Y-m-d', strtotime($row->purchasedate)), 'LRBT', 0, 'L', $fill);

                            $pdf->Cell($wr[2], 7, $purCat->name, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[3], 7, $row->nameTable, 'LRBT', 0, 'L', $fill);
                            if ($row->payment_type == 'party') {
                                $paymentDescription = 'Party: ' . $row->party_name . " - " . $row->cheque_number . "\n"."Cheque Details: " . $row->cheque_payee_name . " (" . $row->cheque_bank_name . " - " . date('d-m-Y', strtotime($qery->cheque_date)) . ")";
                            } else if ($row->payment_type == 'online') {
                                $paymentDescription = "From: " . $row->from_bank_name . "\n"."To: " . $bank->bank_name;
                            } else {
                                $paymentDescription = $bank->bank_name;
                                if ($row->payment_type == 'bank') {
                                    $paymentDescription .= " - " . $row->cheque_number . "\n";
                                    $paymentDescription .= "Cheque Details: " . $row->cheque_payee_name . " (" . $row->cheque_bank_name . " - " . date('d-m-Y', strtotime($row->cheque_date)) . ")";
                                }
                            }
                            $pdf->Cell($wr[4], 7, strlen($paymentDescription) > 56 ? substr($paymentDescription,0,56)."..." : $paymentDescription, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[5], 7, strlen($row->description) > 56 ? substr($row->description,0,56)."..." : $row->description, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[6], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[7], 7, $row->amount, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[8], 7, number_format(($openingBalance + ($totalpayable - $totalpaid))), 'LRBT', 0, 'R', $fill);

                        }
                        if($counter == 20 || ($counter != 20 && ($counter_pagebreak)%24==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++;
                        $counter_pagebreak++;
                    }
                }
                //$pdf->SetFillColor(255, 204, 0);
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 8);
                $pdf->Cell($wr[0], 7, '', '', 0, 'L');
                $pdf->Cell($wr[1], 7, '', '', 0, 'L');
                $pdf->Cell($wr[2], 7, "", '', 0, 'R');
                $pdf->Cell($wr[3], 7, "", '', 0, 'R');
                $pdf->Cell($wr[4], 7, "", '', 0, 'R');
                $pdf->Cell($wr[5], 7, "Total", 'LRBT', 0, 'R');
                $pdf->Cell($wr[6], 7, number_format(($totalpayable), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[7], 7, number_format(($totalpaid), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[8], 7, number_format(($openingBalance + ($totalpayable - $totalpaid)), 2, '.', ''), 'LRBT', 0, 'R', "");


                $pdf->Ln();
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 8);
                $pdf->Cell($wr[0], 7, '', '', 0, 'L');
                $pdf->Cell($wr[1], 7, '', '', 0, 'L');
                $pdf->Cell($wr[2], 7, "", '', 0, 'R');
                $pdf->Cell($wr[3], 7, "", '', 0, 'R');
                $pdf->Cell($wr[4], 7, "", '', 0, 'R');
                $pdf->Cell($wr[5], 7, 'Total Opening Balance', 'RBTL', 0, 'R');
                $pdf->Cell($wr[6], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[7], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[8], 7, !empty($openingBalance)?number_format(($openingBalance), 2, '.', ''):0, 'RBT', 0, 'R', "");

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 8);
                $pdf->Cell($wr[0], 7, '', '', 0, 'L');
                $pdf->Cell($wr[1], 7, '', '', 0, 'L');
                $pdf->Cell($wr[2], 7, "", '', 0, 'R');
                $pdf->Cell($wr[3], 7, "", '', 0, 'R');
                $pdf->Cell($wr[4], 7, "", '', 0, 'R');
                $pdf->Cell($wr[5], 7, 'Total Remaining Balance', 'RBTL', 0, 'R');
                $pdf->Cell($wr[6], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[7], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[8], 7, (number_format(($openingBalance + ($totalpayable - $totalpaid)), 2, '.', '')), 'RBT', 0, 'R', "");

                $pdf->Ln();
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 9);
                $pdf->Cell($wr[1], 7, "", 'T', 0, 'C');
                $pdf->Cell($wr[2], 7, "Signature's", 'T', 0, 'C');
                $pdf->Cell($wr[3], 7, "", 'T', 0, 'L');
                $pdf->Cell($wr[4], 7, '', '', 0, 'R', "");
                $pdf->Cell($wr[5], 7, '', '', 0, 'R', "");
            }

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

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