<?php
 class UploadstaticdataController extends Controller {
    
    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('Create','SaveStaticData','UploadDocuments','CreateInventoryGoodsIn','SaveStaticOther'),
                '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 actionCreate() {
       
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $model = new Order();
            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('create', array('model' => $model), false, false);
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionSaveStaticData(){
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $file= $_POST['Order']['file_name'];
            $distributer_id=$_POST['Order']['distributer_id'];
            $distributer_model = Distributers::model()->with('region_det')->findByPk($distributer_id);
            $region_id =(int)$distributer_model->region_id;     
            $arr_dis=[];$arr_products=[];
            $model = new Order();$other=array();
            if (isset($_POST['Order'])) {
                $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->region_id = $region_id;
                $model->attributes = $_POST['Order'];
                $model->order_date = date('Y-m-d');
                $model->is_locked = 'Y';
                $file= $_POST['Order']['file_name'];
                $model->file_name =$file;
                $valid= $model->validate();
            }
            if($file!=''){
                if (($handle = fopen("upload/uploadstaticdata/".$file, "r")) !== FALSE) {
                    $n = 1;
                    $arr_months=Order::getmonths();
                    $mod_his = Order::model()->find(array('condition'=>'distributer_id='.(int)$_POST['Order']['distributer_id'].' and month = "'.$_POST['Order']['month'].'" and year = "'.$_POST['Order']['year'].'"'));
                    if(!empty($mod_his)){
                        $other[]='Already added Data';
                        $valid = false;
                    }
                    while (($row = fgetcsv($handle)) !== FALSE) {
                        if($n == 1){
                            //$arr_dis['']
                        }
                        if ($n > 1) {
                            $gmc_code= trim($row[0]); //gmc
                            $quantity_ordered=(int)$row[1];
                            $quantity_confirmed=(int)$row[2];
                            $quantity_shipped=(int)$row[3];
                            
                            if($quantity_ordered<0){
                                $other[] = 'GMC with code '.$gmc_code.' and model '.$model_no.' entered negative qty '.$quantity_ordered;
                                $valid = false;
                            }else{
                                //AND (is_active="Y" OR (is_active="D" AND ((discontinuing_month<='.$_POST['Order']['month'].' AND discontinuing_year='.$_POST['Order']['year'].') OR discontinuing_year<'.$_POST['Order']['year'].') 
                                $cnd = 'gmc_code="'.$gmc_code.'" AND (is_active="Y" OR (is_active="D" AND ((discontinuing_month>='.(int)$_POST['Order']['month'].' AND discontinuing_year='.(int)$_POST['Order']['year'].') OR discontinuing_year>'.(int)$_POST['Order']['year'].')))'; 
                                $mod_inv = Inventory::model()->find(array('condition'=>$cnd));
                                $price_ordered=0;
                                if(!empty($mod_inv)){
                                    $category_id=$mod_inv->product_category_id;
                                    $model_no=$mod_inv->model_no;
                                    $base_code =$mod_inv->base_code;
                                    /*region value*/
                                    $price_date = (int)$_POST['Order']['year'].'-'.(int)$_POST['Order']['month'].'-'.'01';
                                    $price_cnd = 'product_id='.(int)$mod_inv->id.' AND region_id='.(int)$region_id.' AND from_date <="'.$price_date.'" AND to_date >="'.$price_date.'"';
                                    $mod_inv_price=InventoryPrice::model()->find(array('condition'=>$price_cnd));
                                    $price_ordered=(float)$mod_inv_price->price;
                                    /*region value*/
                                
                                    $modelItems[$i] = new OrderDetails();
                                    $modelItems[$i]->order_id= 0 ;
                                    $modelItems[$i]->category_id= (int)$category_id ;
                                    $modelItems[$i]->product_id= $mod_inv->id ;
                                    $modelItems[$i]->model = $model_no;
                                    $modelItems[$i]->base_code = $base_code ;
                                    $modelItems[$i]->price = $price_ordered;
                                    $modelItems[$i]->quantity_ordered = $quantity_ordered;
                                    $modelItems[$i]->quantity_confirmed = $quantity_confirmed;
                                    $modelItems[$i]->quantity_shipped = $quantity_shipped;
                                    $modelItems[$i]->region_id = (int)$region_id;
                                    $modelItems[$i]->order_date =$price_date;
                                    if($distributer_model->region_det->currency_type == 'USD'){
                                        $modelItems[$i]->exchange_rate = 1;
                                    }else{
                                        $mod_settings = MasSettings::model()->find();
                                        $currency_rate = $mod_settings->currency_rate;
                                        $modelItems[$i]->exchange_rate = (1/$currency_rate);
                                    }
                                    $modelItems[$i]->currency_type = $distributer_model->region_det->currency_type;
                                    $modelItems[$i]->created_by = Yii::app()->user->id;
                                    $modelItems[$i]->created_date_time =date('Y-m-d H:i:s');
                                    $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($mod_inv->id,$arr_products)) {
                                        $other[] = $gmc_code. ' GMC Repeated ';
                                        $valid = false;
                                    }else{
                                        $arr_products[]=$mod_inv->id;
                                    }
                                }
                                else{
                                    error_log('GMC '.$gmc_code.' and model '.$model_no.' not exits in static file');
                                    /*$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.' and model '.$model_no.' Discontinued';
                                    }else{
                                        $other[] = 'GMC with code '.$gmc_code.' and model '.$model_no.' not exits';
                                    }
                                    $valid = false;*/
                                }
                            }
                        }
                        $n++;
                    }
                    fclose($handle);
                }else{
                    $other[]='File Not Uploaded';
                $valid = false;
                }
            }else{
                $other[]='File Not Uploaded';
                $valid = false;
            }
            if ($valid) {
                
                $model->save();
                if(!empty($modelItems)){
                    foreach ($modelItems as $eachModel) {
                        $eachModel->order_id = $model->id;
                        $eachModel->save(false);
                    }
                }
                
                
                $jsonData['status'] = 'success';
                $jsonData['id'] = $model->id;
                echo CJSON::encode($jsonData);
            } else{
                $error1 = $error2 = array();
                $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 data";
                $error = CJSON::encode(array_merge_recursive($error1, $error2,$other));
                if ($error != '[]')
                    echo $error;
            }
            
        }else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
    public function actionCreateInventoryGoodsIn() {
       
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $model = new InventoryUploads();
            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('create_other', array('model' => $model), false, false);
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
    public function actionSaveStaticOther(){
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $file= $_POST['InventoryUploads']['file_name'];
            $arr_dis=[];$arr_products=[];$other=array();
            if (isset($_POST['InventoryUploads'])) {
                $model = new InventoryUploads();
                $model->type ='Inventory';
                $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['InventoryUploads'];
                $model->uploaded_date = date('Y-m-d');
                $model->is_locked = 'Y';
                $model->file_name =$file;
                $valid= $model->validate();
                 //goodsIn
                $modelGoodsIn = new InventoryUploads();
                $modelGoodsIn->created_by = Yii::app()->user->id;
                $modelGoodsIn->created_date_time = date('Y-m-d H:i:s');
                $modelGoodsIn->type ='GoodsIn';
                $modelGoodsIn->updated_by = Yii::app()->user->id;
                $modelGoodsIn->updated_date_time = date('Y-m-d H:i:s');
                $modelGoodsIn->attributes = $_POST['InventoryUploads'];
                $modelGoodsIn->uploaded_date = date('Y-m-d');
                $modelGoodsIn->is_locked = 'Y';
                $modelGoodsIn->file_name = $file;
                $valid = $modelGoodsIn->validate()&&$valid;
                if($file!=''){
                    if (($handle = fopen("upload/uploadstaticother/".$file, "r")) !== FALSE) {
                        $n = 1;
                        $arr_months=Order::getmonths();
                        $mod_his = InventoryUploads::model()->find(array('condition'=>'month = "'.$_POST['InventoryUploads']['month'].'" and year = "'.$_POST['InventoryUploads']['year'].'"'));
                        if(!empty($mod_his)){
                            $other[]='Already added Data';
                            $valid = false;
                        }
                        while (($row = fgetcsv($handle)) !== FALSE) {
                            if ($n > 1) {
                                $gmc_code= trim($row[0]); //gmc
                                $quantity_inventory=(int)$row[1];
                                $quantity_goodsIn=(int)$row[2];
                                
                                if($quantity_inventory<0||$quantity_inventory<0){
                                    $other[] = 'GMC with code '.$gmc_code.' and model '.$model_no.' entered negative qty ';
                                    $valid = false;
                                }else{
                                    //AND (is_active="Y" OR (is_active="D" AND ((discontinuing_month<='.$_POST['Order']['month'].' AND discontinuing_year='.$_POST['Order']['year'].') OR discontinuing_year<'.$_POST['Order']['year'].') 
                                    $cnd = 'gmc_code="'.$gmc_code.'" AND (is_active="Y" OR (is_active="D" AND ((discontinuing_month>='.(int)$_POST['Order']['month'].' AND discontinuing_year='.(int)$_POST['Order']['year'].') OR discontinuing_year>'.(int)$_POST['Order']['year'].')))'; 
                                    $mod_inv = Inventory::model()->find(array('condition'=>$cnd));
                                    $price_ordered=0;
                                    if(!empty($mod_inv)){
                                        $category_id=$mod_inv->product_category_id;
                                        $model_no=$mod_inv->model_no;
                                        $base_code =$mod_inv->base_code;
                                        
                                        $modelItems[$i] = new InventoryUploadDetails();
                                        $modelItems[$i]->inventory_upload_id = 0;
                                        $modelItems[$i]->category_id = $category_id;
                                        $modelItems[$i]->product_id = $mod_inv->id;
                                        $modelItems[$i]->inventory_quantity = $quantity_inventory;
                                        $modelItems[$i]->goods_in_qty = 0;
                                        $modelItems[$i]->total_quantity = $quantity_inventory;
                                        $modelItems[$i]->month_taken = 0;
                                        $modelItems[$i]->year_taken = '2022';
                                        $modelItems[$i]->created_by = Yii::app()->user->id;
                                        $modelItems[$i]->created_date_time = date('Y-m-d H:i:s');
                                        $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;
                                        $modelGoodsItems[$i] = new InventoryUploadDetails();
                                        $modelGoodsItems[$i]->inventory_upload_id = 0;
                                        $modelGoodsItems[$i]->category_id = $category_id;
                                        $modelGoodsItems[$i]->product_id = $mod_inv->id;
                                        $modelGoodsItems[$i]->inventory_quantity = 0;
                                        $modelGoodsItems[$i]->goods_in_qty = $quantity_goodsIn;
                                        $modelGoodsItems[$i]->total_quantity = $quantity_goodsIn;
                                        $modelGoodsItems[$i]->month_taken = 0;
                                        $modelGoodsItems[$i]->year_taken = '2022';
                                        $modelGoodsItems[$i]->created_by = Yii::app()->user->id;
                                        $modelGoodsItems[$i]->created_date_time = date('Y-m-d H:i:s');
                                        $modelGoodsItems[$i]->updated_by = Yii::app()->user->id;
                                        $modelGoodsItems[$i]->updated_date_time = date('Y-m-d H:i:s');
                                        $valid = $modelGoodsItems[$i]->validate() && $valid;
                                        $i++;
                                    }
                                    else{
                                        /*if($quantity_inventory>0 ||$quantity_goodsIn>0){
                                            $other[] = 'GMC with code '.$gmc_code.' and model '.$model_no.' not exits';
                                             $valid = false;
                                        }else{
                                            error_log('GMC '.$gmc_code.' and model '.$model_no.' not exits in static inventory file');
                                        }*/
                                    }
                                }
                            }
                            $n++;
                        }
                        fclose($handle);
                    }else{
                        $other[]='File Not Uploaded';
                        $valid = false;
                    }
                }else{
                    $other[]='File Not Uploaded';
                    $valid = false;
                }
                
                
                if ($valid) {
                    $model->save();
                    if (!empty($modelItems)) {
                        foreach ($modelItems as $each) {
                            $each->inventory_upload_id = $model->id;
                            $each->save(false);
                        }
                    }
                    $modelGoodsIn->save();
                    if (!empty($modelGoodsItems)) {
                        foreach ($modelGoodsItems as $each) {
                            $each->inventory_upload_id = $modelGoodsIn->id;
                            $each->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['InventoryUploads'];
                    $jsonData['id'] = $model->id;
                    echo CJSON::encode($jsonData);
                } else {
                    $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                    $error2 = json_decode(CActiveForm::validate($modelGoodsIn, '', false), true);
                    if (!empty($modelItems)) {
                        $error3 = json_decode(CActiveForm::validateTabular($modelItems, '', false), true);
                    } else {
                        $error3[] = "Please add atleast one line item";
                    }
                    if (!empty($modelGoodsItems)) {
                        $error4 = json_decode(CActiveForm::validateTabular($modelGoodsItems, '', false), true);
                    } else {
                        $error4[] = "Please add atleast one line item";
                    }
                    $error = CJSON::encode(array_merge_recursive($error1, $error2,$error3,$error4, $other));
                    if ($error != '[]')
                        echo $error;
                }
            }
        }
    }
}