<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Dashboard\Form\{
    BidAddForm,
    BidSearchForm
};
use Dashboard\Model\Bid;
use Dashboard\Model\Vehicle;
use Dashboard\Model\User;
use Zend\Json\Json;
use Zend\Session\Container;
use Zend\Debug\Debug;

class BidController extends RestAPIClientController {

    /**
     * Index
     * @return ViewModel
     */
    public function __construct() {
        $this->bid = new Bid();
        $this->vehicleModel = new Vehicle();
        $this->userModel = new User();
    }

    private $oneWayPackageType = 5;

    public function indexAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $user_type_id = $loginData['user_type_id'];
        $data = [];
        BidSearchForm:: $vehicletype = $this->vehicleModel->getVehicleTypeList();
        //Call API...
        $form = new BidSearchForm();
        if($user_type_id!=10){
            $data['driver_id']=$user_id;
        }
        $bidListing = $this->bid->bidlisting($data);
        if ($bidListing['responsedata']['status'] == "success") {
            $bidListing = $bidListing['responsedata']['data'];
        } else {
            $bidListing = "";
        }

        $viewModel = new ViewModel(['form' => $form, 'bidListing' => $bidListing]);
        return $viewModel;
    }

    /**
     * Add New Basic
     * @return ViewModel
     */
    public function addNewBasicAction() {
        $companyId = $this->config()->getConfig()->company->companyId;
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];

        BidAddForm::$vehicletype = $this->vehicleModel->getVehicleTypeList();
        $form = new BidAddForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $postData = $request->getPost()->toArray();

                $finalData = [];
                $finalData = [
                    'company_id' => $companyId,
                    'vendor_id' => $user_id,
                    'country_id' => '',
                    // 'state_id'=>109,
                    'city_id' => $postData['source_value'],
                    'master_package_id' => $this->oneWayPackageType, //By default for Oneway route package
                    'master_package_mode_id' => 1, //By default on Distance Fare Mode
                    'from_date' => date('Y-m-d h:i:s', strtotime($postData['journey_start_date'])), //"2019-05-23",
                    'to_date' => date('Y-m-d h:i:s', strtotime($postData['journey_end_date'])),
                    //'currency'=>1,
                    //'week_days'=>1,
                    'created_date' => date('Y-m-d h:i:s'),
                    'created_by' => $user_id,
                    'vehicle_type_id' => $postData['vehicle_type'],
                    'city_distance_id' => $postData['distance_city_id'],
                    'via_city' => 2,
                    'start_time' => $postData['journey_start_time'], //"12:35:00",
                    'end_time' => $postData['journey_end_time'], //"20:20:59",
                    'minimum_charge' => $postData['fare'], //"210",
                    'minimum_distance' => $postData['fixed_km'],
                    'per_km_charge' => $postData['extra_km'], //"10"
                    'toll' => $postData['toll'],
                    'parking' => $postData['parking'],
                    'driver_allowance' => $postData['da'], //"10"
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                //echo'<pre>';print_r($finalData);die();
                $JsonData = $this->bid->insertBidInfo($finalData);
                if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $msg = "Bid Details Added Successfully..";

                    $this->redirect()->toRoute('bid', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                    //echo'<pre>';print_r($finalData);die();
                } else {
                    $msg = "Bid Details Could Not Added Successfully..";
                    $this->redirect()->toRoute('bid', ['bid' => 'add-new-basic']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
            // else{
            //  $m= $form->getMessages();
            //}
        }

        //
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }

    /**
     * Add New Basic
     * @return ViewModel
     */
    public function editBasicAction() {

        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        BidAddForm::$vehicletype = $this->vehicleModel->getVehicleTypeList();
        $form = new BidAddForm();
        $route_id = $this->params()->fromQuery('id');
        $city_distance_id = $this->params()->fromQuery('city_id');
        $data = [
            'route_id' => $route_id
        ];
        $getData = $this->bid->getBidInfo($data);
        //echo '<pre>';print_r($getData);die();
        if ($getData['responsedata']['status'] = 'success') {
            $getResponse = $getData['responsedata']['data'][0];
        }
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $postData = $request->getPost()->toArray();

                $finalData = [];
                $finalData = [
                    'route_id' => $postData['route_id'],
                    'city_id' => $postData['source_value'],
                    'from_date' => $this->userModel->changeDateFormat($postData['journey_start_date']),
                    'to_date' => $this->userModel->changeDateFormat($postData['journey_end_date']),
                    'modified_by' => $user_id,
                    'vehicle_type_id' => $postData['vehicle_type'],
                    'city_distance_id' => $postData['distance_city_id'],
                    'via_city' => 2,
                    'start_time' => $postData['journey_start_time'],
                    'end_time' => $postData['journey_end_time'],
                    'minimum_charge' => $postData['fare'],
                    'minimum_distance' => $postData['fixed_km'],
                    'per_km_charge' => $postData['extra_km'],
                    'toll' => $postData['toll'],
                    'parking' => $postData['parking'],
                    'driver_allowance' => $postData['da'],
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                //echo '<pre>';print_r($finalData);die();
                $JsonData = $this->bid->updateBidInfo($finalData);
                //echo '<pre>';print_r($JsonData);die();
                if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $msg = "Bid Details Updated Successfully..";

                    $this->redirect()->toRoute('bid', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Bid Details Could Not Updated Successfully..";
                    $this->redirect()->toRoute('bid', ['bid' => 'edit-basic']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
            // else{
            //  $m= $form->getMessages();
            //}
        }

        //
        $viewModel = new ViewModel(['form' => $form, 'getResponse' => $getResponse]);
        return $viewModel;
    }

    /**
     * Bid Company Price Heading
     * @return ViewModel
     */
    public function bidCompanyPriceHeadingAction() {
        //write code here...

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

    /**
     * Bid View Update Records
     * @return ViewModel
     */
    public function bidViewUpdateRecordsAction() {
        //write code here...

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

    /**
     * Middle Links
     * @return ViewModel
     */
    public function middlelinksAction() {
        //write code here...

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

    /**
     * Update Record Configure
     * @return ViewModel
     */
    public function updateRecordConfigureAction() {
        //write code here...

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

    public function searchBidAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $user_type_id = $loginData['user_type_id'];

        $val = $this->getRequest()->getPost();
        $bidListing = [];
        $data = [
            'source_city' => $val['source_value'],
            'destination_city' => $val['destination_value'],
            'multi_booking_type' => isset($val['booking_type']) ? implode(',', $val['booking_type']) : '',
            'multi_vehicle_type' => isset($val['vehicle_type']) ? implode(',', $val['vehicle_type']) : '',
            'from_date' => $val['from_date'],
            'to_date' => $val['to_date'],
        ];
        $data = array_filter($data);
        if($user_type_id!=10){
            $data['driver_id']=$user_id;
        }
        $result = $this->bid->getBidInfo($data);
        //echo '<pre>';print_r($result);die();
        if ($result['responsedata']['status'] == 'success') {
            $bidListing = $result['responsedata']['data'];
        }

        $viewModel = new ViewModel(['bidListing' => $bidListing]);
        $viewModel->setTemplate('/dashboard/bid/bid-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function allCityListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $cityJsonData = $this->bid->citylist($postdata);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function getKiloMeterAction() {
        $data = [];
        $request = $this->getRequest();
        $postdata = $request->getPost()->toArray();
        $cityJsonData = $this->bid->kiloMeter($postdata);
        //echo '<pre>';print_r($cityJsonData);die();
        if (!empty($cityJsonData)) {
            $data['distance_id'] = $cityJsonData['id'];
            $data['city_distance'] = $cityJsonData['distance_km'];
        } else {
            $data['distance_id'] = '';
            $data['city_distance'] = '';
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function bidStatusAction($data = null) {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $bid_status = $data['status'];
        $data = ['driver_id' => $user_id, 'bid_id' => $id, 'status' => $bid_status];
        $bidStatus = $this->bid->bidStatusUpdation($data);

        $bidListing = $this->bid->bidlisting();
        $viewModel = new ViewModel(['bidListing' => $bidListing['responsedata']['data']]);
        $viewModel->setTemplate('/dashboard/bid/bid-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function deleteBidAction() {
        $route_id = $this->params()->fromQuery('data');
        if (!empty($route_id)) {
            $data = ['driver_id' => $user_id, 'bid_id' => $route_id, 'status' => 2];
            $bidStatus = $this->bid->bidStatusUpdation($data);

            if (!empty($bidStatus)) {
                $msg = "Bid Deleted Successfully..";
                $this->redirect()->toRoute('bid', ['action' => 'index']);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {
                $msg = "Could Not Deleted..";
                $this->redirect()->toRoute('bid', ['action' => 'index']);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            }
        }
    }

}
