<?php
 class GmcpriceuploadController extends Controller {
    
    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 accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('Index', 'UploadGMCPrice','UploadDocuments','DownloadpriceFormat','SavePriceUpload','TestUpdatePrice'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    public function actionUploadGMCPrice() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $model = new GmcPriceUploads();
            Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, 'jquery-2.1.4.js' => false);
            $this->render('upload_form', array('model' => $model), false, false);
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
    public function actionDownloadpriceFormat(){
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $id = Yii::app()->request->getParam('id');
            $product_category_id = Yii::app()->request->getParam('product_category_id');
            if((int)$product_category_id>0){
                
            }
            $model_inventory = Inventory::model()->with('category_det')->findAll(array('order'=>'category_det.sort_order asc'));
            $file = fopen("upload/test.csv", "w");
            $j=0;
            $list[$j++] ='PRICE!';
            $firstrow ='GMC Code';
            $modMasRegion = MasRegion::model()->findAll(array('order'=>'id asc'));
            foreach($modMasRegion as $eachcat){
                $firstrow .='!'.$eachcat->region_name ;
            }
            $list[$j++] =$firstrow.'!'.'Model No'.'!'.'Category';
            foreach ($model_inventory as $i => $row) {
                $inv_row= $row['gmc_code'] ;
                foreach($modMasRegion as $eachreg){
                    $price = InventoryPrice::model()->find(array('condition' => 'product_id=' . (int) $row['id'].' AND region_id='.(int)$eachreg['id'],'order'=>'id DESC','limit'=>'1'))->price;
                    $inv_row .='!'.$price ;
                }
                $inv_row .='!'.$row['model_no'].'!'.$row['category_det']['product_category'];
                $list[$j++] =$inv_row;
            }
            $j++;
            foreach ($list as $line) {
                fputcsv($file, explode('!', $line));
            }
            fclose($file);
            $filename = 'upload/test.csv';
            header("Content-Type: application/csv");
            header('Content-Disposition:attachment; filename="GMCPrice_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        }else{
            throw new CHttpException(404, 'Page not found.');
        }
    }
     public function actionSavePriceUpload() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new GmcPriceUploads();
            $other = array();
            if (isset($_POST['GmcPriceUploads'])) {
                if ((int) @$_POST['GmcPriceUploads']['id'] > 0) {
                    $id = (int) @$_POST['GmcPriceUploads']['id'];
                    $model = $model->findByPk($id);
                } else {
                    $model->created_by = Yii::app()->user->id;
                    $model->created_date_time = date('Y-m-d H:i:s');
                }
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d H:i:s');
                $model->attributes = $_POST['GmcPriceUploads'];
                $model->upload_date = date('Y-m-d');
                if($_POST['GmcPriceUploads']['from_date']!='01/01/1970' && $_POST['GmcPriceUploads']['from_date'] != '')
                {
                    $model->from_date = str_replace('/', '-', $_POST['GmcPriceUploads']['from_date']);
                    $model->from_date= date("Y-m-d", strtotime($model->from_date));
                }
                $file = $_POST['GmcPriceUploads']['file_name'];
                $model->file_name = $file;
                $valid = $model->validate();
                $i = 0;$j=0;
                $arr_products = [];
                $n = 1;$arr_regions=[];$arr_region_ids=[];$j=0;
                if ($file != '') {
                    if (($handle = fopen("upload/price/" . $file, "r")) !== FALSE) {

                        while (($row = fgetcsv($handle)) !== FALSE) {
                            if ($n == 2) {
                                $row_count = count($row)-2;
                                for ($k = 1; $k < $row_count; $k++) {
                                    $region_name = trim($row[$k], '\'"'); //region_name
                                    $arr_regions[$k] = $region_name;
                                    if ($row[$k] == '') {
                                        $other[] = 'Heading Region Missing';
                                        $valid = false;
                                    }else{
                                        $modMasRegion  = MasRegion::model()->find(array('condition' => 'region_name="' . $region_name . '"'));
                                        if(!empty($modMasRegion)){
                                            $region_id = $modMasRegion->id;
                                            $arr_region_ids[$k] = $region_id;
                                        }else{
                                            $other[] = 'Region '.$region_name.' Not Exists';
                                            $valid = false;
                                        }
                                    }
                                }
                            
                            }
                            if ($n > 2) {
                                $gmc_code = trim($row[0]); //gmc
                                $mod_inv = Inventory::model()->find(array('condition' => 'gmc_code="'.$gmc_code.'"'));//AND is_active="Y"
                                if (!empty($mod_inv)) {
                                    for ($i = 1; $i < $row_count; $i++) {
                                        $model_history = InventoryPrice::model()->find(array('condition'=>'region_id ='.(int)$arr_region_ids[$i].' AND product_id ='.(int)$mod_inv['id'],'order'=>'id DESC'));
                                        $new_from_date=$model->from_date;
                                        $modelItems[$j] = new InventoryPrice;
                                        $modelItems[$j]->created_by = Yii::app()->user->id;
                                        $modelItems[$j]->created_date_time = date("Y-m-d H:i:s");
                                        $modelItems[$j]->region_id = $arr_region_ids[$i];
                                        $modelItems[$j]->price = (float)$row[$i];
                                        $modelItems[$j]->product_id = $mod_inv['id'];
                                        $modelItems[$j]->from_date = $new_from_date;
                                        $modelItems[$j]->to_date = "2099-12-31";
                                        $valid = $modelItems[$j]->validate() && $valid;
                                        $j++;
                                        if(!empty($model_history)){
                                            $modelItems[$j] =  InventoryPrice::model()->findByPK((int)$model_history->id);
                                            $modelItems[$j]->updated_by = Yii::app()->user->id;
                                            $modelItems[$j]->updated_date_time = date("Y-m-d H:i:s");
                                            $modelItems[$j]->to_date = $new_from_date;
                                            $valid = $modelItems[$j]->validate() && $valid;
                                            $j++;
                                        }
                                    }
                                   
                                } else {
                                    $other[] = 'GMC with code '.$gmc_code.' not exits';
                                    $valid = false;
                                    /*$cnd = 'gmc_code="'.$gmc_code.'" AND is_active="D" '; //
                                    $mod_inv = Inventory::model()->find(array('condition'=>$cnd));
                                    if(!empty($mod_inv)){
                                        $other[] = 'GMC with code '.$gmc_code.' Discontinued';
                                    }else{
                                        
                                    }*/
                                    
                                }
                            }
                            $n++;
                        }
                        fclose($handle);
                    }
                } else {
                    $other[] = 'File Not Uploaded';
                    $valid = false;
                }
                /*echo '<pre>';
                print_r($modelItems);
                exit;*/
                if ($valid) {

                    $model->save();
                    if (!empty($modelItems)) {
                        foreach ($modelItems as $each) {
                            $each->save(false);
                            OrderDetails::model()->updateAll(array('price' => (float)$each['price']),'product_id='.(int)$each['product_id'].' AND region_id='.(int)$each['region_id'].' AND order_date>="'.$each['from_date'].'" AND order_date<"'.$each['to_date'] .'" '  );
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['GmcPriceUploads'];
                    $jsonData['id'] = $model->id;
                    echo CJSON::encode($jsonData);
                } else {
                    $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                    if (!empty($modelItems)) {
                        $error2 = json_decode(CActiveForm::validateTabular($modelItems, '', false), true);
                    } else {
                        $error2[] = "Please add atleast one line item";
                    }
                    $error = CJSON::encode(array_merge_recursive($error1, $error2, $other));
                    if ($error != '[]')
                        echo $error;
                }
            }
        }
        else {
            throw new CHttpException(404, 'Page not found.');
        }
    }
    /*public function actionTestUpdatePrice(){
        $modelItems= InventoryPrice::model()->findALL();
        if (!empty($modelItems)) {
            foreach ($modelItems as $each) {
                OrderDetails::model()->updateAll(array('price' => (float)$each['price']),'product_id='.(int)$each['product_id'].' AND region_id='.(int)$each['region_id'].' AND order_date>="'.$each['from_date'].'" AND order_date<"'.$each['to_date'] .'" '  );
            }
        }
        echo 'success';
    }*/
 }