<?php
 class GmcgoodsinuploadController 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', 'UploadGMCGoodsIn', 'DownloadGmcGoodsinFormat','UploadDocuments','SaveGMCGoodsInUpload'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    public function actionUploadGMCGoodsIn() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $model = new GmcGoodsinUploads();
            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 actionDownloadGmcGoodsinFormat(){
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $file = fopen("upload/test.csv", "w");
            $j=0;
            $list[$j++] ='GMC Code!GoodsIn Start Month!GoodsIn Start Year!GoodsIn End Month !GoodsIn End Year !Backlog Start Month!Backlog Start Year!Backlog End Month!Backlog End Year';//Type(CM/CM-1/CM-2/CM-3/CM-4)
            $arr_months=Order::getmonths();
            $model_inventory =Inventory::model()->findAll(array('condition'=>'t.is_active="Y"'));
            foreach($model_inventory as $row){
                $list[$j++] =$row['gmc_code'].'!'.$arr_months[$row['goods_in_month']].'!'.$row['goods_in_year'].'!'.$arr_months[$row['goods_in_end_month']].'!'.$row['goods_in_end_year'].'!'.$arr_months[$row['backlog_month']].'!'.$row['backlog_year'].'!'.$arr_months[$row['backlog_end_month']].'!'.$row['backlog_end_year'];
            }
            $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="GoodsIn_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        }else{
            throw new CHttpException(404, 'Page not found.');
        }
    }
    public function actionSaveGMCGoodsInUpload(){
        
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $model = new GmcGoodsinUploads();$other=array();
            if (isset($_POST['GmcGoodsinUploads'])) {
                if ((int) @$_POST['GmcGoodsinUploads']['id'] > 0) {
                    $id = (int) @$_POST['GmcGoodsinUploads']['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['GmcGoodsinUploads'];
                $model->uploaded_date = date('Y-m-d');
                $file= $_POST['GmcGoodsinUploads']['file_name'];
                $model->file_name =$file;
                $valid= $model->validate();
                $i=0;$arr_products=[];$n=1;
                if($file!=''){
                    if (($handle = fopen("upload/gmcgoodsin/" . $file, "r")) !== FALSE) {
                    
                        while (($row = fgetcsv($handle)) !== FALSE) {
                            
                            if ($n > 1) {
                                $gmc_code= trim($row[0]); //gmc
                                $month= trim($row[1]); //goodsin start month
                                $year= trim($row[2]); //goodsin start year
                                //$supply_goodsin= trim($row[3]); //type
                                $gemonth= trim($row[3]); //goodsin end month
                                $geyear= trim($row[4]); //goodsin end year
                                $bmonth= trim($row[5]); 
                                $byear= trim($row[6]);
                                //$supply_backlog= trim($row[6]); //type
                                $bemonth= trim($row[7]); 
                                $beyear= trim($row[8]);
                                $mod_inv = Inventory::model()->find(array('condition'=>'gmc_code="'.$gmc_code.'"'));
                                if(!empty($mod_inv)){
                                    $modelItems[$i] = Inventory::model()->findByPK((int)$mod_inv->id);
                                    $modelItems[$i]->goods_in_month =Order::getmonthNo($month);
                                    $modelItems[$i]->goods_in_year = $year;
                                    $modelItems[$i]->goods_in_end_month = Order::getmonthNo($gemonth);
                                    $modelItems[$i]->goods_in_end_year = $geyear;
                                    //$modelItems[$i]->supply_goodsin = $supply_goodsin;
                                    $modelItems[$i]->backlog_month =Order::getmonthNo($bmonth);
                                    $modelItems[$i]->backlog_year = $byear;
                                    $modelItems[$i]->backlog_end_month = Order::getmonthNo($bemonth);
                                    $modelItems[$i]->backlog_end_year = $beyear;
                                    //$modelItems[$i]->supply_backlog = $supply_backlog;
                                    $modelItems[$i]->updated_by = Yii::app()->user->id;
                                    $modelItems[$i]->updated_date_time =date('Y-m-d H:i:s');
                                    $valid = $modelItems[$i]->validate()&& $valid;
                                    $i++;
                                    if (in_array($gmc_code,$arr_products)) {
                                        $other[] = $gmc_code. ' GMC Repeated ';
                                        $valid = false;
                                    }else{
                                        $arr_products[]=$gmc_code;
                                    }
                                }else{
                                    $other[] = 'GMC with code '.$gmc_code.' not exits';
                                    $valid = false;
                                }
                            }
                            $n++;
                            
                        }
                        fclose($handle);
                    }
                }else{
                    $other[]='File Not Uploaded';
                    $valid = false;
                }
                if ($valid) {
                    //echo '<pre>';print_r($modelItems);
                    $model->save();
                    if(!empty($modelItems)){
                        foreach($modelItems as $each){
                            $each->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['GmcGoodsinUploads'];
                    $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.');
        }
        
    }
}