<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Zend\Json\Json;
use Dashboard\Form\{
    CreditLimitForm
};

class CreditLimitController extends RestAPIClientController {

    /**
     * Index
     * @return ViewModel
     */
    public function indexAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $userTypeId = $loginData['user_type_id'];
        $data = [];

        if ($userTypeId != 6565) {
            $data['vendor_id'] = $user_id;
        }

        $creditLimitListing = $this->getCreditLimitList($data);
        $viewModel = new ViewModel(['creditLimitListing' => $creditLimitListing]);
        return $viewModel;
    }

    /**
     * Add
     * @return ViewModel
     */
    public function addAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

        $userList   =   $this->getUserList();
        CreditLimitForm:: $users = $this->getUserList();
        $form = new CreditLimitForm();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'user_id' => $postData['user_name'],
                    'credit_limit_amount' => $postData['credit_limit_amount'],
                    'from_date' => date('Y-m-d', strtotime($postData['from_date'])),
                    'to_date' => date('Y-m-d', strtotime($postData['to_date'])),
                    'status' => $postData['status'],
                    'created_by' => $userId,
                    'created_date' => date('Y-m-d'),
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                //echo '<pre>';print_r($finalData);//die();
                $JsonData   =   $this->addCreditLimit($finalData);
                if ($JsonData['response']['status']=='success') {
                    $msg = "Details Added Successfully!..";
                    $this->redirect()->toRoute('credit-limit', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not Added!..";
                    $color = "red";
                    $this->redirect()->toRoute('credit-limit', ['action' => 'add']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
        }
        $data = [];
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }

    /**
     * Add
     * @return ViewModel
     */
    public function editAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $id = $this->params()->fromQuery('id');

        $userList   =   $this->getUserList();
        CreditLimitForm:: $users = $this->getUserList();
        $form = new CreditLimitForm();
        $request = $this->getRequest();

        if (!empty($id)) {
            $getDetails = $this->getCreditLimitDetails($id);
            $status = $getDetails['status'];
            $form->setData($getDetails);
            $form->get('user_name')->setValue($getDetails['user_id']);
            $form->get('from_date')->setValue(date('Y-m-d',strtotime($getDetails['from_date'])));
            $form->get('to_date')->setValue(date('Y-m-d',strtotime($getDetails['to_date'])));
        }

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'id' => $postData['id'],
                    'user_id' => $postData['user_name'],
                    'credit_limit_amount' => $postData['credit_limit_amount'],
                    'from_date' => date('Y-m-d', strtotime($postData['from_date'])),
                    'to_date' => date('Y-m-d', strtotime($postData['to_date'])),
                    'status' => $postData['status'],
                    'modified_by' => $userId,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                $JsonData   =   $this->updateCreditLimit($finalData);
                if ($JsonData['response']['status']=='success') {
                    $msg = "Details Updated Successfully!..";
                    $this->redirect()->toRoute('credit-limit', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not be Updated!..";
                    $color = "red";
                    $this->redirect()->toRoute('credit-limit', ['action' => 'edit']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
        }
        $data = [];
        $viewModel = new ViewModel(['form' => $form, 'status' => isset($status)?$status:'1']);
        return $viewModel;
    }

    /**
     * Approved
     * @return ViewModel
     */
    public function approveAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $id = $this->params()->fromQuery('id');

        $userList   =   $this->getUserList();
        CreditLimitForm:: $users = $this->getUserList();
        $form = new CreditLimitForm();
        $request = $this->getRequest();

        if (!empty($id)) {
            $getDetails = $this->getCreditLimitDetails($id);
            $status = $getDetails['status'];
            $approved_status = $getDetails['approved_status'];
            $form->setData($getDetails);
            $form->get('user_name')->setValue($getDetails['user_id']);
            $form->get('from_date')->setValue(date('Y-m-d',strtotime($getDetails['from_date'])));
            $form->get('to_date')->setValue(date('Y-m-d',strtotime($getDetails['to_date'])));
        }

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'id' => $postData['id'],
                    'user_id' => $postData['user_name'],
                    'credit_limit_amount' => $postData['credit_limit_amount'],
                    'from_date' => date('Y-m-d', strtotime($postData['from_date'])),
                    'to_date' => date('Y-m-d', strtotime($postData['to_date'])),
                    'status' => $postData['status'],
                    'approved_status' => $postData['approved_status'],
                    'approved_by' => $userId,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                $JsonData   =   $this->approveCreditLimit($finalData);
                if ($JsonData['response']['status']=='success') {
                    $msg = "Details Updated Successfully!..";
                    $this->redirect()->toRoute('credit-limit', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not be Updated!..";
                    $color = "red";
                    $this->redirect()->toRoute('credit-limit', ['action' => 'edit']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
        }
        $data = [];
        $viewModel = new ViewModel(['form' => $form, 'status' => isset($status)?$status:'1', 'approvestatus' => $approved_status]);
        return $viewModel;
    }

    public function deleteAction() {
        $JsonData = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $id = $this->params()->fromQuery('id');
        if (!empty($id)) {
            $JsonData = [
                'id' => $id,
                'modified_by' => $user_id,
                'status' => 2,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];
        }
        $JsonData   =   $this->deleteCreditLimit($JsonData);
        //echo '<pre>';print_r($JsonData);die();
        if ($JsonData['count'] == 1) {
            $msg = "Record Deleted Successfully..!";

            $this->redirect()->toRoute('credit-limit', ['action' => 'index']);
            $this->flashMessenger()->addMessage(array('success' => $msg));
        } else {
            $msg = "Record Could Not Deleted..!";
            $this->redirect()->toRoute('credit-limit', ['action' => 'index']);
            $this->flashMessenger()->addMessage(array('danger' => $msg));
        }
    }

    public function StatusAction() {
        $form = new CreditLimitForm();
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $postData = $this->getRequest()->getPost();
        $id = implode(',', $postData['selected']);
        $status = $postData['status'];
        $data = ['id' => $id, 'user_id' => $user_id, 'status' => $status];
        //echo '<pre>';print_r($data);die();
        $JsonData = $this->multiUpdate($data);
        $creditLimitListing = $this->getCreditLimitList($data);
        $viewModel = new ViewModel(['form' => $form, 'creditLimitListing' => $creditLimitListing]);
        $viewModel->setTemplate('dashboard/credit-limit/listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * Credit Limit List...
     *
     */
    public function getCreditLimitList($data) {
        $val = [];
        $url = $this->apiUrl() . "/credit-limit/getcreditlimit";
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        if ($data['responsedata']['status'] == 'success') {
            $val = $data['responsedata']['data'];
        }
        return $val;
    }


    /**
     *
     * Credit Limit Add...
     *
     */
    public function addCreditLimit($data) {
        $responsedata = [];
        $url = $this->apiUrl() . "/credit-limit/addCreditLimit";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        return $responsedata;
    }


    /**
     *
     * Credit Limit Data fetch...
     *
     */
    public function getCreditLimitDetails($id) {
        $data = [];
        $url = $this->apiUrl() . "/credit-limit/getcreditlimit?id=" . $id;
        $resp = $this->get($url);
        $responseData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($responseData);die();
        if($responseData['responsedata']['status']=="success"){
            $data = $responseData['responsedata']['data'][0];
        }
        return $data;
    }

    /**
     *
     * Credit Limit Add...
     *
     */
    public function updateCreditLimit($data) {
        $responsedata = [];
        $url = $this->apiUrl() . "/credit-limit/updateCreditLimit";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        return $responsedata;
    }

    public function approveCreditLimit($data) {
        $responsedata = [];
        $url = $this->apiUrl() . "/credit-limit/approveCreditLimit";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        return $responsedata;
    }

    public function deleteCreditLimit($data) {
        $val = '{"id": "' . $data['id'] . '"}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/credit-limit/update?where=" . $val;
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        return $JsonData;
    }

    public function multiUpdate($data) {
        $url = $this->apiUrl() . "/credit-limit/updateStatus";
        $resp = $this->put($url, $data);
        $JsonData = Json::decode($resp->getBody(), true);
        return $JsonData;
    }

    public function getUserList() {
        $jsonDataArray =[];
        $company_id = $this->config()->getConfig()->company->companyId;
        $url = $this->apiUrl() . "/user/getUserList?company_id=" . $company_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        $JsonData = $JsonData['responsedata'];
        //echo '<pre>';print_r($JsonData);die();
        if($JsonData['status']=="success"){
        foreach ($JsonData['data'] as $res) {
            $jsonDataArray[$res['user_id']] = $res['username'].'-'.$res['mobile_no'].'-'.$res['RoleName'];
        }
        }
        return $jsonDataArray;
    }

}
