<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    CreditRequestForm,
    CreditRequestSearchForm
};

use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Zend\Session\Container;
use Zend\Debug\Debug;

class CreditController extends RestAPIClientController {

    /**
     * Payment Approved
     * @return ViewModel
     */
    public function indexAction() {
        $form=  new CreditRequestSearchForm();
        $data = [];
        $creditListing = $this->getCreditList($data);
        //echo '<pre>';print_r($creditListing['data']['responsedata']);die();
        $viewModel = new ViewModel(['form'=>$form,'creditListing' => $creditListing['data']['responsedata']]);
        return $viewModel;
    }


    /**
     * search
     * @return ViewModel
     */
    public function searchrecordAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $data = [
            'payment_ref_no' => $postData['payment_ref_no'],
            'driver_name' => $postData['user_name'],
            'amount' => $postData['deposit_amount'],
            'payment_mode' => $postData['payment_mode'],
        ];
        $data = array_filter($data);
        $data['status']=$postData['status'];
        $creditListing = $this->getCreditList($data);
        $viewModel = new ViewModel(['creditListing' => $creditListing['data']['responsedata']]);
        $viewModel->setTemplate('/dashboard/credit/credit-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }


    /**
     * Get BILLING LIST
     * @return JSON
     */
    public function getCreditList($data) {
        // CALL API HERE /////////
        $url = $this->apiUrl() . "/driver-payment/getDriverPayment";
        $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;
    }


    /**
     *
     * @return ViewModel
     */
    public function approveRequestAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id =   $data['id'];
        $url = $this->apiUrl() . "/driver-payment/".$id;
        $resp = $this->get($url);
        $creditData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($creditData);//die();
        $form = new CreditRequestForm();
        $form->setData($creditData);

        $form->get('payment_ref_no')->setValue($creditData['payment_ref_no'])->setAttribute('disabled', true);
        $form->get('deposit_date')->setValue(date('Y-m-d',strtotime($creditData['deposit_date'])))->setAttribute('disabled', true);
        $form->get('payment_mode')->setValue($creditData['transaction_mode'])->setAttribute('disabled', true);
        $form->get('deposit_amount')->setValue($creditData['amount']);

        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }


     /**
     *
     * @return ViewModel
     */
    public function auditRequestAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id =   $data['id'];
        $url = $this->apiUrl() . "/driver-payment/".$id;
        $resp = $this->get($url);
        $creditData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($creditData);//die();
        $form = new CreditRequestForm();
        $form->setData($creditData);

        $form->get('payment_ref_no')->setValue($creditData['payment_ref_no'])->setAttribute('disabled', true);
        $form->get('deposit_date')->setValue(date('Y-m-d',strtotime($creditData['deposit_date'])))->setAttribute('disabled', true);
        $form->get('payment_mode')->setValue($creditData['transaction_mode'])->setAttribute('disabled', true);
        $form->get('deposit_amount')->setValue($creditData['amount']);

        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }



        /**
     *
     * @return ViewModel
     */
    public function approvedRequestAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $form = new CreditRequestForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            //echo '<pre>';print_r($post);die();
            $form->setData($request->getPost());
            $form->getInputFilter()->get('payment_ref_no')->setRequired(false);
            $form->getInputFilter()->get('deposit_date')->setRequired(false);
            $form->getInputFilter()->get('payment_mode')->setRequired(false);
            $form->getInputFilter()->get('credit_date')->setRequired(false);
            $form->getInputFilter()->get('credit_amount')->setRequired(false);
            $form->getInputFilter()->get('admin_remarks')->setRequired(false);
            if ($form->isValid()) {
                $data = [];
                $data = [
                    'partner_bank' => $post['partner_bank'],
                    'amount' => $post['deposit_amount'],
                    'deposit_bank' => $post['deposit_bank'],
                    'deposit_branch' => $post['deposit_branch'],
                    'remark' => $post['remark'],
                    'status' => 1,
                    'id' => $post['id'],
                ];
                $finaldata = array_filter($data);
                $status = $this->approvedCreditRequestDetails($finaldata);
                if ($status['responsedata']['affectedRows'] > 0) {
                    $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;
        }
    }


            /**
     *
     * @return ViewModel
     */
    public function auditedRequestAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $form = new CreditRequestForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            $form->getInputFilter()->get('payment_ref_no')->setRequired(false);
            $form->getInputFilter()->get('deposit_date')->setRequired(false);
            $form->getInputFilter()->get('payment_mode')->setRequired(false);
            if ($form->isValid()) {
                $data = [];
                $data = [
                    'partner_bank' => $post['partner_bank'],
                    'amount' => $post['deposit_amount'],
                    'deposit_bank' => $post['deposit_bank'],
                    'deposit_branch' => $post['deposit_branch'],
                    'remark' => $post['remark'],
                    'credit_date' => $post['credit_date'],
                    'credit_amount' => $post['credit_amount'],
                    'admin_remarks' => $post['admin_remarks'],
                    'audit_date' => date('Y-m-d H:i:s'),
                    'status' => 2,
                    'id' => $post['id'],
                ];
                $finaldata = array_filter($data);
                $status = $this->approvedCreditRequestDetails($finaldata);
                if ($status['responsedata']['affectedRows'] > 0) {

                    $walletAmt =   $this->getWalletAmt($post['driver_id']);
                    $dataWallet['user_id'] = $post['driver_id'];
                    $dataWallet['wallet_amount'] = $walletAmt + $post['credit_amount'];
                    $resp = $this->getWalletAmtUpdate($dataWallet);
                    $dataTransac=[];
                    $dataTransac=[
                        'user_id'=>$post['driver_id'],
                        'time'=>date('Y-m-d H:i:s'),
                        'amount'=>$post['credit_amount'],
                        'currentbalance'=>$dataWallet['wallet_amount'],
                        'status'=>'Credit',
                        'reason'=>$post['admin_remarks'],
                        'created_by'=>$user_id
                        ];
                    $this->insertDriverTransactionDetails($dataTransac);
                    
                    $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 approvedCreditRequestDetails($data) {
        $url = $this->apiUrl() . "/driver-payment/updateDriverPayment";
        $resp = $this->put($url, $data);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }


    public function getWalletAmt($user_id) {
        $url = $this->apiUrl() . "/user/walletamount?user_id=" . $user_id;
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        $walletAmt = $response['responsedata']['wallet_amount'];
        if ($walletAmt != "") {
            $data = $response['responsedata']['wallet_amount'];
        } else {
            $data = 0;
        }
        return $data;
    }

    public function getWalletAmtUpdate($data) {
        $url = $this->apiUrl() . "/user/updateWalletAmount";
        $resp = $this->put($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        return $response;
    }


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


}
