<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    CronForm,
    CronScheduleForm
};

use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Zend\Session\Container;
use Zend\Debug\Debug;
use Dashboard\Model\User;

class CronController extends RestAPIClientController {
    
    public function __construct() {
        $this->userModel = new User();
    }

    /**
     * Payment Approved
     * @return ViewModel
     */
    public function indexAction() {
        $data = [];
        $data = ['company_id' => $this->config()->getConfig()->company->companyId];
        $uLicenseList = $this->getCronList($data);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        return $viewModel;
    }
  
    /**
     * Get CRON LIST
     * @return JSON
     */
    public function getCronList($data) {      
        $url = $this->apiUrl() . "/master-cron/getCronList";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        $result = [];
        if($responsedata['responsedata']['status']=="success"){
            $result = $responsedata['responsedata']['data'];
        }
        return $result;
    }
    
    public function getMasterCronList() {       
        $data = [];
        $data = ['company_id' => $this->config()->getConfig()->company->companyId];
        $url = $this->apiUrl() . "/master-cron/getCronList";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        $result = [];
        if($responsedata['responsedata']['status']=="success"){
            foreach ($responsedata['responsedata']['data'] as $res) {
                    $result[$res['id']] = $res['name'];
            }
        }
        return $result;
    }   
    
    /**
     * Get CRON SCHEDULE LIST
     * @return JSON
     */
    public function getCronScheduleList($data) {      
        $url = $this->apiUrl() . "/cron-schedule/getCronScheduleList";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        $result = [];
        if($responsedata['responsedata']['status']=="success"){
            $result = $responsedata['responsedata']['data'];
        }
        return $result;
    }
    
    public function addCronAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $form = new CronForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($post);
            if ($form->isValid()) {
                //echo '<pre>';print_r($post);die();
                $data = [
                    'company_id'=> $this->config()->getConfig()->company->companyId,
                    'name' => $post['name'],
                    'description' => $post['description'],
                    'created_by' => $user_id,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                //echo '<pre>';print_r($data);die();
                $insertStatus = $this->addCronDetail($data);
                //echo '<pre>';print_r($insertStatus);die();
                if ($insertStatus['responsedata']['status'] == "success") {
                    $this->flashMessenger()->addMessage(array('success' => 'Cron Details added successfully...'));
                } else {
                    $this->flashMessenger()->addMessage(array('error' => 'Somet thing Went Wrong'));
                }
                $this->redirect()->toRoute('cron', ['action' => 'index']);
            }
        }
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }
    
     /** Function to change CRON STATUS */
    public function cronStatusAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'status' => $status];
        $this->updateCronStatus($data);
        $val = ['company_id' => $this->config()->getConfig()->company->companyId];
        $uLicenseList = $this->getCronList($val);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        $viewModel->setTemplate('/dashboard/cron/cron-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function changeRecordStatusAction() {
        $status=0;
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            if($postData['status']==0 || $postData['status']==2){
                $status=1;
            }
            $data = ['user_id' => $user_id, 'id' => $postData['id'], 'status' => $status];
            $this->updateCronStatus($data);
        }
        $val = ['company_id' => $this->config()->getConfig()->company->companyId];
        $uLicenseList = $this->getCronList($val);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        $viewModel->setTemplate('/dashboard/cron/cron-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function deleteCronAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $id = $this->params()->fromQuery('data');
        $data = ['id' => $id, 'user_id'=>$userId, 'status'=>2];
        $this->updateCronStatus($data);
        $this->redirect()->toRoute('cron', ['action' => 'index']);
        $this->flashMessenger()->addMessage(array('success' => 'Cron Delete Successfully'));
    }
    
    public function addCronDetail($data) {
        $responsedata = [];
        $url = $this->apiUrl() . "/master-cron/addCronDetail";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        return $responsedata;
    }
    
    public function addCronScheduleDetail($data) {
        $responsedata = [];
        $url = $this->apiUrl() . "/cron-schedule/addCronScheduleDetail";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        return $responsedata;
    }
    
    public function updateCronScheduleDetail($data) {
        $responsedata = [];
        $url = $this->apiUrl() . "/cron-schedule/updateCronScheduleDetail";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        return $responsedata;
    }
    
     /** Function to Update the CRON STATUS */
    public function updateCronStatus($data) {
        $url = $this->apiUrl() . "/master-cron/cronListStatus"; //die;
        $resp = $this->put($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }
    
    /** Function to Update the CRON SCHEDULE STATUS */
    public function updateCronScheduleStatus($data) {
        $url = $this->apiUrl() . "/cron-schedule/cronScheduleListStatus"; //die;
        $resp = $this->put($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }
    
     /**
     * Payment Approved
     * @return ViewModel
     */
    public function cronScheduleAction() {
        $data = [];
        $uLicenseList = $this->getCronScheduleList($data);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        return $viewModel;
    }
    
    public function addCronScheduleAction() {
        $data = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        CronScheduleForm::$cron_master = $this->getMasterCronList();
        CronScheduleForm::$user_roles = $this->userModel->getRoleTypeList();
        $form = new CronScheduleForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($post);
            if ($form->isValid()) {
                //echo '<pre>';print_r($post);die();
                $data = [
                    'cron_id'=> $post['cron_id'],
                    'role_id' => $post['role_id'],
                    'day' => $post['day'],
                    'before_after' => $post['before_after'],
                    'created_by' => $user_id,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                //echo '<pre>';print_r($data);die();
                $insertStatus = $this->addCronScheduleDetail($data);
                //echo '<pre>';print_r($insertStatus);die();
                if ($insertStatus['responsedata']['status'] == "success") {
                    $this->flashMessenger()->addMessage(array('success' => 'Cron Schedule Details added successfully...'));
                } else {
                    $this->flashMessenger()->addMessage(array('error' => 'Somet thing Went Wrong'));
                }
                $this->redirect()->toRoute('cron', ['action' => 'cron-schedule']);
            }
        }
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }
    
    public function editCronScheduleAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];

        CronScheduleForm::$cron_master = $this->getMasterCronList();
        CronScheduleForm::$user_roles = $this->userModel->getRoleTypeList();
        $form = new CronScheduleForm();        
        $id = $this->params()->fromQuery('id');
        $data=[
            'auto_id'=>$id
        ];
        $vehicleData = $this->getCronScheduleList($data);
        $vehicleData = $vehicleData[0];
        $form->setData($vehicleData);
        $form->get('id')->setValue($vehicleData['cron_schedule_id']);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            $postData = $this->getRequest()->getPost();
            $postData = $postData->toArray();   
            $postData['cron_id'] = $postData['cron_id'];
            $postData['role_id'] = $postData['role_id'];
            $postData['day'] = $postData['day'];
            $postData['before_after'] = $postData['before_after'];
            $postData['modified_by'] = $user_id;
            $postData['ip'] = $_SERVER['REMOTE_ADDR'];
            $postData['auto_id'] = $postData['id'];
            //$postData = array_filter($postData);
            if($form->isValid()) {
                $updateStatus = $this->updateCronScheduleDetail($postData);
                if ($updateStatus['responsedata']['status'] == "success") {
                    $this->flashMessenger()->addMessage(array('success' => 'Cron Schedule Details updated successfully...'));
                } else {
                    $this->flashMessenger()->addMessage(array('error' => 'Details not updated..'));
                }
                $this->redirect()->toRoute('cron', ['action' => 'cron-schedule']);
            }            
        }
        $viewModel = new ViewModel([
            'form' => $form
        ]);
        return $viewModel;
    }
    
     /** Function to change CRON STATUS */
    public function cronScheduleStatusAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'status' => $status];
        $this->updateCronScheduleStatus($data);
        $val = [];
        $uLicenseList = $this->getCronScheduleList($val);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        $viewModel->setTemplate('/dashboard/cron/cron-schedule-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function changeScheduleRecordStatusAction() {
        $status=0;
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            if($postData['status']==0 || $postData['status']==2){
                $status=1;
            }
            $data = ['user_id' => $user_id, 'id' => $postData['id'], 'status' => $status];
            $this->updateCronScheduleStatus($data);
        }
        $val = [];
        $uLicenseList = $this->getCronScheduleList($val);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        $viewModel->setTemplate('/dashboard/cron/cron-schedule-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function deleteCronScheduleAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $id = $this->params()->fromQuery('data');
        $data = ['id' => $id, 'user_id'=>$userId, 'status'=>2];
        $this->updateCronScheduleStatus($data);
        $this->redirect()->toRoute('cron', ['action' => 'cron-schedule']);
        $this->flashMessenger()->addMessage(array('success' => 'Cron Schedule Delete Successfully'));
    }

}
