<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    BillingManagementSearchForm,
    VoucherForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Zend\Session\Container;
use Zend\Debug\Debug;

class BillingManagementController extends RestAPIClientController {

    private $paid = 1;
    private $unPaid = 2;
    private $collection = 3;
    private $overDue = 4;
    private $partial = 5;
    private $void = 6;
    /**
     * Billing Management Home
     * @return ViewModel
     */
    public function indexAction() {
        BillingManagementSearchForm::$usertype = $this->getUserTypeList();
        BillingManagementSearchForm::$payment_status = $this->getBillingPaymentStatusList();
        $data = ['invoice_no_exist' => 'false'];
        $billListing = $this->getBillingList($data);
        $form = new BillingManagementSearchForm();
        $viewModel = new ViewModel(['form' => $form, 'billListing' => $billListing['data']['responsedata']]);
        return $viewModel;
    }

    /**
     * Bill Invoice
     * @return ViewModel
     */
    public function billInvoiceAction() {
        BillingManagementSearchForm::$usertype = $this->getUserTypeList();
        BillingManagementSearchForm::$payment_status = $this->getBillingPaymentStatusList();
        $data = [];
        $billListing = $this->getBillingList($data);
        $form = new BillingManagementSearchForm();
        $viewModel = new ViewModel(['form' => $form, 'billListing' => $billListing['data']['responsedata']]);
        return $viewModel;
    }

    /**
     * Left Options
     * @return ViewModel
     */
    public function leftOptionsAction() {
        //write code here...

        $viewModel = new ViewModel();
        return $viewModel;
    }

    /**
     * Manage Account
     * @return ViewModel
     */
    public function manageAccountAction() {
        //write code here...

        $viewModel = new ViewModel();
        return $viewModel;
    }

    /**
     * Right Options
     * @return ViewModel
     */
    public function rightOptionsAction() {
        //write code here...

        $viewModel = new ViewModel();
        return $viewModel;
    }

    /**
     * search
     * @return ViewModel
     */
    public function searchbillingrecordAction() {
        //write code here...
        //Call API...
        $data = [];
        $postData = $this->getRequest()->getPost();
        $data = [
            'booking_id' => $postData['booking_id'],
            'payment_status' => $postData['payment_status'],
            'from_date' => $postData['from_date'],
            'to_date' => $postData['to_date'],
            'user_type_id' => $postData['user_type'],
            'user_id' => $postData['user_name'],
            'invoice_no_exist' => 'false'
        ];
        $data = array_filter($data);
        $billListing = $this->getBillingList($data);
        $viewModel = new ViewModel(['billListing' => $billListing['data']['responsedata']]);
        $viewModel->setTemplate('/dashboard/billing-management/billing-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * search
     * @return ViewModel
     */
    public function searchbillinginvoicerecordAction() {
        //write code here...
        //Call API...
        $data = [];
        $postData = $this->getRequest()->getPost();
        $data = [
            'booking_id' => $postData['booking_id'],
            'payment_status' => $postData['payment_status'],
            'from_date' => $postData['from_date'],
            'to_date' => $postData['to_date'],
            'user_type_id' => $postData['user_type'],
            'user_id' => $postData['user_name'],
            'invoice_no' => $postData['invoice_no'],
            'invoice_no_exist' => 'true'
        ];
        $data = array_filter($data);
        $billListing = $this->getBillingList($data);
        $viewModel = new ViewModel(['billListing' => $billListing['data']['responsedata']]);
        $viewModel->setTemplate('/dashboard/billing-management/billing-invoice-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function addVoucherAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $data = $this->getRequest()->getPost();
        VoucherForm::$vouchertype = $this->getVoucherTypeList();
        $form = new VoucherForm();
        if ($data['type'] == 'multiple') {
            $id = implode(',', $data['selected']);
        } else {
            $id = $data['selected'];
        }
        $data = ['billing_id' => $id, 'invoice_no_exist' => 'true'];
        $billListing = $this->getBillingList($data);
        $voucherNo = $this->getVoucherNo();
        $year = $this->getCurrentYear();
        $voucher_no = $this->config()->getConfig()->invoice->voucherPrefix . substr($year, 2) . '/' . $voucherNo;
        $viewModel = new ViewModel(['form' => $form, 'billListing' => $billListing['data']['responsedata'], 'voucher_no' => $voucher_no]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function createVoucherAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $form = new VoucherForm();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $created_date = date('Y-m-d H:i:s');
                $ip = $_SERVER['REMOTE_ADDR'];
                $voucherNo = $this->getVoucherNo();
                $year = $this->getCurrentYear();
                $voucher_no = $this->config()->getConfig()->invoice->voucherPrefix . substr($year, 2) . '/' . $voucherNo;

                $data1 = ['billing_id' => implode(',', $post['booking_id']), 'invoice_no_exist' => 'true'];
                $billListing = $this->getBillingList($data1);

                $billDataArr = [];
                foreach ($billListing['data']['responsedata'] as $val) {
                    $billDataArr[$val['id']]['amount'] = $val['booking_amt_balance'];
                    $billDataArr[$val['id']]['paid_status'] = $val['is_paid'];
                }

                $addvoucherdetail = array_combine($post['booking_id'], $post['amount']);
                foreach ($addvoucherdetail as $key => $val) {
                    $balance_amount = $billDataArr[$key]['amount'];
                    $voucher_amount = $val;
                    if ($voucher_amount > 0) {
                        if ($balance_amount > $voucher_amount) {
                            $balanceAmt = $balance_amount - $voucher_amount;
                            $payStatus = $this->partial;
                        } else if ($balance_amount <= $voucher_amount) {
                            $balanceAmt = $voucher_amount - $balance_amount;
                            $payStatus = $this->paid;
                        } else {
                            $balanceAmt = $balance_amount;
                            $payStatus = $this->unPaid;
                        }
                    }
                    $dataArray[] = ['id' => $key, 'status' => $payStatus, 'balance_amt' => $balanceAmt];
                }

                $data = [];
                $data = [
                    'voucher_type' => $post['voucher_type'],
                    'voucher_no' => $post['voucher_no'],
                    'voucher_date' => $post['voucher_date'],
                    'voucher_no_auto' => $voucher_no,
                    'booking_id' => implode(',', $post['booking_id']),
                    'invoice_id' => $post['booking_invoice_id'],
                    'payment_type' => implode(',', $post['payment_type']),
                    'amount' => implode(',', $post['amount']),
                    'created_date' => $created_date,
                    'updated_data' => $dataArray,
                    'created_by' => $user_id,
                    'ip' => $ip
                ];

                $finaldata = array_filter($data);
                //echo '<pre>';print_r($finaldata);die();
                $status = $this->insertVoucherDetails($finaldata);

                if ($status['responsedata']['affectedRows'] > 0) {
                    //$this->redirect()->toRoute('billingmanagement', ['action' => 'bill-invoice']);
                    $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                }
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function getBookingPaymentStatus($id, $amount) {
        $data1 = ['billing_id' => $id, 'invoice_no_exist' => 'true'];
        $billListing = $this->getBillingList($data1);
        foreach ($billListing['data']['responsedata'] as $val) {
            $balance_amt = $val['booking_amt_balance'];
        }
    }

    /**
     *
     * @return ViewModel
     */
    public function voucherViewAction() {
        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function createInvoiceAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($company_id);
        $data = $this->getRequest()->getPost();
        if ($data['type'] == 'multiple') {
            $id = implode(',', $data['selected']);
        } else {
            $id = $data['selected'];
        }
        $data = ['billing_id' => $id, 'invoice_no_exist' => 'false'];
        $billListing = $this->getBillingList($data);
        //echo '<pre>';print_r($billListing['data']['responsedata']);die();
        $invoiceNo = $this->getInvoiceNo($user_id);
        $year = $this->getCurrentYear();
        $invoice_no = $this->config()->getConfig()->invoice->invoicePrefix . substr($year, 2) . '/' . $invoiceNo;
        $viewModel = new ViewModel(['compData' => $compJsonData, 'billListing' => $billListing['data']['responsedata'], 'invoice_no' => $invoice_no]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function invoiceAction() {
        $viewModel = new ViewModel();
        $viewModel->setTemplate('/dashboard/billing-management/bill-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /** Function to change User STATUS */
    public function billTypeStatusAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $bill_status = $data['status'];
        $data = ['payment_status' => $bill_status];
        $billListing = $this->getBillingList($data);
        $viewModel = new ViewModel(['billListing' => $billListing['data']['responsedata']]);
        $viewModel->setTemplate('/dashboard/billing-management/billing-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * Get BILLING LIST
     * @return JSON
     */
    public function getBillingList($data) {
        // CALL API HERE /////////
        $url = $this->apiUrl() . "/booking/billing";
        $resp = $this->post($url, $data);
        $billingList = Json::decode($resp->getBody(), true);
        if ($billingList != "") {
            $val = ["status" => true, "data" => Json::decode($resp->getBody(), true)];
        } else {
            $val = ["status" => false, "data" => Json::decode($resp->getBody(), true)];
        }
        return $val;
    }

    /** Function to Get VEHICLE AMENITIES */
    public function getBillingPaymentStatusList() {
        $paymentStatusJsonDataArray = [];
        $val = '{"where": {"type": "BILLING"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/cab-status?&filter=" . $val;
        $resp = $this->get($url);
        $paymentStatusJsonData = Json::decode($resp->getBody(), true);
        foreach ($paymentStatusJsonData as $res) {
            $paymentStatusJsonDataArray[$res['status_id']] = $res['status'];
        }
        return $paymentStatusJsonDataArray;
    }

    /**
     * Get User Type List
     * @return JSON
     */
    public function getUserTypeList() {
        $roleJsonDataArray = [];
        $val = '{"where":{"and": [{"role_type": 1},{"status": 1}]}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/user-role?&filter=" . $val;
        $resp = $this->get($url);
        $roleJsonData = Json::decode($resp->getBody(), true);
        foreach ($roleJsonData as $res) {
            $roleJsonDataArray[$res['Role_ID']] = $res['RoleName'];
        }
        return $roleJsonDataArray;
    }

    /**
     * Get Customer List
     * @return JSON
     */
    public function getAjaxUserListAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = [];
        $postData = $this->getRequest()->getPost();
        $company_id = $this->config()->getConfig()->company->companyId;
        $user_type = $postData['user_type'];
        $data = [
            'company_id' => $company_id,
            'user_type' => $user_type,
            'user_id' => $user_id,
                //'user_type_id' => $userTypeId
        ];
        $data = array_filter($data);
        //echo '<pre>';print_r($data);die();
        $url = $this->apiUrl() . "/user/getUserDetailbyParentid";
        $resp = $this->post($url, $data);
        $userJsonData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($userJsonData['responsedata']);die();
        if (!empty($userJsonData['responsedata'])) {
            foreach ($userJsonData['responsedata'] as $value) {
                $customerName = $value['child_name'] . ' (' . $value['child_mobile'] . ')';
                $data1[] = ["customer_id" => $value['child_user_id'], "customer_name" => $customerName];
            }
            $response = ["status" => true, "data" => $data1];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }

    /**
     * Get User Type List
     * @return JSON
     */
    public function getInvoiceNo($user_id) {
        $year = $this->getCurrentYear();
        $url = $this->apiUrl() . "/booking/userGenerateInvoice?&user_id=" . $user_id . "&year=" . $year;
        $resp = $this->get($url);
        $invoiceData = Json::decode($resp->getBody(), true);
        if ($invoiceData['responsedata'][0]['invoice_number'] != "") {
            $invoiceNo = $invoiceData['responsedata'][0]['invoice_number'];
        } else {
            $invoiceNo = $this->config()->getConfig()->invoice->invoiceStart;
        }
        return $invoiceNo;
    }

    /**
     * Get User Type List
     * @return JSON
     */
    public function getCurrentYear() {
        $year = date('Y');
        $month = date('m');
        if ($month <= 03) {
            $year = $year - 1;
        }
        return $year;
    }

    /**
     * Get Customer List
     * @return JSON
     */
    public function addInvoiceAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        /* $countArr   =   $postData['selected'];
          //echo '<pre>';print_r($postData['selected']);die();
          $billArray=[];
          foreach($countArr as $val){
          //  $a=[1,2,'2019-01-17',16];
          } */
        $bookingChargeIds = implode(',', $postData['selected']);
        $invoiceJsonData = $this->addBookingInvoice($bookingChargeIds);
        if ($invoiceJsonData['responsedata']['affectedRows'] > 0) {
            $insertId = $invoiceJsonData['responsedata']['insertId'];
            $response = ["status" => true];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }

    /**
     * Add Booking Invoice
     * @return JSON
     */
    public function addBookingInvoice($bookingChargeIds) {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = [];
        $year = $this->getCurrentYear();
        $invoice_no = $this->getInvoiceNo($user_id);
        $invoiceNo = $this->config()->getConfig()->invoice->invoicePrefix . substr($year, 2) . '/' . $invoice_no;
        $data = [
            'year' => $year,
            'user_id' => $user_id,
            'invoice_no' => $invoice_no,
            'prefix' => $this->config()->getConfig()->invoice->invoicePrefix,
            'created_by' => $user_id,
            'created_date' => date('Y-m-d H:i:s'),
            'invoicebills' => $bookingChargeIds,
            'invoice_number_format' => $invoiceNo,
        ];
        //echo '<pre>';print_r($data);die();
        $url = $this->apiUrl() . "/booking/AddBookingInvoice";
        $resp = $this->post($url, $data);
        $invoiceData = Json::decode($resp->getBody(), true);
        return $invoiceData;
    }

    /**
     * Get Voucher No
     * @return JSON
     */
    public function getVoucherNo() {
        $url = $this->apiUrl() . "/booking/getVoucherNo";
        $resp = $this->get($url);
        $voucherData = Json::decode($resp->getBody(), true);
        if ($voucherData['responsedata'][0]['voucher_no'] != "") {
            $voucherNo = $voucherData['responsedata'][0]['voucher_no'];
        } else {
            $voucherNo = $this->config()->getConfig()->invoice->voucherStart;
        }
        return $voucherNo;
    }

    /**
     * Get Voucher Type List
     * @return JSON
     */
    public function getVoucherTypeList() {
        $voucherTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/voucher-type";
        $resp = $this->get($url);
        $voucherTypeJsonData = Json::decode($resp->getBody(), true);
        foreach ($voucherTypeJsonData as $res) {
            $voucherTypeJsonDataArray[$res['id']] = $res['name'] . '( ' . $res['code'] . ')';
        }
        return $voucherTypeJsonDataArray;
    }

    public function insertVoucherDetails($data) {
        $url = $this->apiUrl() . "/booking/addInvoiceVoucher";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

}
