<?php
 class UploadsalesController 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', 'UploadSalesdocument','GetList', 'DownloadSales','UploadDocuments','SaveSalesUpload','Delete',
                'DownloadUploaded','View','GetviewList','Download'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    public function actionIndex() {
       // if (isset(Yii::app()->user->havePermissionOn['card']) || Yii::app()->user->authorised_user == 1) {
            $this->render('index');
      //  } else {
         //   throw new CHttpException(403, 'access denied.');
       // }
    }
   public function actionGetList() {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $model = new UploadSales();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $year = $_POST['year'];
            $month = $_POST['month'];
            $columns = array(
                // datatable column index  => database column name
                0 => 't.id',
                1 => 'added_date',
                2 => 'month',
                3 => 'year',
                
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = '1=1';
            
            $arr_months=Order::getmonths();
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                $condition .= " and (created_date_time LIKE '%" . $searchString . "%' 
                         OR month LIKE '%" . $searchString . "%' OR year LIKE '%" . $searchString . "%')";
            }
            $count = $model->count(array('condition' => $condition));
            $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
            $recordsTotal = $count;
            $recordsFiltered = $count;
            $data['draw'] = $draw;
            $data['recordsTotal'] = $recordsTotal;
            $data['recordsFiltered'] = $recordsFiltered;
            $rowData = array();
            $m = 1;
            foreach ($model as $row) {
                $div = '';
                
                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["sales_view"])) {
                    $div .= ' <button class="btn btn-primary btn-xs" onclick="viewsales(' . $row[id] . ');" title="View Sales"><i class="fa fa-eye"></i></button>';
                }
                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["sales_download"])) {
                    $div .= '<button type="button"  class="btn btn-primary btn-xs" onclick="downloadsales(' . $row[id] . ');" title="Download"><i class="fa fa-download"></i></button>';
                }
                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["sales_delete"])) {
                    $div .= ' <button type="button"  class="btn btn-primary btn-xs" onclick="deleteSales(' . $row['id'] . ')" title="Delete Sales"><i class="fa fa-trash"></i></button>';
                }


                $rowData[] = array($m,
                    date('d/m/Y',strtotime($row['created_date_time'])),$arr_months[(int)$row['month']],$row['year'],
                    '<div class="btn-wrap text-center">' . $div . '</div>');
    
                $m++;
            }
            $data['data'] = $rowData;
            echo json_encode($data);
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
    public function actionUploadSalesdocument() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $model = new UploadSales();
            $month = (int) Yii::app()->request->getParam('month');
            $year = (int) Yii::app()->request->getParam('year');
            $supply_confirm_id=(int) Yii::app()->request->getParam('supply_confirm_id');
            $model->supply_confirm_id=$supply_confirm_id;
            $model->month=$month;
            $model->year=$year;
            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 actionSaveSalesUpload(){
        
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $model = new UploadSales();$other=array();
            if (isset($_POST['UploadSales'])) {
                if ((int) @$_POST['UploadSales']['id'] > 0) {
                    $id = (int) @$_POST['UploadSales']['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->attributes = $_POST['UploadSales'];
                $file= $_POST['UploadSales']['file_name'];
                $model->file_name =$file;
                $valid= $model->validate();
                $i=0;$groups=[];$n=1;$arr_dis=[];$arr_gmc=[];
                if($file!=''){
                    if (($handle = fopen("upload/sales/" . $file, "r")) !== FALSE) {
                        while (($row = fgetcsv($handle)) !== FALSE) {
                            if ($n > 2) {
                                $gmc_code= trim($row[9]); //gmc
                                $qty= trim($row[16]); //qty
                                $type= trim($row[29]); //type
                                $distributer_code= trim($row[61]); //qty
                                $distributer_model = Distributers::model()->find(array('condition'=>'distributer_name="'.$distributer_code.'" OR alias_name="'.$distributer_code.'"'));
                                $mod_inv = Inventory::model()->find(array('condition'=>'gmc_code="'.$gmc_code.'"'));
                                if((int)$qty>0){//($type=="FO"||$type=="3PO")&& --commented since 19-09-2022 for upload sales of all type
                                    if(empty($distributer_model)||empty($mod_inv)){
                                        if(empty($distributer_model)){
                                            if(!in_array($distributer_code,$arr_dis)){
                                                $arr_dis[] = $distributer_code;
                                            }
                                            $valid = false;
                                        }
                                        if(empty($mod_inv)){
                                            if(!in_array($distributer_code,$arr_gmc)){
                                                $arr_gmc[] = $gmc_code;
                                            }
                                            $valid = false;
                                        }
                                    }else{
                                       /* $model_gmc_exists=OrderDetails::model()->with('parent_det')->find(array('condition'=>'product_id='.(int)$mod_inv['id'].' AND parent_det.month="'.(int)$_POST['UploadSales']['month'].'" AND parent_det.year='.(int)$_POST['UploadSales']['year'].' AND parent_det.distributer_id='.(int)$distributer_model->id));
                                        if(empty($model_gmc_exists)){
                                            $other[] = 'GMC with code '.$gmc_code.' not exists in order uploaded for '.$distributer_code.' for year '.(int)$_POST['UploadSales']['year'].' and month '.(int)$_POST['UploadSales']['month'];
                                            $valid = false;
                                        }else{*/
                                            
                                            $key =$mod_inv->id.'_'.$distributer_model->id;
                                            
                                            if (!array_key_exists($key, $groups)) {
                                                $groups[$key] = array(
                                                    'product_id' => $mod_inv->id,
                                                    'quantity' => $qty,
                                                    'distributer_id' => $distributer_model->id,
                                                    'order_id' => (int)$model_gmc_exists->parent_det->id,
                                                    'order_detail_id' => (int)$model_gmc_exists->id,
                                                );
                                            } else {
                                                $groups[$key]['quantity'] = $groups[$key]['quantity'] + $qty;
                                            }
                                            
                                        /* } */
                                    }
                                }
                                        
                            }
                            $n++;
                        }
                        
                    }
                    fclose($handle);
                
                }else{
                    $other[]='File Not Uploaded';
                    $valid = false;
                }
                if ($valid) {
                    //echo '<pre>';print_r($groups);exit;
                    $model->save();
                    if(!empty($groups)){
                        foreach($groups as $each){
                            if((int)$each['order_detail_id']>0){
                                $modelOrder=OrderDetails::model()->findByPK((int)$each['order_detail_id']);
                                $modelOrder->quantity_shipped=(int)$each['quantity'];
                                $modelOrder->save(false);
                            }
                            $modeldetails=new UploadSalesDetails();
                            $modeldetails->sales_upload_id=$model['id'];
                            $modeldetails->product_id=$each['product_id'];
                            $modeldetails->quantity=$each['quantity'];
                            $modeldetails->distributer_id=$each['distributer_id'];
                            $modeldetails->order_id=$each['order_id'];
                            $modeldetails->order_detail_id=$each['order_detail_id'];
                            $modeldetails->created_by =Yii::app()->user->id;
                            $modeldetails->created_date_time =date('Y-m-d H:i:s');
                            $modeldetails->updated_by =Yii::app()->user->id;
                            $modeldetails->updated_date_time =date('Y-m-d H:i:s');
                            $modeldetails->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['UploadSales'];
                    $jsonData['id'] = $model->id;
                    echo CJSON::encode($jsonData);
                } else {
                    $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                    if(empty($groups)){
                        $other[] = "Please add atleast one line item";
                    }
                    if(!empty($arr_dis)){
                        $other[] = "Distributer codes ".implode($arr_dis,',').' not exists';
                    }
                    if(!empty($arr_gmc)){
                        $other[] = "GMC codes ".implode($arr_gmc,',').' not exists';
                    }
                    $error = CJSON::encode(array_merge_recursive($error1,$other));
                    if ($error != '[]')
                        echo $error;
                }
            }
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
        
    }
    public function actionView() {
         if(count($_GET) > 0){
            $model = new UploadSales();
            $id = (int) Yii::app()->request->getParam('id');
            if ($id > 0) {
                $model = $model->findByPk($id);
            }
           $this->render('view_salesform', array('model' => $model));  
         }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
    
    
    public function actionDelete(){
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST)>0){
            $id = $_POST['id'];
            if($id>0){
                $model = new UploadSales();
                $modelItems= new UploadSalesDetails();
                $modelAllItems=  $modelItems->findAll(array('condition'=>'sales_upload_id='.$id));
                foreach($modelAllItems as $each){
                    $model_gmc_exists=OrderDetails::model()->findByPk((int)$each->order_detail_id);
                    $model_gmc_exists->quantity_shipped=0;
                    $model_gmc_exists->save(false);
                }
                $model->deleteByPk($id);
                $modelItems->deleteAll('sales_upload_id=:refer_id', array(':refer_id' => $id));
                echo "success";
            } else {
                echo "fail";
            }
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    } 
    public function actionGetviewList() {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $sales_upload_id = (int)$_POST['order_id'];
            $model = new UploadSalesDetails();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $columns = array(
                // datatable column index  => database column name
                0 => 't.id',
                1 => 'category_det.product_category',
                2 => 'product_det.gmc_code',
                3 => 'dis_det.distributer_name',
                4 => 't.quantity'
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = 'sales_upload_id='.$sales_upload_id;
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                $condition .= " and (category_det.product_category LIKE '%" . $searchString . "%' 
                         OR product_det.gmc_code LIKE '%" . $searchString . "%' OR 
                         dis_det.distributer_name LIKE '%" . $searchString . "%' OR t.quantity LIKE '%" . $searchString . "%')";
            }
            $count = $model->with('product_det.category_det','product_det','dis_det')->count(array('condition' => $condition));
            $model = $model->with('product_det.category_det','product_det','dis_det')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
            $recordsTotal = $count;
            $recordsFiltered = $count;
            $data['draw'] = $draw;
            $data['recordsTotal'] = $recordsTotal;
            $data['recordsFiltered'] = $recordsFiltered;
            $rowData = array();
            $m = 1;
            foreach ($model as $row) {
                $rowData[] = array($m,
                        $row['product_det']['category_det']['product_category'], $row['product_det']['gmc_code'], $row['dis_det']['distributer_name'], $row['quantity']);
                $m++;
            }
            $data['data'] = $rowData;
            echo json_encode($data);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }
    /*public function actionDownloadUploaded(){
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        $id = $_GET['id'];
        if(count($_GET) > 0){
            $file = fopen("upload/test.csv", "w");
            $j=0;
            $list[$j++] ='GMC code!Quantity';
            $model_inventory =Inventory::model()->findAll(array('condition'=>'t.is_active="Y"'));
            foreach($model_inventory as $row){
                $list[$j++] =$row['gmc_code'].'!0';
            }
            $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="Intial_backlog_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        }else{
            throw new CHttpException(404, 'Page not found.');
        }
    }*/
    public function actionDownload(){
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        $id = $_GET['id'];
        if(count($_GET) > 0){
            $model = new UploadSales();
            $model = $model->findBypk($id);    
            $filename = 'upload/sales/'. $model->file_name;
            header("Content-Type: application/csv");
            header('Content-Disposition:attachment; filename="Sales_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        }else{
            throw new CHttpException(404, 'Page not found.');
        }
    }
}