<?php

namespace Dashboard\Controller;

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

class AirportMasterController extends RestAPIClientController {

    public function __construct() {
        $this->commonModel = new CommonModel();
    }

    /**
     * Index
     * @return ViewModel
     */
    public function indexAction() {

        $form = new AirportForm ();
        $data = [];
        $airportlisting = $this->getAirportListing($data);
        $viewModel = new ViewModel(['form' => $form, 'airportlisting' => $airportlisting]);
        return $viewModel;
    }

    public function addAirportAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

        $form = new AirportForm ();
        $request = $this->getRequest();

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

            $AreaName = $this->fetchGoogleApiData($postData['airport_railway_name']);
            $AreaName = Json::decode($AreaName);
            if (isset($AreaName) && !empty($AreaName)) {
                $AreaLat = $AreaName->results[0]->geometry->location->lat;
                $AreaLng = $AreaName->results[0]->geometry->location->lng;
                $AreaZone = $AreaName->results[0]->address_components[1]->long_name;
            } else {
                $AreaLat = '';
                $AreaLng = '';
                $AreaZone = '';
            }
            $finalData = [];
            $finalData = [
                'country_id' => $postData['country_id'],
                'state_id' => $postData['state_id'],
                'city_id' => $postData['city_id'],
                'airport_railway_name' => $postData['airport_railway_name'],
                'meeting_point' => $postData['meeting_point'],
                'latitude' => $AreaLat,
                'longitude' => $AreaLng,
                'zone' => $AreaZone,
                'status' => $postData['status'],
                'created_by' => $userId,
                'created_date' => date('Y-m-d')
            ];

            $finalData = array_filter($finalData);
            //echo'<pre>';print_r($finalData);die();
            $url = $this->apiUrl() . "/airport-railway";
            $val = $this->post($url, $finalData);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);


            if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                $msg = "Details Added Successfully!..";

                $this->redirect()->toRoute('airport-master', ['action' => 'add-airport']);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {
                $msg = "Details Could Not Added!..";
                $color = "red";
                $this->redirect()->toRoute('airport-master', ['action' => 'add-airport']);
                $this->flashMessenger()->addMessage(array('danger' => $msg));
            }
        }
        else{
            $msg = $form->getMessages();

        }

    }
     $data = [];
     $airportlisting = $this->getAirportListing($data);
     $viewModel = new ViewModel(['form' => $form, 'airportlisting' => $airportlisting]);
        return $viewModel;

  }

    public function editAirportAction() {
        $responsedata = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $id = $this->params()->fromQuery('id');
        $form = new AirportForm ();
        $request = $this->getRequest();
        if (!empty($id)) {
            $data = [
                'id' => $id
            ];
            $url = $this->apiUrl() . "/airport-railway/masterairport";
            $val = $this->post($url, $data);
            $JsonData = $val->getBody();
            $getres = Json::decode($JsonData, true);
            $responsedata = $getres['responsedata'][0];
            $form->setData($responsedata);
        }
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {

            $AreaName = $this->fetchGoogleApiData($postData['airport_railway_name']);
            $AreaName = Json::decode($AreaName);
            if (isset($AreaName) && !empty($AreaName)) {
                $AreaLat = $AreaName->results[0]->geometry->location->lat;
                $AreaLng = $AreaName->results[0]->geometry->location->lng;
                $AreaZone = $AreaName->results[0]->address_components[1]->long_name;
            } else {
                $AreaLat = '';
                $AreaLng = '';
                $AreaZone = '';
            }
            $finalData = [];
            $finalData = [
                'id' => $postData['id'],
                'country_id' => $postData['country_id'],
                'state_id' => $postData['state_id'],
                'city_id' => $postData['city_id'],
                'airport_railway_name' => $postData['airport_railway_name'],
                'meeting_point' => $postData['meeting_point'],
                'latitude' => $AreaLat,
                'longitude' => $AreaLng,
                'zone' => $AreaZone,
                'status' => $postData['status']
                    // 'modified_by' => $userId,
                    //'modified_date' => date('Y-m-d H:i:s')
            ];
            $val = '{"id": "' . $postData['id'] . '"}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/airport-railway/update?where=" . $val;
            $val = $this->post($url, $finalData);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);

            if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                $msg = "Details Updated Successfully..!";

                $this->redirect()->toRoute('airport-master', ['action' => 'index']);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {
                $msg = "Details Could Not Updated ..!";
                $this->redirect()->toRoute('airport-master', ['action' => 'edit-airport','id'=>$postData['id']]);
                $this->flashMessenger()->addMessage(array('danger' => $msg));
            }
          }
           else{
            //$msg = $form->getMessages();
            return $this->redirect()->toUrl('edit-airport?id='.$postData['id']);
        }


        }
        $data = [];
        $airportlisting = $this->getAirportListing($data);
        $viewModel = new ViewModel(['form' => $form, 'airportlisting' => $airportlisting, 'getStatus' => $responsedata]);
        return $viewModel;
    }

    public function getCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $url = $this->apiUrl() . "/city/stateCountryByCityName?city_name=" . $term;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        $cityData = $cityJsonData['response']['data'];

        if ($cityJsonData['response']['status'] == "success") {
            foreach ($cityData as $value) {
                $data[] = ["country_id" => $value['country_id'], "state_id" => $value['state_id'], "city_id" => $value['city_id'], "label" => $value['citystatecountry']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function deleteAction() {
        $id = $this->params()->fromQuery('id');
        $url = $this->apiUrl() . "/airport-railway/" . $id;
        $resp = $this->delete($url, true);
        $vehicleTypeJsonData = Json::decode($resp->getBody(), true);
        if ($vehicleTypeJsonData['count'] == 1) {
            $msg = "Record Deleted Successfully..!";

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

    public function getAirportListing($data) {
        //echo'<pre>';print_r($data);die();
        $url = $this->apiUrl() . "/airport-railway/masterairport";
        $resp = $this->post($url, $data);
        $airportlisting = Json::decode($resp->getBody(), true);
        //echo'<pre>';print_r($airportlisting);die();
        return $airportlisting['responsedata'];
    }

    public function fetchGoogleApiData($address) {
        $url = $this->config()->getConfig()->google_map->apiData . "?address=" . urlencode($address) . '&key=' . $this->config()->getConfig()->google_map->key;
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl_handle);
        $result = curl_exec($curl_handle);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($curl_handle));
        }
        curl_close($curl_handle);
        return $result;
    }

    public function filterAirportAction() {
        $postData = $this->getRequest()->getPost()->toArray();
        $city_id = isset($postData['city_id']) ? $postData['city_id'] : '';
        $airport_railway_name = isset($postData['airport_railway_name']) ? $postData['airport_railway_name'] : '';
        $status = isset($postData['status']) ? $postData['status'] : '';

        $data = [];
        $data = [
            'city_id' => $postData['city_id'],
            'airport_name' => $postData['airport_railway_name'],
        ];

        $data = array_filter($data);
        $data['status']=$postData['status'];
        $airportlisting = $this->getAirportListing($data);
        $viewModel = new ViewModel(['airportlisting' => $airportlisting]);
        $viewModel->setTemplate('/dashboard/airport-master/airport-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

      public function StatusAction() {
        $form = new AirportForm ();
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $postData = $this->getRequest()->getPost();
        $id = implode(',', $postData['selected']);
        $airport_status = $postData['status'];
        $data1 = ['user_id' => $user_id, 'id' => $id, 'airport_status' => $airport_status];
        //echo '<pre>';print_r($data1);die();
        $this->commonModel->updateAirportStatus($data1);
        $airportlisting = $this->getAirportListing($data);
        $viewModel = new ViewModel(['form' => $form, 'airportlisting' => $airportlisting]);
        $viewModel->setTemplate('dashboard/airport-master/airport-listing.phtml');
        $viewModel->setTerminal(true);

        return $viewModel;
    }
}
