<?php



/* 

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

class InventoryuploadController 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('InventoryIndex', 'GoodsInIndex','GetInventoryUploadList','deleteconsolOrder','GetviewList',

                'GetInventoryUploadGoodsinList','Delete','ViewInventory','ViewGoodsIn','GetinventoryviewList','GetgoodsinviewList','checkHistory',

                'editinventory','SaveEdittedInventory'),

                'expression' => '$user->isMember()',

            ),

            array('deny', // deny all users

                'users' => array('*'),

            ),

        );

    }



    // Uncomment the following methods and override them if needed

    public function filters() {

        return array(

            'accessControl', // perform access control for CRUD operations

        );

    }

    

    public function actionInventoryIndex() {

        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);

        if(count($_GET) > 0){

            $this->render('inventory_index');

        }

        else{

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

        }

    }

    public function actionGoodsInIndex() {

        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);

        if(count($_GET) > 0){

            $this->render('goodsin_index');

        }

        else{

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

        }

    }

    public function actionGetInventoryUploadList() {

        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

        if(count($_POST) > 0){

            $model = new InventoryUploads();

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

                2 => 'year',

                3 => 'month',

                4 => 'id',

            );

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

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

            if($_POST['order'][1]['column']>0){

                $filterColumn .= ' , '.$columns[$_POST['order'][1]['column']];

            }

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

            $condition = 'type="Inventory" ';

            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 (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["inventory_view"])) {

                     $div .=   ' <button class="btn btn-primary btn-xs" onclick="viewinventoryupload('.$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["inventory_delete"])) {

                if(empty($model_his)&& $row['is_locked']=='N')

                {

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

                }

                }

                $rowData[] = array($m,

                    date('d/m/Y',strtotime($row['uploaded_date'])),$row['year'],$arr_months[(int)$row['month']],'<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 actionGetInventoryUploadGoodsinList() {

        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

        if(count($_POST) > 0){

            $model = new InventoryUploads();

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

                2 => 'year',

                3 => 'month',

                4 => 'id',

            );

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

            if($_POST['order'][1]['column']>0){

                $filterColumn .= ' , '.$columns[$_POST['order'][1]['column']];

            }

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

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

            $condition = 'type="GoodsIn" ';

            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 (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));

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

            $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["goodsin_view"])) {

                    $div .=   ' <button class="btn btn-primary btn-xs" onclick="viewgoodsin('.$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["goodsin_delete"])) {

                if(empty($model_his)&& $row['is_locked']=='N')

                {

                    //if(empty($model_last)|| $model_last->id==$row['id']){

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

                    //}

                }

                }

                $rowData[] = array($m,date('d/m/Y',strtotime($row['uploaded_date'])),$row['year'],$arr_months[(int)$row['month']],'<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 actionViewInventory() {

         if(count($_GET) > 0){

            $model = new InventoryUploads();

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

            if ($id > 0) {

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

            }

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

         }

        else{

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

        }

    }

    

    public function actionGetinventoryviewList() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

        if (count($_POST) > 0) {

            $order_id = (int)$_POST['inventory_upload_id'];

            $model = new InventoryUploadDetails();

            $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 => 'product_det.model_no',

                4 => 'total_quantity',

                5 => 'month_taken',

                6 => 'year_taken',

            );

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

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

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

            $condition = 'inventory_upload_id='.$order_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 product_det.model_no LIKE '%" . $searchString . "%' 

                         OR total_quantity LIKE '%" . $searchString . "%')";

            }

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

            $model = $model->with('category_det','product_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;

            $arr_months=Order::getmonths();

            foreach ($model as $row) {

                $div = '';

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

                     $div .=   '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'inventoryupload/editinventory&id='.$row['id'].'\',\'Edit Inventory Upload\',\'lg\')"><i class="fa fa-pencil"></i></button>';

                //}

                $rowData[] = array($m,

                    $row['category_det']['product_category'], $row['product_det']['gmc_code'], $row['product_det']['model_no'], $row['total_quantity'], $row['year_taken'], $arr_months[$row['month_taken']],$div);

                $m++;

            }

            $data['data'] = $rowData;

            echo json_encode($data);

        } else {

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

        }

    }

    

    public function actionViewGoodsIn() {

         if(count($_GET) > 0){

            $model = new InventoryUploads();

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

            if ($id > 0) {

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

            }

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

         }

        else{

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

        }

    }

    public function actionGetgoodsinviewList() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

        if (count($_POST) > 0) {

            $order_id = (int)$_POST['inventory_upload_id'];

            $model = new InventoryUploadDetails();

            $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 => 'product_det.model_no',

                4 => 'total_quantity',

                5 => 'month_taken',

                6 => 'year_taken',

            );

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

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

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

            $condition = 'inventory_upload_id='.$order_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 product_det.model_no LIKE '%" . $searchString . "%' 

                         OR total_quantity LIKE '%" . $searchString . "%')";

            }

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

            $model = $model->with('category_det','product_det','parent_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;

            $arr_months=Order::getmonths();

            foreach ($model as $row) {

                $rowData[] = array($m,

                    $row['category_det']['product_category'], $row['product_det']['gmc_code'], $row['product_det']['model_no'], '<div class="text-right">'.$row['total_quantity'].'</div>', $arr_months[$row['month_taken']] ."-". $row['year_taken'],$arr_months[$row['end_month']]."-".$row['end_year']);

                $m++;

            }

            $data['data'] = $rowData;

            echo json_encode($data);

        } else {

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

        }

    }

    public function actionDelete(){

        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

        if(count($_POST)>0){

            $id = $_POST['id'];

            if($id>0){

                $model = new InventoryUploads();

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

                $type  = $model->type;

                $month = $model->month;

                $year  = $model->year;

                $model->deleteByPk($id);

                $modelItems= new InventoryUploadDetails();

                if($type=="GoodsIn"){

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

                    foreach($modelAllItems as $each){

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

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

                    }*/

                    $modelInv = new Inventory();

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

                    if(!empty($modelAllItems)){

                        foreach($modelAllItems as $eachInv){

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

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

                        }

                    }

                }else{

                    /*

                    Reduce one month from massettings after deleting uploaded inventory file

                    */

                    MasSettings::DeductOneInvMonth();

                }

                

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

                //$updated_flag=OrderDetails::updateShippingConfirmation((int)$month,(int)$year);

                echo "success".$updated_flag;

            } else {

                echo "fail";

            }

            

        }

        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 = InventoryUploads::model()->find(array('condition'=>'type="GoodsIn"','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 1 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);

        }

    }

    public function actionEditInventory(){

        if(count($_GET) > 0){

            $model = new InventoryUploadDetails();

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

            if ($id > 0) {

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

            }

            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('edit_inventoryupload_form', array('model' => $model));  

         }

        else{

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

        }

    }

    public function actionSaveEdittedInventory(){

        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

        $other=[];

        if(count($_POST) > 0){

            $model = new InventoryUploadDetails();

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

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

                    $id = (int) @$_POST['InventoryUploadDetails']['id'];

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

                    $old_qty=$model->total_quantity;

                }

                $model->total_quantity = $_POST['InventoryUploadDetails']['total_quantity'];

                $model->inventory_quantity = $_POST['InventoryUploadDetails']['total_quantity'];

                $model->updated_by = Yii::app()->user->id;

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

                $valid = $model->validate();

                if ($valid) {

                    $model->save();

                    OrderDetails::updateShippingConfirmationByProduct((int)$model->parent_det->month,(int)$model->parent_det->year,(int)$model->product_id);

                    //*Write to auditlog --- Start*//

                    //*Write to auditlog -----End*//

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

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

                    echo CJSON::encode($jsonData);

                } else{

                    $error1 =  array();

                    $error1 = json_decode(CActiveForm::validate($model, '', false), true);

                    $error = CJSON::encode(array_merge_recursive($error1,$other));

                    if ($error != '[]')

                        echo $error;

                }

            }

        }else{

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

        }

    }

}