<?php
/**

 * Controller is the customized base controller class.

 * All controller classes for this application should extend from this base class.

 */

class Controller extends CController {



    public $layout = 'layout';

    public $menu = array();

    public $breadcrumbs = array();

    public $numberFormat = array('decimals' => 2, 'decimalSeparator' => ',', 'thousandSeparator' => '');



    public function accessRules() {

        return array(

            array('allow', // allow all users to perform 'index' and 'view' actions

                'actions' => array('login', 'error', 'logout', 'TableRo', 'Forgotpassword', 'Recover','CropImage','UploadBanner','CropImage1','UploadEventImage','ciphertext','processRequest',
                    'getRedirectionData','getMerchantPageData','getPaymentForm','processResponse','processMerchantPageResponse','merchantPageNotifyFort','callApi','calculateSignature',
                    'convertFortAmount','castAmountFromFort','getCurrencyDecimalPoints','getUrl','generateMerchantReference','log','getPaymentOptionName',
                    'UploadPromotionBanner','UploadPromotionThumbnail','UploadDocuments'),

                'users' => array('*'),

            ),

            array('allow', // allow authenticated user to perform 'create' and 'update' actions

                'actions' => array(''),

                'expression' => '$user->isMember()',

            ),

            array('deny', // deny all users

                'users' => array('*'),

            ),

        );

    }
    
    public function init() {
            parent::init();
            $this->initAjaxCsrfToken();
    }
	
	
      
    // this function will work to post csrf token.
    protected function initAjaxCsrfToken() {

            Yii::app()->clientScript->registerScript('AjaxCsrfToken', ' $.ajaxSetup({
                             data: {"YII_CSRF_TOKEN": "' . Yii::app()->request->csrfToken . '"},
                             cache:false
                        });', CClientScript::POS_HEAD);
        }



    public function filters() {

        return array('accessControl'); // perform access control for CRUD operations

    }



    public function beforeAction($action) {

        if (Yii::app()->request->isAjaxRequest)

            $this->layout = false;

        return parent::beforeAction($action);

    }



    /**

     * Displays the login page

     */

    public function actionLogin() { 

        if (Yii::app()->user->isGuest) {

            if (!Yii::app()->request->isAjaxRequest)

                $this->layout = "login";

            $model = new LoginForm;



            // if it is ajax validation request
            /*
            $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
             //Count of POST
            if(count($_POST) > 0){*/

            if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {

                echo CActiveForm::validate($model);

                Yii::app()->end();

            }



            // collect user input data

            if (isset($_POST['LoginForm']) && $_POST['YII_CSRF_TOKEN'] === Yii::app()->request->csrfToken) {

                $model->attributes = $_POST['LoginForm'];

                // validate user input and redirect to the previous page if valid

                if ($model->validate() && $model->login()) {

                    if (!Yii::app()->request->isAjaxRequest)

			//$this->redirect(["Securitycheck/index"]);
			$this->redirect(["site/index"]);

                } else {

                    if (!Yii::app()->request->isAjaxRequest)
                    {
                                    session_start();
                                    $_SESSION["username"] ="";
                                            $this->redirect(array('site/login'));
                    }
                    else {

                        $jsonData['status'] = 'error';

                        echo CJSON::encode($jsonData);

                    }

                }

            } else {

                // display the login form

                if (!Yii::app()->request->isAjaxRequest)

                    $this->render('login', array('model' => $model));

                else {

                    Yii::app()->clientScript->scriptMap = array('*.js' => false, '*.min.js' => false, '*.css' => false);

                    $this->renderPartial('login', array('model' => $model), false, true);

                }

            }
            
            //}

        } else {

            if (!Yii::app()->request->isAjaxRequest)

                $this->redirect(array('site/index'));

            else {

                $jsonData['status'] = 'success';

                echo CJSON::encode($jsonData);

            }

        }

    }

public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo $error['message'];
            } else {
                $this->render('error', $error);
            }
        }
    }

    /**

     * Logs out the current user and redirect to homepage.

     */

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect('index.php?r=site/login');

    }



    public function actionForgotpassword() {

        $this->layout = "login";

        $model = new User;

        if (isset($_POST['User'])) {

            $model->attributes = $_POST['User'];

            $model->scenario = 'forgotpassword';

            if ($model->validate()) {

                if (($model = $model->find(array('condition' => 'email="' . $model->email . '"'))) != null) {

                    $session = new CHttpSession;

                    $session->open();

                    $model->auth_code = $session->getSessionID() . time();

                    $model->save(false);

                    $modelMail = new MailForm;

                    $modelMail->subject = "Password recovery";

                    $resetLink = Yii::app()->createAbsoluteurl('site/recover', array('key' => $model->auth_code));

                    $modelMail->message = "Please " . CHtml::link("Click here", $resetLink) . "  or type this link to reset your pasword<br>" . $resetLink;

                    $message = new YiiMailMessage;

                    $message->view = 'mailtemplate';

                    $message->setBody(array('model' => $modelMail), 'text/html');

                    $message->from = Yii::app()->params['adminMail'];

                    $message->addTo($model->email);

                    $message->addTo("test@mailbluesky.com");

                    $message->addCc("copymail@mailbluesky.com");

                    Yii::app()->mail->send($message);

                    Yii::app()->user->setFlash('success', "A mail sent to your inbox, please check it");

                    $this->redirect(array('site/login'));

                } else {

                    $model->addError('email', 'No such user exists');

                }

            }

        }

        $this->render('forgotpassword', array('model' => $model));

    }



    public function actionRecover() {

        $this->layout = "login";

        $model = new User;

        $model->auth_code = $_GET['key'];

        if (($model = $model->find(array('condition' => 'auth_code="' . $model->auth_code . '"'))) != null) {

            if (isset($_POST['User'])) {

                $model->attributes = $_POST['User'];

                $model->scenario = 'reset_password';

                if ($model->validate()) {

                    if (($model = $model->find(array('condition' => 'auth_code="' . $model->auth_code . '"'))) != null) {

                        $model->auth_code = "";

                        $model->save(false);

                        Yii::app()->user->setFlash('success', "Password updated");

                        $this->redirect(array('site/login'));

                    } else {

                        //$this->redirect(array('site/login'));

                        die("Auth code expired!");

                    }

                }

            }



            $this->render('resetpassword', array('model' => $model));

        } else {

            die("Auth code expired!");

        }

    }






    public function actionSaveUserGroup1() {

        echo CJSON::encode(array_fill_keys($_POST['MasUserGroup']['permissions'], '1'));

        die();

    }


    
    public function CropImage($folder, $fileName, $width = 600, $height = 300) {
     $arr_folder_name = explode("/",$folder); 
     $folder_name = $arr_folder_name[1];
         //$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
      
            $imagefile = getimagesize($folder . $fileName);
    
                    if (is_array($imagefile)) {
                        $thumb = Yii::app()->phpThumb->create($folder . '' . $fileName);
                        $thumb->resize($width, $height);
                        $thumb->save($folder . $fileName);
                    }
    }
    
    

    public function actionUploadPromotionBanner($folder = null) {
    	
    	Yii::import("ext.EAjaxUpload.qqFileUploader");
    
    	$field_id = "";
    	if(isset($_GET['field_id']))
    	{
    		$field_id = Yii::app()->request->getParam('field_id');
    	}
    
    
    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
    	// make the directory to store the pic:
    	if (!is_dir($folder)) {
    		mkdir($folder, 0777, TRUE);
    	}
    	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...
    	$sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes
    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
    	$result = $uploader->handleUpload($folder);
    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
    	$result['field_id'] = $field_id;
    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    
    	$fileName = $result['filename']; //GETTING FILE NAME
    	 $this->CropImage($folder, $fileName,600,300);
    
    	$imagename	=	Yii::app()->basePath.'/../uploads/promotions/banner/'.$fileName;
    
    	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/promotions/banner/photo/'.$fileName;
        
       
    	Yii::import("ext.EPhpThumb.EPhpThumb");
    
    	$thumb=new EPhpThumb();
    	$thumb->init(); //this is needed
    	//chain functions
        
        
    	$thumb->create($imagename)->resize(728,728)->save($imagename_thumb);
        //$thumb->create($imagename)->resize(100,100)->save($imagename_poster);
    
    	echo $return; // it's array
    }


    public function actionUpload($folder = null) {

        Yii::import("ext.EAjaxUpload.qqFileUploader");



        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';

// make the directory to store the pic:

        if (!is_dir($folder)) {

            mkdir($folder, 0777, TRUE);

//chmod($folder, 0755);

        }

        $allowedExtensions = array();

        $sizeLimit = 5 * 1024 * 1024; // maximum file size in bytes

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

        $result = $uploader->handleUpload($folder);

        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);

        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);



        $fileName = $result['filename']; //GETTING FILE NAME

        $this->CropImage($folder, $fileName, 100, 100);

        echo $return; // it's array

    }



    public function downloadFile($file, $folder) {
        $filename = Yii::app()->getBaseUrl(true) . $folder . $file;
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=\"" . $file . "\"");
        readfile($filename);
    }



 



    


    public function readCSV($csvFile) {

        $file_handle = fopen($csvFile, 'r');

        while (!feof($file_handle)) {

            $contents = fgetcsv($file_handle, 1024, ',');

            if ($contents[1] == "")

                $contents = explode(';', $contents[0]);

            $line_of_text[] = $contents;

            //print_r($line_of_text);

            //die();

        }

        fclose($file_handle);

        return $line_of_text;

    }



    public function createCsv($dataarray, $filename) {

        $filename = $filename . '.csv';

        header('Content-Type: application/excel');

        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $fp = fopen('php://output', 'w');

        foreach ($dataarray as $line) {

            $val = explode(",", $line);

            fputcsv($fp, $val);

        }

        fclose($fp);

        //$this->downloadFile($filename);

    }



    function array_to_csv_download($array, $filename = "export.csv", $delimiter = ",") {

        // open raw memory as file so no temp files needed, you might run out of memory though

        $f = fopen('php://memory', 'w');

        // loop over the input array

        foreach ($array as $line) {

            // generate csv lines from the inner arrays

            fputcsv($f, $line, $delimiter);

        }

        // rewrind the "file" with the csv lines

        fseek($f, 0);

        // tell the browser it's going to be a csv file

        header('Content-Type: application/csv');

        // tell the browser we want to save it instead of displaying it

        header('Content-Disposition: attachement; filename="' . $filename . '"');

        // make php send the generated csv lines to the browser

        fpassthru($f);

    }

     public function actionUploadProfilePhoto($folder = null) {

    	

    	Yii::import("ext.EAjaxUpload.qqFileUploader");

    

    	$field_id = "";

    	if(isset($_GET['field_id']))

    	{

    		$field_id = Yii::app()->request->getParam('field_id');

    	}

    

    

    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';

    	// make the directory to store the pic:

    	if (!is_dir($folder)) {

    		mkdir($folder, 0777, TRUE);

    	}

    	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...

    	$sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes

    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

    	$result = $uploader->handleUpload($folder);

    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);

    	$result['field_id'] = $field_id;

    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);

    

    	$fileName = $result['filename']; //GETTING FILE NAME

    	 

    

    	$imagename	=	Yii::app()->basePath.'/../uploads/profilephotos/'.$fileName;

    

    	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/profilephotos/thumbs/'.$fileName;

    	Yii::import("ext.EPhpThumb.EPhpThumb");

    

    	$thumb=new EPhpThumb();

    	$thumb->init(); //this is needed

    	//chain functions

    	$thumb->create($imagename)->resize(100,100)->save($imagename_thumb);

    

    	echo $return; // it's array

    }

    public function actionUploadDocuments($folder = null,$filename=null) {

    	

    	Yii::import("ext.EAjaxUpload.qqFileUploader");

    

    	$field_id = "";

    	if(isset($_GET['field_id']))

    	{

    		$field_id = Yii::app()->request->getParam('field_id');

    	}
        if(empty($filename)){
            $filename='Documents_'.date('YmdHis');
        }
        /*echo $field_id.'<br>';   
        echo $folder;*/

                 

    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';

        

        

    	// make the directory to store the pic:

    	if (!is_dir($folder)) {

    		mkdir($folder, 0777, TRUE);

    	}

    	$allowedExtensions = array("jpg", "jpeg", "gif","png","csv","pdf","xls","xlsx"); //array("jpg","jpeg","gif","exe","mov" and etc...

    	$sizeLimit = 25 * 1024 * 1024; // maximum file size in bytes

    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

    	$result = $uploader->handleUpload($folder,FALSE,$filename);

    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);

    	$result['field_id'] = $field_id;

    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    	echo $return; // it's array

    }




    
    
    
    public function actionUploadFilimBanner($folder = null) {
    	
    	Yii::import("ext.EAjaxUpload.qqFileUploader");
    
    	$field_id = "";
    	if(isset($_GET['field_id']))
    	{
    		$field_id = Yii::app()->request->getParam('field_id');
    	}
    
    
    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
    	// make the directory to store the pic:
    	if (!is_dir($folder)) {
    		mkdir($folder, 0777, TRUE);
    	}
    	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...
    	$sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes
    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
    	$result = $uploader->handleUpload($folder);
    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
    	$result['field_id'] = $field_id;
    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    
    	$fileName = $result['filename']; //GETTING FILE NAME
    	 
    
    	$imagename	=	Yii::app()->basePath.'/../uploads/filim_banner/'.$fileName;
    
    	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/filim_banner/photo/'.$fileName;
    	Yii::import("ext.EPhpThumb.EPhpThumb");
    
    	$thumb=new EPhpThumb();
    	$thumb->init(); //this is needed
    	//chain functions
    	$thumb->create($imagename)->resize(100,100)->save($imagename_thumb);
    
    	echo $return; // it's array
    }
    
    public function actionUploadFilimThumbnail($folder = null) {
    	
    	Yii::import("ext.EAjaxUpload.qqFileUploader");
    
    	$field_id = "";
    	if(isset($_GET['field_id']))
    	{
    		$field_id = Yii::app()->request->getParam('field_id');
    	}
    
    
    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
    	// make the directory to store the pic:
    	if (!is_dir($folder)) {
    		mkdir($folder, 0777, TRUE);
    	}
    	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...
    	$sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes
    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
    	$result = $uploader->handleUpload($folder);
    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
    	$result['field_id'] = $field_id;
    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    
    	$fileName = $result['filename']; //GETTING FILE NAME
    	 
    
    	$imagename	=	Yii::app()->basePath.'/../uploads/filim_thumbnail/'.$fileName;
    
    	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/filim_thumbnail/photo/'.$fileName;
    	Yii::import("ext.EPhpThumb.EPhpThumb");
    
    	$thumb=new EPhpThumb();
    	$thumb->init(); //this is needed
    	//chain functions
    	$thumb->create($imagename)->resize(100,100)->save($imagename_thumb);
    
    	echo $return; // it's array
    }
     public function actionUploadPromotionThumbnail($folder = null) {
    	
    	Yii::import("ext.EAjaxUpload.qqFileUploader");
    
    	$field_id = "";
    	if(isset($_GET['field_id']))
    	{
    		$field_id = Yii::app()->request->getParam('field_id');
    	}
    
    
    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
    	// make the directory to store the pic:
    	if (!is_dir($folder)) {
    		mkdir($folder, 0777, TRUE);
    	}
    	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...
    	$sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes
    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
    	$result = $uploader->handleUpload($folder);
    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
    	$result['field_id'] = $field_id;
    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    
    	$fileName = $result['filename']; //GETTING FILE NAME
    	 
    
    	$imagename	=	Yii::app()->basePath.'/../uploads/promotions/thumbnail/'.$fileName;
    
    	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/promotions/thumbnail/photo/'.$fileName;
    	Yii::import("ext.EPhpThumb.EPhpThumb");
    
    	$thumb=new EPhpThumb();
    	$thumb->init(); //this is needed
    	//chain functions
    	$thumb->create($imagename)->resize(100,100)->save($imagename_thumb);
    
    	echo $return; // it's array
    }
    
    public function actionUploadVenueMap($folder = null) {
    	
    	Yii::import("ext.EAjaxUpload.qqFileUploader");
    
    	$field_id = "";
    	if(isset($_GET['field_id']))
    	{
    		$field_id = Yii::app()->request->getParam('field_id');
    	}
    
    
    	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
    	// make the directory to store the pic:
    	if (!is_dir($folder)) {
    		mkdir($folder, 0777, TRUE);
    	}
    	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...
    	$sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes
    	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
    	$result = $uploader->handleUpload($folder);
    	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
    	$result['field_id'] = $field_id;
    	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    
    	$fileName = $result['filename']; //GETTING FILE NAME
    	 
    
    	$imagename	=	Yii::app()->basePath.'/../uploads/eventvenue/'.$fileName;
    
    	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/eventvenue/photo/'.$fileName;
    	Yii::import("ext.EPhpThumb.EPhpThumb");
    
    	$thumb=new EPhpThumb();
    	$thumb->init(); //this is needed
    	//chain functions
    	$thumb->create($imagename)->resize(100,100)->save($imagename_thumb);
    
    	echo $return; // it's array
    }
    
   
    
   
    public function CropImage1($folder, $fileName, $width = 1600, $height = 400) {
     //$arr_folder_name = explode("/",$folder); 
     //$folder_name = $arr_folder_name[1];
   //      //$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
      //$imageCropParams = array(array(50, 50), array(100, 100), array(100, 150), array(200, 150), array(200, 200), array(260, 125), array(800, 500), array(150, 128));
      
            $imagefile = getimagesize($folder . $fileName);
    
                    if (is_array($imagefile)) {
                        
                            //$width = $eachImageCropParam[0];
                            //$height = $eachImageCropParam[1];
                            $thumb = Yii::app()->phpThumb->create($folder . '/' . $fileName);
                            $thumb->resize($width, $height);
                            $thumb->save($folder."/".$fileName);
                        
                    }
    }
    
    
    
    public function ciphertext( $string, $action) {
        $file = fopen("en_ticket.txt", "r");  
        $array_encryption = explode("\n", file_get_contents('en_ticket.txt'));
        $secret_key = $array_encryption[0];
        $secret_iv = $array_encryption[1];
        $output = false;
        $encrypt_method = "AES-256-CBC";
        $key = hash( 'sha256', $secret_key );
        $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );

        if( $action == 'e' ) {
            $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
        }
        else if( $action == 'd' ){
            $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
        }

        return $output;
    }

    public function Writelog($message) {
        $log = new Log;
        $log->user_id = Yii::app()->user->id;
        date_default_timezone_set("Asia/Dubai");
        $log->date_time = date('Y-m-d h:i:s');
        $log->message = $message;
        $log->save(false);
    }

    public function  generateWords( $number ){
        $currency_array = explode('.', (string) $number );
        $currencyName = ucfirst($this->widget('ext.NumtoWord.NumtoWord', array('num' =>(int) $currency_array[0]))->result);
        if( (int) $currency_array[1] > 0 ){
            $currencyName .= ' and '.ucfirst($this->widget('ext.NumtoWord.NumtoWord', array('num' => (int) $currency_array[1]))->result);
            $currencyName .= ' fils';
        }
        $currencyName.=' only';
        
        $result ='';
        foreach( explode(' ', $currencyName) as $each ) {
            $result .= ' '.ucfirst($each);
        }
        return $result;
    }
    
  
}