<?php

namespace Dashboard\Controller;

use Zend\Mvc\Controller\AbstractActionController;
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\Session\Container;

class BidController extends AbstractActionController {

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

    public function indexAction() {
        //write code here...
        $bidListing = '';
        $bookingstatus = [
            '1' => 'Select',
            '2' => 'Confirmed Bookings',
            '3' => 'Pending Bookings',
            '4' => 'Canceled Bookings',
            '5' => 'Expired Bookings'
        ];

        BidSearchForm:: $bookingstatus = $bookingstatus;

        //Call API...
        $form = new BidSearchForm();

        $bidListing = $this->bid->bidlisting();
        //echo'<pre>';print_r($bidListing);die();

        $viewModel = new ViewModel(['form' => $form, 'bidListing' => $bidListing['responsedata']['data']]);
        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' => 101,
                    // 'state_id'=>109,
                    'city_id' => $postData['source_value'],
                    'master_package_id' => 1, //By default for Oneway route package
                    'master_package_mode_id' => 1, //By default on Distance Fare Mode
                    'from_date' => date('Y-m-d', strtotime($postData['journey_start_date'])), //"2019-05-23",
                    'to_date' => date('Y-m-d', 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"
                        //'moduleids'=>implode(',',$postData['modulenameid']),
                        //'created_by'=>$userId,
                        // 'status'=>$postData['status'],
                        // 'created_date'=>date('Y-m-d')
                ];
                $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() {

        $bidListing = [
            '0' => [
                'source' => 'Delhi',
                'destination' => 'Jaipur',
                'cab_no' => '5375',
                'fare' => '2514',
                'extra_charge' => '500',
                'distance' => '1000',
                'extra_km' => '5',
                'journey_date' => '20 Apr 2018',
                'availability' => '20 Apr 2018 - 30 Apr 2018',
                'cab_type' => 'Sedan',
                'release_time' => '09:5$bidListing0'
            ],
            '1' => [
                'source' => 'Delhi',
                'destination' => 'Jaipur',
                'cab_no' => '5375',
                'fare' => '2514',
                'extra_charge' => '500',
                'distance' => '1000',
                'extra_km' => '5',
                'journey_date' => '20 Apr 2018',
                'availability' => '20 Apr 2018 - 30 Apr 2018',
                'cab_type' => 'Sedan',
                'release_time' => '09:50'
            ],
            '2' => [
                'source' => 'Delhi',
                'destination' => 'Jaipur',
                'cab_no' => '5375',
                'fare' => '2514',
                'extra_charge' => '500',
                'distance' => '1000',
                'extra_km' => '5',
                'journey_date' => '20 Apr 2018',
                'availability' => '20 Apr 2018 - 30 Apr 2018',
                'cab_type' => 'Sedan',
                'release_time' => '09:50'
            ],
            '3' => [
                'source' => 'Delhi',
                'destination' => 'Jaipur',
                'cab_no' => '5375',
                'fare' => '2514',
                'extra_charge' => '500',
                'distance' => '1000',
                'extra_km' => '5',
                'journey_date' => '20 Apr 2018',
                'availability' => '20 Apr 2018 - 30 Apr 2018',
                'cab_type' => 'Sedan',
                'release_time' => '09:50'
            ],
            '4' => [
                'source' => 'Delhi',
                'destination' => 'Jaipur',
                'cab_no' => '5375',
                'fare' => '2514',
                'extra_charge' => '500',
                'distance' => '1000',
                'extra_km' => '5',
                'journey_date' => '20 Apr 2018',
                'availability' => '20 Apr 2018 - 30 Apr 2018',
                'cab_type' => 'Sedan',
                'release_time' => '09:50'
            ]
        ];

        $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();
//        $postdata=[
//            'source_name'=>'Kanpur',
//             'destination_name'=>'Delhi',
//             'source_id'=>4861,
//             'destination_id'=>706
//        ];
        $cityJsonData = $this->bid->kiloMeter($postdata);
        $cityJsonData['id']='';
        $cityJsonData['distance_km']='';
        if (isset($cityJsonData[0]['distance_km'])) {

            $data['distance_id'] = $cityJsonData[0]['id'];
            $data['city_distance'] = $cityJsonData[0]['distance_km'];
        } else {
            $data['distance_id'] = $cityJsonData['id'];
            $data['city_distance'] = $cityJsonData['distance_km'];
        }

        $view = new JsonModel($data);
        return $view;
    }

    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));
            }
        }
    }

}
