<?php

    /*

    created By jisha jacob

    */

    class UploadbacklogController 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('Index', 'UploadBacklogDocument','GetList', 'DownloadBacklog','UploadDocuments','SavebacklogUpload','DeleteBackLog','ViewBackLog','GetbacklogviewList','checkHistory'),

                '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_DEFAULT);

        if(count($_POST) > 0){

            $model = new UploadBacklog();

            $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';

             if($month!=''){

                $condition.=' AND month='. $month;

                

            }

            if($year>0){

                $condition.=' AND year='. $year;

                

            }

            $arr_months=Order::getmonths();

            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

                $searchString = $_POST['search']['value'];

                $condition .= " and (added_date 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["backlog_view"])) {

                     //$div .=   '<button type="button"  class="btn btn-sm btn-theme" onclick="downloadconsolidatedorder('.$row[id].');" title="ALL"><i class="fa fa-download"></i></button>';

                     $div .=   ' <button class="btn btn-primary btn-xs" onclick="ViewBackLog('.$row['id'].');"><i class="fa fa-eye"></i></button>';

                     

                }

                $model_his = SupplyConfirmation::model()->find(array('condition'=>'month = "'.$row['month'].'" and year = "'.$row['year'].'"'));

                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["backlog_delete"])) {

                if(empty($model_his))

                {

                    $div .=   '&nbsp<button type="button"  class="btn btn-primary btn-xs " onclick="DeleteBackLog('.$row['id'].')"><i class="fa fa-trash"></i></button>';

                }

                }

                $rowData[] = array($m,

                    date('d/m/Y',strtotime($row['added_date'])),$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 actionUploadBacklogDocument() {

        $_GET   = filter_input_array(INPUT_GET, FILTER_DEFAULT);

        if(count($_GET) > 0){

            $model = new UploadBacklog();

            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.');

        }

        

    }

    /*

    modified on 26-04-2022

    Function to save uploaded monthwise backlog*/      

    public function actionSavebacklogUpload(){

        

        $_POST  = filter_input_array(INPUT_POST, FILTER_DEFAULT);

        if(count($_POST) > 0){

            $model = new UploadBacklog();$other=array();

            if (isset($_POST['UploadBacklog'])) {

                if ((int) @$_POST['UploadBacklog']['id'] > 0) {

                    $id = (int) @$_POST['UploadBacklog']['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['UploadBacklog'];

                $file= $_POST['UploadBacklog']['file_name'];

                $model->file_name =$file;

                $model->added_date=date('Y-m-d');

                $valid= $model->validate();

                $i=0;$groups=[];$n=1;$arr_dis=[];$arr_gmc=[];

                

                if($file!=''){

                    if (($handle = fopen("upload/backlog/".$file,"r")) !== FALSE) {

                        $n = 1;

                        $arr_months=Order::getmonths();

                        $mod_his = UploadBacklog::model()->find(array('condition'=>'month = "'.$_POST['UploadBacklog']['month'].'" and year = "'.$_POST['UploadBacklog']['year'].'"'));

                        if(!empty($mod_his)){

                            $other[]='Already added Data';

                            $valid = false;

                        }

                        while (($row = fgetcsv($handle)) !== FALSE) {

                            $row_count=count($row);

                            if ($n == 1) {

                                for($j=15;$j<$row_count;$j++){

                                    $arr_upload_months[$j]=$row[$j];

                                    if($row[$j]==''){

                                        $other[]='Heading Month and Year missing';

                                        $valid = false;

                                    }

                                }

                            }

                            if ($n > 1 && $valid) {

                                $gmc_code= trim($row[6]); //gmc

                                $type= trim($row[14]); //type

                                if($type=="Order Backlog Qty"){

                                    $mod_inv = Inventory::model()->with('category_det')->find(array('condition'=>'gmc_code="'.$gmc_code.'"'));

                                    if(!empty($mod_inv)){

                                        $month_taken =$mod_inv->backlog_end_month;

                                        $year_taken =(int)$mod_inv->backlog_end_year;

                                        $upload_year = $mod_inv->backlog_year;

                                        $upload_month= $mod_inv->backlog_month;

                                        if(($upload_year<$year_taken)||(($upload_year==$year_taken)&&($upload_month<=$month_taken)) ){

                                            $qty=0;

                                            $row_taken = 0;

                                            for($j=15;$j<$row_count;$j++){

                                                $yearmonth =$arr_upload_months[$j];

                                                $each_month = substr($yearmonth, -2); 

                                                $each_year = substr($yearmonth, 0, 4);; 

                                                

                                                if((float)$row[$row_taken]<0){

                                                    $other[] = 'GMC with code '.$gmc_code.' entered negative quantity '.(float)$row[$row_taken];

                                                    $valid = false;

                                                }

                                                if((((int)$each_month>=((int)$upload_month) && (int)$each_year==(int)$upload_year)||((int)$upload_year<(int)$each_year))&&(((int)$each_month<=$month_taken && $year_taken==$each_year)||($year_taken>(int)$each_year))){

                                                    $row_taken = $j;

                                                    $qty = (float)$qty+(float)$row[$row_taken];

                                                }

                                                

                                            }

                                            if(((float)$qty)<0){

                                                $other[] = 'GMC with code '.$gmc_code.' entered negative quantity '.((float)$qty);

                                                $valid = false;

                                            }else{

                                                $modelItems[$i] = new UploadBacklogDetails();

                                                $modelItems[$i]->upload_id= 0 ;

                                                $modelItems[$i]->product_id= (int)$mod_inv->id ;

                                                $modelItems[$i]->gmc_code=$gmc_code;

                                                $modelItems[$i]->quantity = $qty ;

                                                $modelItems[$i]->start_month = $upload_month;

                                                $modelItems[$i]->start_year = $upload_year;

                                                $modelItems[$i]->end_month = $month_taken;

                                                $modelItems[$i]->end_year = $year_taken;

                                                $modelItems[$i]->created_by = Yii::app()->user->id;

                                                $modelItems[$i]->created_date_time =date('Y-m-d H:i:s');

                                                $valid = $modelItems[$i]->validate() && $valid;

                                                $i++;

                                                if (in_array($mod_inv->id,$arr_gmc)) {

                                                    $other[] = $gmc_code. ' GMC Repeated ';

                                                    $valid = false;

                                                }else{

                                                    $arr_gmc[]=$mod_inv->id;

                                                }

                                            }

                                        }

                                    }

                                   

                                }else{

                                    $other[] = 'Type '.$type.' not equal to Order Backlog Qty';

                                    $valid = false;

                                }

                            }

                            $n++;

                        }

                        

                    }

                    fclose($handle);

                

                }else{

                    $other[]='File Not Uploaded';

                    $valid = false;

                }

                if ($valid) {

                    //echo '<pre>';print_r($model);print_r($modelItems);die();

                    $model->save();

                    if(!empty($modelItems)){

                        foreach($modelItems as $each){

                            $each->upload_id= (int)$model->id;

                            $each->save(false);

                            $each->refresh();

                            //$mod_inv = Inventory::AddOneBacklogMonth((int)$each->product_id);

                            

                        }

                    }

                    $modelInv = new Inventory();

                    $modelAllItems=  $modelInv->findAll(array('condition' => 't.is_active="Y"'));

                    if(!empty($modelAllItems)){

                        foreach($modelAllItems as $eachInv){

                            //Increase one month from inventory after  uploaded backlog file

                            Inventory::AddOneBacklogMonth((int)$eachInv->id);

                        }

                    }

                    $jsonData['status'] = 'success';

                    $jsonData['frm'] = $_POST['UploadBacklog'];

                    $jsonData['id'] = $model->id;

                    //$jsonData['updated_flag'] = OrderDetails::updateShippingConfirmation((int)$_POST['UploadBacklog']['month'],(int)$_POST['UploadBacklog']['year']);

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

         if(count($_GET) > 0){

            $model = new UploadBacklog();

            $id = (int) Yii::app()->request->getParam('id');

            if ($id > 0) {

                $model = $model->findByPk($id);

            }

           $this->render('view_backlog_sales', array('model' => $model));  

         }

        else{

              throw new CHttpException(404, 'Page not found.');

        }

    }



    public function actionDeleteBackLog(){

        $_POST  = filter_input_array(INPUT_POST, FILTER_DEFAULT);

        if(count($_POST)>0){

            $id = $_POST['id'];

            if($id>0){

                $model = new UploadBacklog();

                $model->deleteByPk($id);

                $modelItems= new UploadBacklogDetails();

                /*$modelAllItems=  $modelItems->findAll(array('condition'=>'upload_id='.$id));

                foreach($modelAllItems as $each){

                    //Reduce one month from inventory after deleting uploaded backlog file

                    Inventory::DeductOneBacklogMonth((int)$each->product_id);

                }*/

                

                $modelItems->deleteAll('upload_id=:refer_id', array(':refer_id' => $id)); 

                $modelInv = new Inventory();

                $modelAllItems=  $modelInv->findAll(array('condition' => 't.is_active="Y"'));

                if(!empty($modelAllItems)){

                    foreach($modelAllItems as $each){

                        //Reduce one month from inventory after deleting uploaded backlog file

                        Inventory::DeductOneBacklogMonth((int)$each->id);

                    }

                }

                echo "success";

            } else {

                echo "fail";

            }

        }

        else{

              throw new CHttpException(404, 'Page not found.');

        }

    } 

  public function actionGetbacklogviewList() {

        $_POST = filter_input_array(INPUT_POST, FILTER_DEFAULT);

        if (count($_POST) > 0) {

            $upload_id = (int)$_POST['upload_id'];

            $model = new UploadBacklogDetails();

            $draw = $_POST['draw'];

            $offset = $_POST['start'];

            $limit = $_POST['length'];

            $columns = array(

                // datatable column index  => database column name

                0 => 't.id',

                1 => 'upload_id',

                2 => 'category_det.product_category',

                3 => 't.gmc_code'

            );

            $filterColumn = $columns[$_POST['order'][0]['column']];

            $filterOrder = $_POST['order'][0]['dir'];

            $orderBy = $filterColumn . " " . $filterOrder;

            $condition = 'upload_id='.$upload_id;

            $arr_months=Order::getmonths();

            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

                $searchString = $_POST['search']['value'];

                $condition .= " and (upload_id LIKE '%" . $searchString . "%' 

                         OR category_det.product_category LIKE '%" . $searchString . "%'  OR t.gmc_code LIKE '%" . $searchString . "%')";

            }

            $count = $model->with('product_det','product_det.category_det')->count(array('condition' => $condition));

            $model = $model->with('product_det','product_det.category_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['gmc_code'],$arr_months[(int)$row['start_month']]."-".$row['start_year'],$arr_months[(int)$row['end_month']]."-".$row['end_year'], '<div class="text-right">'.$row['quantity'].'</div>');

                $m++;

            }

            $data['data'] = $rowData;

            echo json_encode($data);

        } else {

            throw new CHttpException(404, 'Page not found.');

        }

    }

    /*

    Download format for Backlog Document

    */

    public function actionDownloadBacklog(){

        $_GET  = filter_input_array(INPUT_GET, FILTER_DEFAULT);

        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="Backlog_downloadformat.csv"');

            readfile($filename);

            Yii::app()->end();

            return;

        }else{

            throw new CHttpException(404, 'Page not found.');

        }

    }

    public function actioncheckHistory(){

        if(count($_GET) > 0){

            $year = Yii::app()->request->getParam('year');

            $month = Yii::app()->request->getParam('month');

            $model_last = UploadBacklog::model()->find(array('condition'=>'1=1','order'=>'year,month DESC','limit'=>1));

            $arr_months=Order::getmonths();

            $data['status'] = 'success';

            $data['msg'] = '';

            if(!empty($model_last)){

                if($model_last->month=='12'){

                    if($month!="1" || $year!=(int)($model_last->year+1)){

                        $data['msg'] = 'Expected Month is January AND Expected Year is'.(int)($model_last->year+1);

                    }

                }

                else{

                    if($month!=(int)($model_last->month+1) ||  $year!=(int)($model_last->year)){

                        $data['msg'] = 'Expected Month is '.$arr_months[(int)($model_last->month+1)].' AND Expected Year is '.(int)($model_last->year);

                    }

                }

            }else{

                $data['msg'] = '';

            }

            echo json_encode($data);

        }

    }

}