<?php

namespace Dashboard\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Application\Controller\RestAPIClientController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Zend\Json\Json;
use Zend\Session\Container;
use Dashboard\Form\{
    VehicleTypeForm
};
use Zend\Debug\Debug;
use Dashboard\Model\Vehicle;

class VehicleTypeController extends RestAPIClientController {

    public function __construct() {
        $this->vehicleModel = new Vehicle();
    }

    /**
     * Index
     * @return ViewModel
     */
    public function indexAction() {
        $data = "";
        $status = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        VehicleTypeForm::$vehicletype = $this->vehicleModel->getVehicleTypeList();
        $form = new VehicleTypeForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $status = (isset($post['status'])) ? $post['status'] : '';
            //Debug::dump($post); exit;
            $form->setData($request->getPost());
            if (!empty($post['search_vehicle_type'])) {
                if ($post['vehicle_type'] != "" && $post['status'] == "") {
                    $val = '{"where": {"id":' . $post['vehicle_type'] . '}}';
                    $data = rawurlencode($val);
                } else if ($post['vehicle_type'] != "" && $post['status'] != "") {
                    $val = '{"where":{"and": [{"id": "' . $post['vehicle_type'] . '"},{"status":' . $post['status'] . '}]}}';
                    $data = rawurlencode($val);
                } else if ($post['vehicle_type'] == "" && $post['status'] != "") {
                    $val = '{"where": {"status":' . $post['status'] . '}}';
                    $data = rawurlencode($val);
                }
                //echo '<pre>';print_r($data);die();
                $this->flashMessenger()->addMessage(array('success' => 'Vehicle Type Listed successfully...'));
            } else {
                $created_date = date('Y-m-d H:i:s');
                $data = [];
                $data = [
                    'vehicle_type' => $post['vehicle_type_name'],
                    'status' => $post['status'],
                    'created_date' => $created_date,
                    'created_by' => $user_id
                ];
                $insertStatus = $this->vehicleModel->insertVehicleType($data);
                $data = "";
                $this->flashMessenger()->addMessage(array('success' => 'Vehicle Type added successfully...'));
            }
        }

        $mvehicleList = $this->vehicleModel->getVehicleTypeData($data);
        $mvehicleList = isset($mvehicleList['data']['data'])?$mvehicleList['data']['data']:'';
        //$mvehicleList = isset($mvehicleList)?$mvehicleList:'';
        //echo '<pre>';print_r($mvehicleList);die();
        $viewModel = new ViewModel(['form' => $form, 'mvehicleList' => $mvehicleList, 'vehicle_type_id' => '', 'status' => $status]);
        return $viewModel;
    }

    public function deleteAction() {
        $id = $this->params()->fromQuery('data');
        $data = ['id' => $id];
        $this->vehicleModel->deleteVehicleType($data);
        $this->redirect()->toRoute('vehicletype', ['action' => 'index']);
    }

    public function editAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $form = new VehicleTypeForm();
        $id = $this->params()->fromQuery('id');
        $url = $this->apiUrl() . "/vehicle-type/" . $id;
        $resp = $this->get($url);
        $vehicleData = Json::decode($resp->getBody(), true);
        //Debug::dump($vehicleData); exit;
        $vehicleType = isset($vehicleData['vehicle_type'])?$vehicleData['vehicle_type']:'';
        $vehicleTypeStatus = $vehicleData['status'];
        $vehicleImage = isset($vehicleData['vehicle_image'])?$vehicleData['vehicle_image']:'';
        $form->get('vehicle_type_name')->setValue($vehicleType);
        $form->get('vehicle_type_id')->setValue($id);
        $form->setData($vehicleData);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($post);
            if ($form->isValid()) {
                if (isset($_FILES['vehicle_image']['name']) && $_FILES['vehicle_image']['name'] != '') {
                    $file = $_FILES['vehicle_image']['tmp_name'];
                    $file    = file_get_contents($file);
                    $base64string    = base64_encode($file);
                    $uploaddir = $_SERVER['DOCUMENT_ROOT'];
                    $file = '/upload/vehicle_type_image/';
                    $fileName= 'vehicle_type'.date('Y-m-d_h-i-s');
                    $filepath = $uploaddir . $file . $fileName;
                    $data1['base64image']= $base64string;
                    $data1['filepath']= $filepath;
                    $this->vehicleModel->uploadimageapi($data1);
                }else{
                    $fileName = "";
                }
                $data = [
                    'id' => $post['vehicle_type_id'],
                    'vehicle_type' => $post['vehicle_type_name'],
                    'seating_capacity' => $post['seating_capacity'],
                    'luggage' => $post['luggage'],
                    'color' => $post['color'],
                    //'vehicle_image' => $fileName,
                    'status' => $post['status'],
                    'modified_by' => $user_id
                ];
                if($fileName!=""){
                    $data['vehicle_image']=$fileName;
                }
                //echo '<pre>';print_r($data);die();
                $insertStatus = $this->vehicleModel->updateVehicleType($data);
                $this->redirect()->toRoute('vehicletype', ['action' => 'index']);
            }
        }



//        $request = $this->getRequest();
//        if ($request->isPost()) {
//            $post = $request->getPost()->toArray();
//            $data = [];
//            $data = [
//                'id' => $post['vehicle_type_id'],
//                'vehicle_type' => $post['vehicle_type_name'],
//                'status' => $post['status'],
//                'modified_by' => $user_id
//            ];
//            $insertStatus = $this->vehicleModel->updateVehicleType($data);
//            $this->redirect()->toRoute('vehicletype', ['action' => 'index']);
//        }
        $mvehicleList = $this->vehicleModel->getVehicleTypeData();
        $mvehicleList = $mvehicleList['data']['data'];
        $viewModel = new ViewModel(['form' => $form, 'mvehicleList' => $mvehicleList, 'vehicle_type_id' => $id, 'status' => $vehicleTypeStatus, 'vehicleImage'=>$vehicleImage]);
        $viewModel->setTemplate('/dashboard/vehicle-type/edit-vehicle-type');
        return $viewModel;
    }

    /** Function to change VEHICLE TYPE STATUS */
    public function vehicleTypeStatusAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        //print_r($data); die;
        $id = implode(',', $data['selected']);
        $vehicle_type_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'vehicle_type_status' => $vehicle_type_status];
        $this->vehicleModel->updateVehicleTypeStatus($data);
        $mvehicleList = $this->vehicleModel->getVehicleTypeData();
        $mvehicleList = $mvehicleList['data']['data'];
        $viewModel = new ViewModel(['mvehicleList' => $mvehicleList]);
        $viewModel->setTemplate('/dashboard/vehicle-type/vehicle-type-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function addVehicleTypeAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $form = new VehicleTypeForm();
        $request = $this->getRequest();


        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($post);
            if ($form->isValid()) {
                //echo '<pre>';print_r($post);die();
                if (isset($_FILES['vehicle_image']['name']) && $_FILES['vehicle_image']['name'] != '') {
                    $file = $_FILES['vehicle_image']['tmp_name'];
                    $file    = file_get_contents($file);
                    $base64string    = base64_encode($file);
                    $uploaddir = $_SERVER['DOCUMENT_ROOT'];
                    $file = '/upload/vehicle_type_image/';
                    $fileName= 'vehicle_type'.date('Y-m-d_h-i-s');
                    $filepath = $uploaddir . $file . $fileName;
                    $data1['base64image']= $base64string;
                    $data1['filepath']= $filepath;
                    $this->vehicleModel->uploadimageapi($data1);
                }else{
                    $fileName = "";
                }

                $data = [
                    'vehicle_type' => $post['vehicle_type_name'],
                    'seating_capacity' => $post['seating_capacity'],
                    'luggage' => $post['luggage'],
                    'color' => $post['color'],
                    'vehicle_image' => $fileName,
                    'status' => $post['status'],
                    'created_date' => date('Y-m-d H:i:s'),
                    'created_by' => $user_id
                ];
                $insertStatus = $this->vehicleModel->insertVehicleType($data);
                $this->flashMessenger()->addMessage(array('success' => 'Vehicle Type added successfully...'));
                $this->redirect()->toRoute('vehicletype', ['action' => 'index']);
            }
        }
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;

  }

  /** Function to change VEHICLE TYPE STATUS */
    public function vehicleTypeOrderAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        //print_r($data); die;
        //$id = implode(',', $data['position']);
        $position = $data['order'];
        //echo '<pre>';print_r($position);die();
        foreach($position as $v){
            if($v['id']!=""){
                $data = ['user_id' => $user_id, 'id' => $v['id'], 'display_order' => $v['position']];
                $this->vehicleModel->updateVehicleTypeOrder($data);
            }
        }
        $mvehicleList = $this->vehicleModel->getVehicleTypeData();
        $mvehicleList = $mvehicleList['data']['data'];
        $viewModel = new ViewModel(['mvehicleList' => $mvehicleList]);
        $viewModel->setTemplate('/dashboard/vehicle-type/vehicle-type-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

}
