<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Zend\Json\Json;
use Zend\Config\Config;
use Zend\Config\Factory;
use Dashboard\Model\Booking;
use Dashboard\Model\Bid;
use Dashboard\Model\Vehicle;
use Dashboard\Model\User;
use Dashboard\Model\CommonModel;

class IndexController extends RestAPIClientController {

    public function __construct() {
        $this->bookingModel =    new Booking();
        $this->bidModel =    new Bid();
        $this->userModel = new User();
        $this->CommonModel = new CommonModel();
    }

    /**
     * index
     * @return ViewModel
     */
    public function indexAction() {
        $data = [];
        $data1 = [];
        $dataCredit = [];
        $dataWallet = [];
        $dataAssigned = [];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        //echo '<pre>';print_r($sessionUser->userData);die();
        $user_id = $loginData['user_id'];
        $userTypeId = $loginData['user_type_id'];
        $name = $loginData['first_name'];
        $email = $loginData['email'];
        $mobile = $loginData['mobile'];
        $address = isset($loginData['address'])? $loginData['address']:'';
        $referralKey = $loginData['referral_key'];

        if ($userTypeId != 6565) {
            $dataCredit = [];
            $dataWallet = [];
        } else {
            $dataCredit = ['id' => $user_id, 'user_type_id' => $userTypeId];
            $dataWallet = ['id' => $user_id];
        }
        $dataWallet = ['id' => $user_id];
        $dataBooking = ['date'=>date('Y-m-d'),'user_id'=>$user_id,'user_type_id'=>$userTypeId];
        $bookingCount = $this->bookingModel->getBookingCounts($dataBooking);
        $current = $bookingCount[0]['current_booking'];
        $future = $bookingCount[0]['future_booking'];
        $completed = $bookingCount[0]['completed_booking'];
        //$pending = $bookingCount[0]['pending_booking'];
        $canceled = $bookingCount[0]['cancelled_booking'];
        //$total = $current + $future + $completed + $pending + $canceled;
        $total = $current + $future + $completed + $canceled;

        //call API
        $personalDetails = [
            'first_name' => $name,
            'email' => $email,
            'mobile' => $mobile,
            'address' => $address,
            'referal_key' => $referralKey,
            'company_name' => 'null',
            'user_type_id'=>$userTypeId
        ];
        //call API

        $data = ['pickup_date' => date('Y-m-d')];
        $data1 = ['unassigned_booking' => 1,'status' => 1];
        $dataAssigned = ['status' => 3];

        $creditBalance = $this->bookingModel->getCreditBalance($dataCredit);       
        $paymentuploadData = $this->bookingModel->getUserpaymentUploadHistory($user_id,$userTypeId);
        $paymentuploadbalance = $this->bookingModel->getUserUploadCreditBalance($user_id);
        $recentBookings = $this->bookingModel->getRecentBookings($data);
        $unassignedBookings = $this->bookingModel->getRecentBookings($data1);
        $assignedBookings = $this->bookingModel->getRecentBookings($dataAssigned);
        //echo '<pre>';print_r($assignedBookings);die();
        $walletHistory = $this->bookingModel->getWalletPoint($dataWallet);
        $bidparam['driver_id'] = ($userTypeId != 10) ? $user_id : 0;
        $bidListing = $this->bidModel->bidlisting($bidparam);
        //echo '<pre>';print_r($bidListing);die();
        if($bidListing['responsedata']['status']=="success"){
            $bidListing = $bidListing['responsedata']['data'];
        }else{
            $bidListing = "";
        }
        $data['user_type_id'] = '3,4';
        $data['parent_id'] = $user_id;
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        $userListing = $this->userModel->getUserList($data);
        $userListing = $userListing['data']['responsedata'];
        //$userListing = array_slice($userListing['data']['responsedata'], 0, 10);
        $userStatus = $this->userModel->driverStatus();
        $filter_array = ['signup_status' => 10,'is_active' => 4];
        $userListing = array_filter($userListing, function ($val_array) use ($filter_array) {
            $intersection = array_intersect_assoc($val_array, $filter_array);
            return (count($intersection)) === count($filter_array);
        });
        $userListing = array_values($userListing);
        //echo '<pre>';print_r($userListing);die();
        $relationManagerData=[];
        $user_type_id = 11;
        if ($user_id != '') {
            $data = ['user_id' => $user_id, 'user_type_id' => $user_type_id];
            $response = $this->userModel->getUserStaff($data);
            if (!empty($response['responsedata'])) {
                $relationManagerData = $response['responsedata'];
            }
        }
        //echo'<pre>';print_r($userListing);die();

        //echo '<pre>';print_r();die();
        $walletAmount = $this->bookingModel->getWalletAmt($user_id);
        $viewModel = new ViewModel([
            'current' => $current,
            'future' => $future,
            'completed' => $completed,
            //'pending' => $pending,
            'canceled' => $canceled,
            'total' => $total,
            'personalDetails' => $personalDetails,
            'creditBalance' => $creditBalance['responsedata'],
            'recentBookings' => $recentBookings,
            'unassignedBookings' => $unassignedBookings,
            'assignedBookings' => $assignedBookings,
            'walletHistory' => $walletHistory['responsedata'],
            'bidListing' => $bidListing,
            'userListing' => $userListing,
            'userStatus' => $userStatus,
            'relatinaldata'=>$relationManagerData,
            'wallet_amount' => $walletAmount,
            'paymentuploadData' => $paymentuploadData,
            'creditbalance' => $paymentuploadbalance
            
        ]);
        return $viewModel;
    }

    public function setconfigurationAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $comp_id = $loginData['company_id'];
        $compData = $this->getCompanySetupDetails($comp_id);

        $filename = getcwd() . '/config/autoload/customconfig.php';
        $configFile = Factory::fromFile($filename);
        $configFile['site_name'] = $compData['site_name'];
        $configFile['site_title'] = $compData['site_title'];
        $configFile['global_email'] = $compData['global_email'];
        $configFile['admin_footer'] = $compData['admin_footer'];
        $configFile['admin_footer_url'] = $compData['admin_footer_url'];
        $configFile['frontend_footer'] = $compData['frontend_footer'];
        $configFile['frontend_footer_url'] = $compData['frontend_footer_url'];
        $configFile['admin_header_logo'] = $compData['admin_header_logo'];
        $configFile['frontend_header_logo'] = $compData['frontend_header_logo'];
        $configFile['admin_favicon'] = $compData['admin_favicon'];
        $configFile['frontend_favicon'] = $compData['frontend_favicon'];


        if (!Factory::toFile($filename, $configFile)) {
            $result = ['result' => false, 'message' => 'Can\'t put content to ' . $filename . 'due to file permission issue.'];
        } else {
            $result = ['result' => true, 'message' => 'Cofiguration content has been set successfully.'];
        }

        if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
            $viewModel = new JsonModel();
        }

        $viewModel->setVariables(['data' => $result]);

        return $viewModel;
    }

    public function claimBookingAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $user_type_id = $loginData['user_type_id'];
        $userid = 0;
        if($user_type_id!='10'){
          $userid = $user_id;
        }
        $data = $this->getRequest()->getPost();
        $booking_id = $data['booking_id'];
        $vehicleList = $this->bookingModel->getVehicleTypeList();
        $driverList = $this->bookingModel->getActiveDriverList($userid);
        $viewModel = new ViewModel([
            'booking_id' => $booking_id,
            'vehicleList' => $vehicleList,
            'driverList' => $driverList
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

     public function acceptBookingAction() {

        $responsedata = [];
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $userId = $userData['user_id'];

        $booking_id = $this->params()->fromQuery('booking_id');

        if (!empty($booking_id)) {
            $data = [
                'user_id' => $userId,
                'booking_id' => $booking_id
            ];
            $url = $this->apiUrl() . "/driver/driveracceptjob";
            $val = $this->post($url, $data);
            $JsonData = $val->getBody();
            $responsedata = Json::decode($JsonData, true);
            $responsedata = $responsedata['responsedata'];
        }


            if ($responsedata['status']=='true') {
                $msg = "Booking Acceptd ..!";

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


         public function downloadFileDataAction(){
         $request = $this->getRequest();

            $userId = $this->params()->fromQuery('userid');
            $doclevelname = $this->params()->fromQuery('filename');

            $b2bUrlbasePath = $this->config()->getConfig()->base_url->file_path;
            $b2bUrlFilePath = $this->config()->getConfig()->base_url->b2burl;

            $userUploadedDoc = $this->userModel->getUserDocument($userId,$doclevelname);

            if($userUploadedDoc['responsedata']['status']=='success'){
               $existfilename   = $userUploadedDoc['responsedata']['data'][0]['doc_file_upload'];
               if($existfilename!=''){

                     $downloadfilebasename = $b2bUrlbasePath."".$userId."/".$existfilename;
                     $downloadfilename = $b2bUrlFilePath."/".$userId."/".$existfilename;
                     $filename = basename($existfilename);

                    if (file_exists($downloadfilebasename)){
                            header('Content-Type: application/force-download');
                            header("Content-Transfer-Encoding: Binary");
                            header('Content-Disposition: inline; filename='.$existfilename);
                            header('Expires: 0');
                            header('Cache-Control: must-revalidate');
                            header('Pragma: public');
                            header('Content-Length: ' . filesize($downloadfilebasename));
                            ob_clean();
                            flush();
                            readfile($downloadfilename);
                            die();
                        } else {
                            http_response_code(404);
                            die();
                        }
               }else{
                   echo "Not file exist";die;
               }


        }

        $viewModel = new JsonModel();
        $viewModel->setVariables([]);

        return $viewModel;
    }
    
    /** Function to change VEHICLE TYPE STATUS */
    public function removeRecentlyViewedAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        //print_r($data); die;
        $val = ['user_id' => $user_id, 'id' => $data['id'] , 'ip' => $_SERVER['REMOTE_ADDR']];
        $this->CommonModel->deleteRecentViewedItems($val);
        $viewModel = new ViewModel();
        $viewModel->setTemplate('dashboard/index/recent-viewed.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }



}
