<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Zend\Json\Json;
use Zend\Config\Config;
use Zend\Config\Factory;
use Zend\Validator\StringLength;
use Dashboard\Model\UserLicenseModel;
use Dashboard\Model\CommonModel;
use Dashboard\Model\User;
use Dashboard\Form\{
    AdUserLicenseForm
};

use User\Form\LoginForm;
use User\Form\ApiUserForm;
use User\Model\Registration;
 

class LicenseController extends RestAPIClientController {

    public function __construct() {
        $this->userModel = new User();
        $this->licenseModel = new UserLicenseModel();
        $this->commonModel = new CommonModel();
        $this->registrationModel = new Registration();
    }

    /**
     * index
     * @return ViewModel
     */
    public function indexAction() {
        $data = "";
        $status = "";
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $user_id = $sessionContainer->user_id;

        AdUserLicenseForm::$membershipackage = $this->licenseModel->getMembershipPackage();
        AdUserLicenseForm::$master_package = $this->commonModel->getPackageTypeList();
        $form = new AdUserLicenseForm();
        //$data = ['user_id' => $user_id];
        $data = [];
        $uLicenseList = $this->licenseModel->getUserLicenseDetail($data);
        //echo '<pre>';print_r($uLicenseList);die();
        $viewModel = new ViewModel(['form' => $form, 'uLicenseList' => $uLicenseList, 'status' => $status]);
        return $viewModel;
    }

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

        AdUserLicenseForm::$membershipackage = $this->licenseModel->getMembershipPackage();
        AdUserLicenseForm::$master_package = $this->commonModel->getPackageTypeList();
        $form = new AdUserLicenseForm();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());

            $postData = $this->getRequest()->getPost();
            $postData = $postData->toArray();
            $postData['created_by'] = $user_id;
            $postData['license_start_date'] = date('Y-m-d',strtotime($postData['license_start_date']));
            $postData['license_end_date'] = date('Y-m-d',strtotime($postData['license_end_date']));
            $postData['ip'] = $_SERVER['REMOTE_ADDR'];
            if ($form->isValid()) {
                $insertStatus = $this->licenseModel->insertLicenseData($postData);
                if ($insertStatus['responsedata']['status'] == "success") {
                    $this->flashMessenger()->addMessage(array('success' => 'Details insert successfully...'));
                } else {
                    $this->flashMessenger()->addMessage(array('error' => 'Details not inserted..'));
                }
                $this->redirect()->toRoute('license', ['action' => 'index']);
            }else{
                //$m  =   $form->getMessages();
                //echo '<pre>';print_r($m);die();
            }
            
        }
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }
    
    public function editUserLicenseAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];

        AdUserLicenseForm::$membershipackage = $this->licenseModel->getMembershipPackage();
        AdUserLicenseForm::$master_package = $this->commonModel->getPackageTypeList();
        $form = new AdUserLicenseForm();
        
        $id = $this->params()->fromQuery('id');
        $data=[
            'auto_id'=>$id
        ];

        $vehicleData = $this->licenseModel->getUserLicenseDetail($data);
        $vehicleData = $vehicleData[0];
        //echo '<pre>';print_r($vehicleData);die();
        $form->setData($vehicleData);
        $form->get('owner_name')->setValue($vehicleData['first_name']);
        $form->get('owner_address')->setValue($vehicleData['last_name']);
        $form->get('owner_email')->setValue($vehicleData['email']);
        $form->get('owner_mobile')->setValue($vehicleData['mobile']);
        $form->get('user_license_id')->setValue($vehicleData['user_license_id']);
        $form->get('package')->setValue($vehicleData['package_id']);
        $form->get('license_start_date')->setValue(date('d-m-Y', strtotime($vehicleData['license_start_date'])));
        $form->get('license_end_date')->setValue(date('d-m-Y', strtotime($vehicleData['license_end_date'])));
        $userRegisterDomains  = $this->licenseModel->getUserDomainRegisterList($vehicleData['user_license_id']);
        $userDomainsPackage  = $this->licenseModel->getUserDomainPackageList($vehicleData['user_license_id']);
        //echo '<pre>';print_r($userDomainsPackage);die();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            $postData = $this->getRequest()->getPost();
            $postData = $postData->toArray();            
            $postData['modified_by'] = $user_id;
            $postData['created_by'] = $user_id;
            $postData['license_start_date'] = date('Y-m-d',strtotime($postData['license_start_date']));
            $postData['license_end_date'] = date('Y-m-d',strtotime($postData['license_end_date']));
            $postData['ip'] = $_SERVER['REMOTE_ADDR'];
            $postData = array_filter($postData);
            //echo '<pre>';print_r($postData);die();
            if($form->isValid()) {
                $updateStatus = $this->licenseModel->updateLicenseData($postData);
                if ($updateStatus['responsedata']['status'] == "success") {
                    $this->flashMessenger()->addMessage(array('success' => 'Details updated successfully...'));
                } else {
                    $this->flashMessenger()->addMessage(array('error' => 'Details not updated..'));
                }
                $this->redirect()->toRoute('license', ['action' => 'index']);
            }
            
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'userRegisterDomains' => $userRegisterDomains,
            'userDomainsPackage' => $userDomainsPackage
        ]);
        return $viewModel;
    }
    
    
    /** Function to change USER LICENSE STATUS */
    public function userLicenseStatusAction() {
        $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']);
        $license_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'status' => $license_status];
        $this->licenseModel->updateUserLicenseStatus($data);
        $val = ['user_id' => $user_id];
        $uLicenseList = $this->licenseModel->getUserLicenseDetail($val);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        $viewModel->setTemplate('/dashboard/license/user-license-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->licenseModel->updateUserLicenseStatus($data);
        }
        $val = ['user_id' => $user_id];
        $uLicenseList = $this->licenseModel->getUserLicenseDetail($val);
        $viewModel = new ViewModel(['uLicenseList' => $uLicenseList]);
        $viewModel->setTemplate('/dashboard/license/user-license-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function deleteLicenseAction() {
        $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->licenseModel->updateUserLicenseStatus($data);
        $this->redirect()->toRoute('license', ['action' => 'index']);
        $this->flashMessenger()->addMessage(array('success' => 'License Delete Successfully'));
    }
    
    public function addNewUserLicenseAction(){
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        $form = new LoginForm();
        $msg = "";
        $valide_mobile = '';
        $request = $this->getRequest();
        $usertype = 'api-user';
        $userTypeArr = $this->config()->getConfig()->userTypeId;
        $userTypeArr = $userTypeArr->toArray();
        $userTypeId = $userTypeArr[$usertype];

        ApiUserForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        ApiUserForm::$master_package = $this->commonModel->getPackageTypeList();
        ApiUserForm::$membershipackage = $this->licenseModel->getMembershipPackage();

        $loginDetailForm = new ApiUserForm();
        $loginDetailForm->get('registration_type')->setValue($userTypeId);
        $loginDetailForm->get('prefix_contact_no')->setAttribute('class', 'test_class');
        if ($request->isPost()) {
            $loginDetailForm->setData($request->getPost());

            $loginformData = $this->getRequest()->getPost();
            $loginformData = $loginformData->toArray();

            if ($loginDetailForm->isValid()) {

                $first_name = (trim($loginformData['first_name']));
                $last_name = (trim($loginformData['last_name']));
                $email = trim($loginformData['email']);
                $contact_no = $loginformData['contact_no'];
                $password = trim($loginformData['password']);
                $registrationType = $loginformData['registration_type'];
                $confirmPassword = trim($loginformData['confirm_password']);
                $nationality = trim($loginformData['nationality_value']);
                $mobile_prefix =  $loginformData['prefix_contact_no'];
                $company_name    =  $loginformData['company_name'];
                $company_address =  $loginformData['company_address'];
                $company_postal_code =  $loginformData['company_postal'];
                $company_website =  $loginformData['company_website'];
                    $validator = new StringLength();
                    $validator->setMin(6);
                    $validator->setMax(20);
                    $valid = $validator->isValid("$password");
                    if ($valid) {
                        if ($confirmPassword == $password) {
                            $finalData = [];
                            $finalData = [
                                'username' => $email,
                                'user_type_id' => $registrationType
                            ];

                            $JsonData = $this->registrationModel->verifyUser($email,$contact_no,$registrationType);
                            //echo '<pre>';print_r($JsonData);die();
                            if ((!empty($JsonData)) && ($JsonData['responsedata']['status']) == 'success') {
                                $responseData = $JsonData['responsedata']['data'];
                                $user_id = $responseData["user_id"];
                                $userTypeId = $responseData["user_type_id"];
                                $is_active = $responseData["is_active"];

                                $signup_status = $responseData['signup_status'];
                                if ($signup_status > 0 && $signup_status == 10 && $is_active == 0) {
                                    $msg = 'Account is not active,Contact with admin';
                                } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 1) {
                                    $msg = 'Account Already Created';
                                }
                            } else {
                                $finalData = [];
                                $finalData = [
                                    'company_id' => $this->config()->getConfig()->company->companyId,
                                    'first_name' => $first_name,
                                    'last_name' => $last_name,
                                    'email' => $email,
                                    'mobile_prefix' => $mobile_prefix,
                                    'mobile' => $contact_no,
                                    'user_type_id' => $userTypeId,
                                    'password' => $password,
                                    'nationality' => $nationality,
                                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                                    'signup_status' =>10, 
                                    'is_active' =>1 
                                ];
                                $finalData = array_filter($finalData);
                                $finalData['parent_id'] = 0;
                                $JsonData = $this->registrationModel->userNewSignup($finalData);
                                if (!empty($JsonData)) {
                                    if($JsonData['responsedata']['status']=='failed'){
                                        $msg = $JsonData['responsedata']['message'];
                                    }else{
                                        $user_id = $JsonData['responsedata']['user_id'];
                                        //$sessionContainer = new Container('userlogin');
                                        //$sessionContainer->user_id = $user_id;                                        
                                        $companyData = [];
                                        $companyData = [
                                            'user_id' => $user_id,
                                            'company_name' => $company_name,
                                            'company_address' => $company_address,                                         
                                            'email' => $email,                                           
                                            'mobile_no' => $contact_no,                                          
                                            'country' => $nationality,
                                            'pincode' => $company_postal_code,                                           
                                            'added_by' => $user_id,                                            
                                            'website_url' => $company_website,                                            
                                            'created_date' => date('Y-m-d')                                            
                                        ];
                                                                            
                                        $url = $this->apiUrl() . "/company";
                                        $val = $this->post($url, $companyData);
                                        $JsonData = $val->getBody();               
                                        $JsonData = Json::decode($JsonData, true);  
                                        
                                        $adduserlicenseData = [
                                            'user_id'     => $user_id,
                                            'module'      =>  $loginformData['package_module'],
                                            'package'     =>  $loginformData['package'],
                                            'license_option' =>  $loginformData['license_option'],
                                            'created_by'  => $user_id,                                            
                                            'domain_name' => $company_website,
                                             'ip'         => $_SERVER['REMOTE_ADDR']
                                        ];
                                        
                                        $this->licenseModel->insertLicenseData($adduserlicenseData);
                                        $this->redirect()->toRoute('license', ['action' => 'index']);
                                    }
                                }else{
                                   $msg = "Registration not done";
                                }
                            }
                        } else {
                            $msg = "password and confirm password did't match";
                        }
                    } else {
                        $msg = "password should be greater than 6 and smaller than 20";
                    }
            } else {
                //$msg = "All fields are mandatory";
            }
        }
        
        $viewModel = new ViewModel(
                [
            'form' => $loginDetailForm,
            'loginform' => $form,
            'error_msg' => $msg
        ]);
        
        return $viewModel;
    }



}
