<?php

/* Created By Jisha */

class InventoryController 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', 'Test'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('Index', 'Create', 'GetList', 'Save', 'Delete', 'DeletePriceDetails',
                    'UploadGoodsIn', 'SaveUploadGoodsIn', 'UploadInventory', 'SaveUploadInventory',
                    'UploadDocuments', 'Discontinue', 'Savediscontinue','Avoiddiscontinue','Saveavoiddiscontinue'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $this->render('index');
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    // Uncomment the following methods and override them if needed
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function actionGetList() {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new Inventory();
            $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 => 'gmc_code',
                3 => 'model_no',
                4 => 'cbm',
                5 => 'base_code',
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = '1=1';
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                $condition .= " and (category_det.product_category LIKE '%" . $searchString . "%' OR gmc_code LIKE '%" . $searchString . "%' 
                         OR model_no LIKE '%" . $searchString . "%'  OR base_code LIKE '%" . $searchString . "%')";
            }
            $count = $model->with('category_det')->count(array('condition' => $condition));
            $model = $model->with('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) {
                $div = '<div class="btn-wrap text-center">';
                if ($row['is_active'] == 'Y') {
                    if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["master_gmc_edit"])) {
                    $div .= '<button class="btn btn-primary btn-xs" title="Edit" onclick="loadPopupModal(\'inventory/create&id=' . $row['id'] . '\',\'Edit GMC\',\'lg\')"><i class="fa fa-pencil"></i></button>'; 
                    }
                    if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["master_gmc_discontinue"])) {
                    $div .= ' <button class ="btn btn-danger btn-xs" title="Discontinue" onclick="discontinuegmc(' . $row['id'] . ')"><i class="fa fa-close "></i></button>';
                    }
                    } else {
                    if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["master_gmc_view_inventory"])) {    
                    $div .= '<button class="btn btn-primary btn-xs" title="View" onclick="loadPopupModal(\'inventory/create&type=view&id=' . $row['id'] . '\',\'View GMC\',\'lg\')"><i class="fa fa-eye"></i></button>';
                    }
                    if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["master_gmc_continue"])) {    
                    
                    $div .= ' <button class ="btn btn-success btn-xs" title="Continue" onclick="avoiddiscontinuegmc(' . $row['id'] . ')"><i class="fa fa-retweet "></i></button>';
                    }
                     }
//}
                $div.= '</div>';

                $rowData[] = array($m,
                    $row['category_det']['product_category'], $row['gmc_code'], $row['model_no'], $row['base_code'],
                    $div);

                $m++;
            }
            $data['data'] = $rowData;
            echo json_encode($data);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionCreate() {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $model = new Inventory();
            $id = (int) Yii::app()->request->getParam('id');
            $type = Yii::app()->request->getParam('type');
            $modelDetails = array(new InventoryPrice());
            if ($id > 0) {
                $model = $model->findByPk($id);
            }
            $modelDetails = InventoryPrice::model()->findAll(array('condition' => 'product_id=' . (int) $id.' AND to_date="2099-12-31"'));
            if (empty($modelDetails)) {
                $modelDetails = array(new InventoryPrice());
            }
            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, 'modelDetails' => $modelDetails, 'type' => $type), false, false);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionSave() {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new Inventory();
            $arr_regions = [];
            $other = array();
            if (isset($_POST['Inventory'])) {
                if ((int) @$_POST['Inventory']['id'] > 0) {
                    $id = (int) @$_POST['Inventory']['id'];
                    $model = $model->findByPk($id);
                }
                $model->attributes = $_POST['Inventory'];
                $model->gmc_code = trim($_POST['Inventory']['gmc_code']);
                $model->model_no = trim($_POST['Inventory']['model_no']);
                $model->base_code = trim($_POST['Inventory']['base_code']);
                $valid = $model->validate();
                $p = 0;
                if (is_array($_POST['InventoryPrice'])) {
                    foreach ($_POST['InventoryPrice'] as $i => $item) {
                        if (in_array((int) $item['region_id'], $arr_regions)) {
                            $other[] = 'Price Already added For Same region';
                            $valid = false;
                        } else {
                            $arr_regions[] = (int) $item['region_id'];
                        }
                        $old_from_date= $item['from_date'];
                        $new_from_date = (int)$item['from_year'].'-'.(int)$item['from_month'].'-01';
                        $new_from_date_timestamp = strtotime($new_from_date);
                        $old_from_date_timestamp = strtotime($old_from_date);
                        
                        $modelDetails[$p] = new InventoryPrice;
                        if ((int) $item['id'] > 0) {
                            $modelDetails[$p] = InventoryPrice::model()->findByPk((int) $item['id']);
                        } else {
                            $modelDetails[$p]->created_by = Yii::app()->user->id;
                            $modelDetails[$p]->created_date_time = date("Y-m-d H:i:s");
                        }
                        $modelDetails[$p]->attributes = $item;
                        $modelDetails[$p]->product_id = 0;
                        $modelDetails[$p]->from_date = $item['from_date'];
                        if($old_from_date != $new_from_date) {
                            $modelDetails[$p]->to_date = $new_from_date;
                        }
                        $modelDetails[$p]->updated_by = Yii::app()->user->id;
                        $modelDetails[$p]->updated_date_time = date("Y-m-d H:i:s");
                        $valid = $modelDetails[$p]->validate() && $valid;
                        $p++;
                        if($old_from_date != $new_from_date) {
                            if($new_from_date_timestamp < $old_from_date_timestamp)
                            {
                                $other[] = 'New Date must be greated than previous date';
                                $valid = false;
                            }
                            $modelDetails[$p] = new InventoryPrice;
                            $modelDetails[$p]->created_by = Yii::app()->user->id;
                            $modelDetails[$p]->created_date_time = date("Y-m-d H:i:s");
                            $modelDetails[$p]->region_id = $item['region_id'];
                            $modelDetails[$p]->price = $item['price'];
                            $modelDetails[$p]->product_id = 0;
                            $modelDetails[$p]->from_date = $new_from_date;
                            $modelDetails[$p]->to_date = "2099-12-31";
                            $valid = $modelDetails[$p]->validate() && $valid;
                            $p++;
                        }
                    }
                }
                //echo '<pre>';print_r($model);print_r($modelDetails);
                if ($valid) {
                    $model->save();
                    if (!empty($modelDetails)) {
                        foreach ($modelDetails as $eachModel) {
                            $eachModel->product_id = $model->id;
                            $eachModel->save(false);
                            OrderDetails::model()->updateAll(array('price' => $eachModel['price']),'product_id='.(int)$model->id.' AND region_id='.(int)$eachModel['region_id'].' AND order_date>="'.$eachModel['from_date'].'" AND order_date<"'.$eachModel['to_date'] .'" '  );

                        }
                    }
                    $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($modelDetails))
                        $error2 = json_decode(CActiveForm::validateTabular($modelDetails, '', 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 actionDeletePriceDetails() {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $id = $_POST['id'];
            if ($id > 0) {
                $modelDetails = new InventoryPrice();
                $modelDetails->deleteByPk($id);
                $data['status'] = "success";
            } else {
                $data['status'] = "fail";
            }
            echo CJSON::encode($data);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    /* public function actionDelete() {

      $id = $_POST['id'];
      $model_c = Customer::model()->findAll(array('condition' => 'customer_country = ' . $id . ' '));
      $model_com = Company::model()->findAll(array('condition' => 'shipping_country = ' . $id . ' '));
      if (empty($model_c) && empty($model_com)) {
      $model = new Inventory();
      $model->deleteByPk($id);
      echo "success";
      } else {
      echo "fail";
      }
      } */

    public function actionUploadGoodsIn() {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        $flag = 0;
        if (count($_GET) > 0) {
            $model = new InventoryUploads();
            $mod_inv = Inventory::model()->find(array('condition' => 'goods_in_year="0000" OR goods_in_month="0"'));
            if (!empty($mod_inv)) {
                $flag = 1;
            }
            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_goodsin_form', array('model' => $model, 'flag' => $flag), false, false);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionUploadInventory() {
        $_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('upload_inventory_form', array('model' => $model), false, false);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    /* function to save uploaded GoodsIn data */

    public function actionSaveUploadGoodsIn() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new InventoryUploads();
            $other = array();
            if (isset($_POST['InventoryUploads'])) {
                if ((int) @$_POST['InventoryUploads']['id'] > 0) {
                    $id = (int) @$_POST['InventoryUploads']['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->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');
                $file = $_POST['InventoryUploads']['file_name'];
                $model->file_name = $file;
                $valid = $model->validate();
                $i = 0;
                $arr_products = [];
                if ($file != '') {
                    if (($handle = fopen("upload/goodsin/" . $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'] . '" AND type="GoodsIn"'));
                        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 == "Goods-in Qty") {
                                    $mod_inv = Inventory::model()->with('category_det')->find(array('condition' => 'gmc_code="' . $gmc_code . '"'));
                                    if (!empty($mod_inv)) {
                                        /* $cat_type=$mod_inv->supply_goodsin;
                                          //find end month for goodsin upload
                                          $arr_category_month = Inventory::getmonthyear((int)$_POST['InventoryUploads']['year'],(int)$_POST['InventoryUploads']['month'],$cat_type);
                                          $month_taken =$arr_category_month['month_taken'];
                                          $year_taken =(int)$arr_category_month['year_taken']; */
                                        $upload_year = $mod_inv->goods_in_year;
                                        $upload_month = $mod_inv->goods_in_month;
                                        $month_taken = $mod_inv->goods_in_end_month;
                                        $year_taken = (int) $mod_inv->goods_in_end_year;
                                        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 ($row[$row_taken] < 0) {
                                                    $other[] = 'GMC with code ' . $gmc_code . ' entered negative quantity' . $qty;
                                                    $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 += $row[$row_taken];
                                                }
                                            }
                                            if ($qty < 0) {
                                                $other[] = 'GMC with code ' . $gmc_code . ' entered negative quantity' . $qty;
                                                $valid = false;
                                            } else {
                                                $modelItems[$i] = new InventoryUploadDetails();
                                                $modelItems[$i]->inventory_upload_id = 0;
                                                $modelItems[$i]->category_id = $mod_inv->product_category_id;
                                                $modelItems[$i]->product_id = $mod_inv->id;
                                                $modelItems[$i]->inventory_quantity = 0;
                                                $modelItems[$i]->goods_in_qty = $qty;
                                                $modelItems[$i]->total_quantity = $qty;
                                                $modelItems[$i]->month_taken = $upload_month;
                                                $modelItems[$i]->year_taken = $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');
                                                $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{
                                      $other[] = 'GMC with code '.$gmc_code.' not exits';
                                      $valid = false;
                                      } */
                                } else {
                                    $other[] = 'Type ' . $type . ' not equal to Goods-in Qty';
                                    $valid = false;
                                }
                            }
                            $n++;
                        }
                        fclose($handle);
                    }
                } else {
                    $other[] = 'File Not Uploaded';
                    $valid = false;
                }
                if ($valid) {
                    $model->save();
                    if (!empty($modelItems)) {
                        foreach ($modelItems as $each) {
                            //increase month by one in Inventory 
                            $mod_inv = Inventory::AddOneGoodsInMonth((int) $each->product_id);
                            $each->inventory_upload_id = $model->id;
                            $each->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['InventoryUploads'];
                    $jsonData['id'] = $model->id;
                    $jsonData['updated_flag'] = OrderDetails::updateShippingConfirmation((int) $_POST['InventoryUploads']['month'], (int) $_POST['InventoryUploads']['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.');
        }
    }

    /* function to save uploaded Inventory data */

    public function actionSaveUploadInventory() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new InventoryUploads();
            $other = array();
            if (isset($_POST['InventoryUploads'])) {
                if ((int) @$_POST['InventoryUploads']['id'] > 0) {
                    $id = (int) @$_POST['InventoryUploads']['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->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');
                $file = $_POST['InventoryUploads']['file_name'];
                $model->file_name = $file;
                $valid = $model->validate();
                $i = 0;
                $arr_products = [];
                if ($file != '') {
                    if (($handle = fopen("upload/inventory/" . $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'] . '" and type="Inventory"'));
                        if (!empty($mod_his)) {
                            $other[] = 'Already added Data';
                            $valid = false;
                        }
                        $mod_settings = MasSettings::model()->find();
                        $year_taken = $mod_settings->inventory_year;
                        $month_taken = $mod_settings->inventory_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;
                                    }
                                }
                            }
                            if ((int) $row_taken == 0) {
                                $other[] = 'Data not found for year ' . (int) $year_taken . ' and month ' . ((int) $month_taken);
                                $valid = false;
                            }
                            if ($n > 1) {
                                $gmc_code = trim($row[6]); //gmc
                                $type = trim($row[14]); //type
                                $qty = $row[$row_taken];
                                if ($qty < 0) {
                                    $other[] = 'GMC with code ' . $gmc_code . ' entered negative quantity ' . $qty;
                                    $valid = false;
                                } else {
                                    if ($type == "Inventory Qty(good)") {
                                        $mod_inv = Inventory::model()->find(array('condition' => 'gmc_code="' . $gmc_code . '"'));
                                        if (!empty($mod_inv)) {
                                            $modelItems[$i] = new InventoryUploadDetails();
                                            $modelItems[$i]->inventory_upload_id = 0;
                                            $modelItems[$i]->category_id = $mod_inv->product_category_id;
                                            $modelItems[$i]->product_id = $mod_inv->id;
                                            $modelItems[$i]->inventory_quantity = $qty;
                                            $modelItems[$i]->goods_in_qty = 0;
                                            $modelItems[$i]->total_quantity = $qty;
                                            $modelItems[$i]->month_taken = (int) $month_taken;
                                            $modelItems[$i]->year_taken = (int) $year_taken;
                                            $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{
                                          $other[] = 'GMC with code '.$gmc_code.' not exits';
                                          $valid = false;
                                          } */
                                    } else {
                                        $other[] = 'Type ' . $type . ' not equal to Inventory Qty(good)';
                                        $valid = false;
                                    }
                                }
                            }
                            $n++;
                        }
                        fclose($handle);
                    }
                } 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);
                        }
                    }
                    //increase month by one in massettings 
                    MasSettings::AddOneInvMonth();
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['InventoryUploads'];
                    $jsonData['id'] = $model->id;
                    $jsonData['updated_flag'] = OrderDetails::updateShippingConfirmation((int) $_POST['InventoryUploads']['month'], (int) $_POST['InventoryUploads']['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 actionTest() {
        $arr_category_month = MasProductCategory::getgoodsinmonthyear('2022', '9', 'CM-2');
        echo $month_taken = $arr_category_month['month_taken'];
        echo $year_taken = (int) $arr_category_month['year_taken'];
    }

    public function actionDiscontinue() {
        //code aded by rahul on 7-6-22 
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $model = new Inventory();
            $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('discontinue_form', array('model' => $model), false, false);
        }
    }

    public function actionSavediscontinue() {
        //code aded by rahul on 7-6-22

        $model = new Inventory();
        $id = $_POST['Inventory']['id'];
        $discontinuing_month = $_POST['Inventory']['discontinuing_month'];
        $discontinuing_year = $_POST['Inventory']['discontinuing_year'];

        $model->updateByPk($id, array('is_active' => 'D', 'discontinuing_month' => $discontinuing_month, 'discontinuing_year' => $discontinuing_year));

        echo CJSON::encode(array('status' => 'success'));
    }
      public function actionAvoiddiscontinue() {
        //code aded by rahul on 14-6-22 
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $model = new Inventory();
            $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('avoid_discontinue_form', array('model' => $model), false, false);
        }
    }
    public function actionSaveavoiddiscontinue() {
        //code aded by rahul on 14-6-22

        $model = new Inventory();
        $id = $_POST['Inventory']['id'];
        $goods_in_month = $_POST['Inventory']['goods_in_month'];
        $goods_in_year = $_POST['Inventory']['goods_in_year'];
        $goods_in_end_month = $_POST['Inventory']['goods_in_end_month'];
        $goods_in_end_year = $_POST['Inventory']['goods_in_end_year'];
        $backlog_month = $_POST['Inventory']['backlog_month'];
        $backlog_year = $_POST['Inventory']['backlog_year'];
        $backlog_end_month = $_POST['Inventory']['backlog_end_month'];
        $backlog_end_year = $_POST['Inventory']['backlog_end_year'];
        $model->updateByPk($id, array('is_active' => 'Y', 'goods_in_month' => $goods_in_month, 'goods_in_year' => $goods_in_year,'goods_in_end_month' => $goods_in_end_month, 'goods_in_end_year' => $goods_in_end_year,
            'backlog_month' => $backlog_month, 'backlog_year' => $backlog_year,'backlog_end_month' => $backlog_end_month, 'backlog_end_year' => $backlog_end_year));

        echo CJSON::encode(array('status' => 'success'));
    }
}
