<?php

class GmcuploadController 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', 'DownloadFormat', 'UploadGMC', 'SaveGMCUpload', 'UploadDocuments', 'DownloadGmcFormat'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionUploadGMC() {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $model = new GmcUploads();
            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 actionDownloadGmcFormat() {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $file = fopen("upload/test.csv", "w");
            $j = 0;
            $list[$j++] = 'PRODUCT CATEGORY!GMC Code!Model No!CBM!BASE CODE';
            $model_inventory = Inventory::model()->with('category_det')->findAll(array('condition' => 't.is_active="Y"'));
            foreach ($model_inventory as $row) {
                $list[$j++] = $row['category_det']['product_category'] . '!' . $row['gmc_code'] . '!' . $row['model_no'] . '!' . $row['cbm'] . '!' . $row['base_code'];
            }
            $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="GMC_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionSaveGMCUpload() {

        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new GmcUploads();
            $other = array();
            if (isset($_POST['GmcUploads'])) {
                if ((int) @$_POST['GmcUploads']['id'] > 0) {
                    $id = (int) @$_POST['GmcUploads']['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['GmcUploads'];
                $model->upload_date = date('Y-m-d');
                $file = $_POST['GmcUploads']['file_name'];
                $model->file_name = $file;
                $valid = $model->validate();
                $i = 0;
                $arr_products = [];
                $n = 1;
                if ($file != '') {
                    if (($handle = fopen("upload/gmc/" . $file, "r")) !== FALSE) {

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

                            if ($n > 1) {
                                $product_category = trim($row[0], '\'"'); //productcategory
                                $category_id = (int) MasProductCategory::model()->find(array('condition' => 'product_category="' . $product_category . '"'))->id;
                                if ($category_id == 0) {
                                    $other[] = ' Category ' . $product_category . ' not added';
                                    $valid = false;
                                }
                                $gmc_code = trim($row[1]); //gmc
                                $model_no = trim($row[2]); //model
                                $mod_inv = Inventory::model()->find(array('condition' => 'gmc_code="' . $gmc_code . '"'));
                                if (!empty($mod_inv)) {
                                    $modelItems[$i] = Inventory::model()->findByPK((int) $mod_inv->id);
                                    $modelItems[$i]->product_category_id = (int) $category_id;
                                    $modelItems[$i]->model_no = $model_no;
                                    $modelItems[$i]->cbm = $row[3];
                                    $modelItems[$i]->base_code = $row[4];
                                    $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($gmc_code, $arr_products)) {
                                        $other[] = $gmc_code . ' GMC Repeated ';
                                        $valid = false;
                                    } else {
                                        $arr_products[] = $gmc_code;
                                    }
                                } else {
                                    $modelItems[$i] = new Inventory();
                                    $modelItems[$i]->product_category_id = (int) $category_id;
                                    $modelItems[$i]->gmc_code = $gmc_code;
                                    $modelItems[$i]->model_no = $model_no;
                                    $modelItems[$i]->cbm = $row[3];
                                    $modelItems[$i]->base_code = $row[4];
                                    $modelItems[$i]->goods_in_month = 0;
                                    $modelItems[$i]->goods_in_year = '0000';
                                    $modelItems[$i]->goods_in_end_month = 0;
                                    $modelItems[$i]->goods_in_end_year = '0000';
                                    $modelItems[$i]->backlog_month = 0;
                                    $modelItems[$i]->backlog_year = '0000';
                                    $modelItems[$i]->backlog_end_month = 0;
                                    $modelItems[$i]->backlog_end_year = '0000';
                                    $modelItems[$i]->is_active = 'Y';
                                    $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++;
                                }
                            }
                            $n++;
                        }
                        fclose($handle);
                    }
                } else {
                    $other[] = 'File Not Uploaded';
                    $valid = false;
                }
                /*echo '<pre>';
                print_r($modelItems);
                exit;*/
                if ($valid) {

                    $model->save();
                    if (!empty($modelItems)) {
                        foreach ($modelItems as $each) {
                            $each->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['GmcUploads'];
                    $jsonData['id'] = $model->id;
                    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.');
        }
    }

}
