<?php

Class UploadunshippedController 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', 'UploadUnshippeddocument','GetList', 'DownloadUnshipped','UploadDocuments','SaveunshippedUpload',

                'DeleteUploadUnshipped','ViewUploadUnshipped','GetunshippedviewList','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_SANITIZE_STRING);

        if(count($_POST) > 0){

            $model = new UploadUnshippedSales();

            $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["unshipped_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="ViewUploadUnshipped('.$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["unshipped_delete"])) {

                if(empty($model_his))

                {

                    $div .=   ' <button type="button"  class="btn btn-primary btn-xs " onclick="DeleteUploadUnshipped('.$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 actionUploadUnshippeddocument() {

        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);

        if(count($_GET) > 0){

            $model = new UploadUnshippedSales();

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

        

        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

        $row_taken = 0;

        if(count($_POST) > 0){

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

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

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

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

                $file= $_POST['UploadUnshippedSales']['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/unshippedsales/" . $file, "r")) !== FALSE) {

                        

                        $mod_settings = MasSettings::model()->find();

                        $year_taken = $mod_settings->unshipped_year;

                        $month_taken= $mod_settings->unshipped_month;

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

                            if ($n == 1) {

                                $row_count=count($row);

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

                                    $yearmonth =$row[$j];

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

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

                                    

                                    if((int)$each_month==((int)$month_taken) && (int)$each_year==(int)$year_taken ){

                                        $row_taken = $j;

                                    }

                                }

                            }

                            //echo '$row_taken'.$row_taken;

                            if((int)$row_taken==0){

                                $other[]='Data not found for year '.(int)$year_taken.' and month '.((int)$month_taken);

                                $valid = false;

                            }

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

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

                            $qty= trim($row[$row_taken]); //qty

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

                            if(!empty($mod_inv)){

                                if((int)$qty<0){

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

                                    $valid = false;

                                }else if((int)$qty>0){

                                    if($type=="Unshipped Sales Qty"){

                                        if(empty($mod_inv)){

                                            $arr_gmc[] = $gmc_code;

                                            $valid = false;

                                        }else{

                                            

                                            $key =$mod_inv->id;

                                            

                                            if (!array_key_exists($key, $groups)) {

                                                $groups[$key] = array(

                                                    'product_id' => $mod_inv->id,

                                                    'gmc_code' => $gmc_code,

                                                    'quantity' => $qty,

                                                );

                                            } else {

                                                $groups[$key]['quantity'] = $groups[$key]['quantity'] + $qty;

                                            }

                                            

                                        }

                                    }else{

                                        $other[] = 'Type '.$type.' not equal to Unshipped Sales Qty';

                                        $valid = false;

                                    }

                                }

                                        

                            }

                            $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){

                            $modeldetails=new UploadUnshippedDetails();

                            $modeldetails->upload_id=$model['id'];

                            $modeldetails->product_id=$each['product_id'];

                            $modeldetails->gmc_code=$each['gmc_code'];

                            $modeldetails->quantity=$each['quantity'];

                            $modeldetails->created_by =Yii::app()->user->id;

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

                            $modeldetails->save(false);

                        }

                    }

                    //increase month by one in massettings 

                    MasSettings::AddOneUnshippedMonth();

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

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

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

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

                    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_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 actionViewUploadUnshipped() {

         if(count($_GET) > 0){

            $model = new UploadUnshippedSales();

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

            if ($id > 0) {

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

            }

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

         }

        else{

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

        }

    }

    /*

    Download format for Unshipped Document

    */

    public function actionDownloadUnshipped(){

        $_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!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="Unshipped_downloadformat.csv"');

            readfile($filename);

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

            return;

        }else{

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

        }

    }

    

    public function actionDeleteUploadUnshipped(){

        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

        if(count($_POST)>0){

            $id = $_POST['id'];

            if($id>0){

                $model = new UploadUnshippedSales();

                $model->deleteByPk($id);

                $modelItems= new UploadUnshippedDetails();

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

                /*

                Reduce one month from massettings after deleting uploaded unshipped file

                */

                MasSettings::DeductOneUnshippedMonth();

                echo "success";

            } else {

                echo "fail";

            }

        }

        else{

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

        }

    } 

    public function actionGetunshippedviewList() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

        if (count($_POST) > 0) {

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

            $model = new UploadUnshippedDetails();

            $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 => 'quantity',

                4 => 't.gmc_code'

            );

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

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

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

            $condition = 'upload_id='.$upload_id;

            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 . "%'   OR t.quantity 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'], '<div class="text-right">' . $row['quantity'] . '</div>');

                $m++;

            }

            $data['data'] = $rowData;

            echo json_encode($data);

        } 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 = UploadUnshippedSales::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);

        }

    }

}