<?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', 'Forgotpassword', 'Recover'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'calender', 'allocatematerial', 'getAllocatedProducts', 'getAllocatedFiles', 'getAllocatedCustomers', 'UploadEmployeecsv',
                    'Upload', 'UploadProfilePhoto', 'UploadDocuments', 'UploadCustomerDocuments', 'MaterialAllocation', 'UploadInventoryFile', 'ciphertext',
                    'UploadDocument', 'UploadExpense', 'decimaltimeHours', 'UploadCategoryImage', 'UploadExes'
                ),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function filters() {

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

    public function getHttp_token() {
        return "manu123";
    }

    public function beforeAction($action) {
        if (isset(Yii::app()->user->company_db_name) && Yii::app()->user->company_db_name != "") {
            $company_db_name = Yii::app()->user->company_db_name;
            Yii::app()->db->setActive(false);
            Yii::app()->db->connectionString = 'mysql:host=localhost;dbname=' . $company_db_name;
            Yii::app()->db->tablePrefix = 'crm_';
            Yii::app()->db->setActive(true);
        }
        if (Yii::app()->request->isAjaxRequest)
            $this->layout = false;
        return parent::beforeAction($action);
    }

    /*public function ChangeDB() {
        //code added by nisha on 01-06-2023
//        $database = "blskysoftware_pos_dehnee";
        //    $database = "erpbluesky_erp_starco";
//        $database = "erpbluesky_erp_qumash";
        //$database = "blskymine_crm_school";
        Yii::app()->db->setActive(false);
        Yii::app()->db->connectionString = 'mysql:host=localhost;dbname=' . $database;
        Yii::app()->db->tablePrefix = 'erp_';
        Yii::app()->db->setActive(true);
        date_default_timezone_set("Asia/Dubai");
//        header('Content-type: application/json');
    }*/

    /**

     * Displays the login page

     */
    public function actionLogin() {

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

        if (!Yii::app()->request->isAjaxRequest)
            $this->layout = "login";

        $model = new LoginForm;

        // ajax validation
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input
        if (isset($_POST['LoginForm'])) {

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

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

                if (!Yii::app()->request->isAjaxRequest) {
                    $this->redirect(array('expense/index'));
                } else {
                    echo CJSON::encode(array('status' => 'success'));
                }

            } else {

                if (!Yii::app()->request->isAjaxRequest)
                    $this->redirect(array('site/login'));
                else
                    echo CJSON::encode(array('status' => 'error'));
            }

        } else {

            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('expense/index'));
        else
            echo CJSON::encode(array('status' => 'success'));
    }
}


    /**

     * Logs out the current user and redirect to homepage.

     */
    public function actionLogout() {

        Yii::app()->user->logout();

        $this->redirect(Yii::app()->homeUrl);
    }

    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!");
        }
    }

    /**

     * This is the action to handle external exceptions.

     */
    public function actionError() {

        if ($error = Yii::app()->errorHandler->error) {

            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    function CropIfImage($folder, $fileName, $width = 100, $height = 100, $frm = '') {

        //$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));

        if ($frm = 'single') {
            $imageCropParams = array(array($width, $height));
        } else {
            $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)) {

            foreach ($imageCropParams as $eachImageCropParam) {

                $width = $eachImageCropParam[0];

                $height = $eachImageCropParam[1];

                $thumb = Yii::app()->phpThumb->create($folder . '/' . $fileName);

                $thumb->resize($width, $height);

                if ($frm = 'single') {
                    $thumb->save($folder . '/' . $fileName);
                } else {
                    $thumb->save($folder . '/' . $width . $height . '_' . $fileName);
                }
            }
        }
    }

    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 = 2 * 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->CropIfImage($folder, $fileName, 100, 100);

        echo $return; // it's array
    }

    public function downloadFile($file, $folder) {

//die("here");

        $filename = Yii::app()->getBaseUrl(true) . $folder . $file;

//$file_url = 'http://www.myremoteserver.com/' . $file_name;

        header('Content-Type: application/octet-stream');

        header("Content-Transfer-Encoding: Binary");

        header("Content-disposition: attachment; filename=\"" . $file . "\"");

        readfile($filename);
    }

    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) {



        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","pdf"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $allowedExtensions = array("png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "xls", "xlsx");

        $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);
        echo $return; // it's array



        /* $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/documents/'.$fileName;



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

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



          $thumb=new EPhpThumb();

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

          //chain functions

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



          echo $return; // it's array */
    }

    /*     * ***************************** Code added by Mereena on 28/11/2017 ****************************** */

    public function actionMaterialAllocation() {
        $id = Yii::app()->request->getParam('id');
        $modelName = Yii::app()->request->getParam('modelName');

        $model = new $modelName();
        $model = $model->findByPk($id);
        $modelNameItems = $model->items;
        $modelAllocate = new AllocatedMaterial();

        $modelAllocate->deleteAll('file_id=:file_id', array(':file_id' => $model->file_id));
        $jsonData['shoratage'] = "";
        $itemsAllocated = 0;

        foreach ($modelNameItems as $eachModel) {

            if ($eachModel->product->inventory_item_type == 1) {

                $indirect_model = new InventoryIndirectTransferItem();
                $available_qty = $indirect_model->with('parent', 'unitdetails')->find(array('select' => '(SUM(transfer_qty-damaged_qty-transferred_qty)) * unitdetails.factor AS available_qty', 'condition' => 'parent.is_complete!="Y" AND t.item_id="' . $eachModel->product_id . '"', 'group' => 't.item_id'))->available_qty;
                $indirectQuantity = $indirect_model->with('parent', 'unitdetails')->find(array('select' => '(SUM(t.damaged_qty)) * unitdetails.factor AS damaged_qty', 'condition' => 't.item_id="' . $eachModel->product_id . '" AND t.damaged_qty !="0"', 'group' => 't.item_id'))->damaged_qty;
                $damaged_model = new DamagedStoreDetails();
                $damageQuantity = $damaged_model->with('unitdetails')->find(array('select' => '(SUM(t.quantity)) * unitdetails.factor AS quantity', 'condition' => 't.product_id="' . $eachModel->product_id . '"', 'group' => 't.product_id'))->quantity;
                $creditnote_model = new CreditnoteItem();
                $creditQuantity = $creditnote_model->with('parent', 'orderunit')->find(array('select' => '(SUM(t.returned_quantity)) * orderunit.factor AS returned_quantity', 'condition' => 'parent.sales_return="DA" AND t.product_id="' . $eachModel->product_id . '" AND t.returned_quantity !="0"', 'group' => 't.product_id'))->returned_quantity;
                $damaged_qty = (float) $indirectQuantity + (float) $creditQuantity + (float) $damageQuantity;

                $quantity = (float) $eachModel->product->totalQuantity + (float) $damaged_qty + (float) $available_qty;

                $shoratge = (float) $quantity - (float) $eachModel->product->total_allocated_quantity - (float) $eachModel->quantity;
                if ($shoratge <= 0)
                    $jsonData['shoratage'] .= "Item " . $eachModel->product->part_number . " need extra " . abs($shoratge) . "No.s<br/>";
                else
                    $shoratge = 0;

                $modelAllocatedMaterial = new AllocatedMaterial();
                $arr_allocated_material_details = $modelAllocatedMaterial->find(array('condition' => 'file_id=' . $model->file_id . ' AND product_id=' . $eachModel->product_id));

                if (!empty($arr_allocated_material_details))
                    $modelAllocatedMaterial = $arr_allocated_material_details;

                $modelWarehouse = new MasInventoryWarehouse();
                $arr_default_ware_house = $modelWarehouse->getDefaultWarehouse();
                $default_ware_house_id = 0;

                if (count($arr_default_ware_house) > 0)
                    $default_ware_house_id = (int) $arr_default_ware_house->id;

                $modelAllocatedMaterial->product_id = $eachModel->product_id;
                $modelAllocatedMaterial->file_id = $model->file_id;
                $modelAllocatedMaterial->warehouse_id = $default_ware_house_id;
                $modelAllocatedMaterial->quantity = ( (float) $eachModel->quantity + $shoratge );
                $modelAllocatedMaterial->allocation_date = date('Y-m-d');
                $modelAllocatedMaterial->created_by = Yii::app()->user->id;
                $modelAllocatedMaterial->created_datetime = date('Y-m-d h:i:s');

                if ($modelName == "Quotes") {
                    $end_date = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") + 14, date("Y")));
                    if ($model->qtn_validity > $end_date) {
                        $modelAllocatedMaterial->allocation_end_date = $end_date;
                    } else {
                        $modelAllocatedMaterial->allocation_end_date = $model->qtn_validity;
                    }
                    $modelAllocatedMaterial->allocated_from = "Q";
                } else if ($modelName == "Order") {
                    $modelAllocatedMaterial->allocation_end_date = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") + 14, date("Y") + 10));
                    $modelAllocatedMaterial->allocated_from = "O";
                }

                if ($modelAllocatedMaterial->quantity > 0) {
                    $modelAllocatedMaterial->save(false);
                    $itemsAllocated++;
                }
            }
        }

        $modelName = new $modelName();
        if ($itemsAllocated > 0)
            $modelName->updateByPk($id, array('materials_allocated' => "Y"));
        $jsonData['no_of_items_allocated'] = $itemsAllocated;
        echo CJSON::encode($jsonData);
    }

    /*     * *********************************** End ********************************************** */

    /*     * ************************ START Upload stock in to Inventory ********************************* */

    public function actionUploadInventoryFile($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("csv"); //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->CropIfImage($folder, $fileName, 100, 100);

        echo $return; // it's array
    }

    /*     * ************************ END Upload stock in to Inventory ********************************* */

    public function writeStockledger($arr_data, $transacion_type, $type) {
        $stockLedger = new StockLedger;
        // $stockLedger->header_id = $arr_data['header_id'];
        //$stockLedger->header_item_id = $arr_data['header_item_id'];
        $stockLedger->transaction_date = $arr_data['transaction_date'];
        $stockLedger->transaction_type = $arr_data['transaction_type'];
        $stockLedger->product_id = $arr_data['product_id'];
        $stockLedger->quantity = ( $type == 'OUT' ) ? -1 * $arr_data['quantity'] : $arr_data['quantity'];
        $stockLedger->unit_id = $arr_data['unit_id'];
        $stockLedger->product_location_id = $arr_data['product_location_id'];
        $stockLedger->warehouse_id = $arr_data['warehouse_id'];
        $stockLedger->rack_id = $arr_data['rack_id'];
        $stockLedger->bin_id = $arr_data['bin_id'];
        $stockLedger->created_by = $arr_data['created_by'];
        $stockLedger->created_date = $arr_data['created_date'];
        $stockLedger->cost_price = $arr_data['cost_price'];
        $stockLedger->save(false);
    }

    function ciphertext($string, $action) {
        $file = fopen("en_encdec_hr.txt", "r");
        $array_encryption = explode("\n", file_get_contents('en_encdec_hr.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' && $string != '') {
            $string = strtoupper($string);
            $output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
        } else if ($action == 'd' && $string != '') {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }
        return $output;
    }

    public function actionUploadEmployeecsv($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("csv"); //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->CropIfImage($folder, $fileName, 100, 100);

        echo $return; // it's array
    }

    public function actionUploadDocument($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 = 2 * 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
        echo $return; // it's array
    }

    public function actionUploadExpense($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("csv", "zip", "png", "txt", "pdf", "doc", "docx", "jpg", "jpeg", "gif"); //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->CropIfImage($folder, $fileName, 100, 100);

        echo $return; // it's array
    }

    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 actionUploadCustomerDocuments($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", "png", "doc", "docx", "xls", "xlsx", "pdf", "bmp", "jpeg"); //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);
        echo $return; // it's array
    }

    public function actionUploadCategoryImage($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", "png", "bmp", "jpeg"); //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);
        $image_height = 50;
        $image_width = 50;
        $frm = 'single';
        $this->CropIfImage($folder, $result['filename'], $image_width, $image_height, $frm);
        echo $return; // it's array
    }

    function decimaltimeHours($time) {
        $hms = explode(":", $time);
        return round($hms[0] + ($hms[1] / 60) + ($hms[2] / 3600), 2);
    }

    public function actionUploadExes($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("exe");

        $sizeLimit = 50 * 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);
        echo $return; // it's array
    }

}
