<?php
 class SalesController 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('SaveSalesUpload'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    public function actionSaveSalesUpload(){
        
        $_POST  = filter_input_array(INPUT_POST, FILTER_DEFAULT);
        if(count($_POST) > 0){
            $model = new UploadSales();$other=array();
            if (isset($_POST['UploadSales'])) {
                if ((int) @$_POST['UploadSales']['id'] > 0) {
                    $id = (int) @$_POST['UploadSales']['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['UploadSales'];
                $file= $_POST['UploadSales']['file_name'];
                $model->file_name =$file;
                $valid= $model->validate();
                $i=0;$groups=[];$n=1;$arr_dis=[];$arr_gmc=[];$p=0;static $distCache = [];$arr_gmc_with_models=[];
                static $invCache = [];
                if($file!=''){
                    if (($handle = fopen("upload/sales/" . $file, "r")) !== FALSE) {
                        while (($row = fgetcsv($handle)) !== FALSE) {
                            if ($n >1) {
                                $remarks='';
                                $gmc_code= trim($row[32]); //gmc AG
                                $base_code= trim($row[12]); //base_code M
                                $pay_term= trim($row[9]); //pay J
                                $qty= (float)trim($row[17]); //qty R
                                $amt_usd= (float)trim(str_replace(['$', ','], '', $row[21]) ); //amt in usd V
                                $type= trim($row[9]); //payment_type J
                                $distributer_code= trim($row[27]); // distr account code
                                if($pay_term=='FOC'){
                                    $remarks = 'Value is '.$amt_usd.'. But FOC Item ';
                                    $amt_usd=0;
                                }
                                if(!isset($distCache[$distributer_code])) {
                                    $distCache[$distributer_code] = Distributers::model()->find([
                                        'condition' => 'FIND_IN_SET(:code, alias_3_name)',
                                        'params' => [':code' => $distributer_code]
                                    ]);
                                }
                                if(!isset($invCache[$gmc_code])) {
                                    $invCache[$gmc_code] = Inventory::model()->find([
                                        'condition' => 'gmc_code = :gmc',
                                        'params' => [':gmc' => $gmc_code]
                                    ]);
                                }
                
                                $distributer_model = $distCache[$distributer_code];
                                $mod_inv = $invCache[$gmc_code];
                                if($qty!=0){
                                    if(empty($distributer_model)||empty($mod_inv)){
                                        if(empty($distributer_model)){
                                            if(!in_array($distributer_code,$arr_dis)){
                                                $arr_dis[] = $distributer_code;
                                            }
                                        }
                                        if(empty($mod_inv)){
                                            if(!in_array($gmc_code,$arr_gmc)){
                                                $arr_gmc[] = $gmc_code;
                                                $arr_gmc_with_models[] = $gmc_code.'/ ('.$base_code.')';
                                            }
                                        }
                                    }else{
                                        
                                        $detail = new SalesDetails();
                                        $detail->attributes = [
                                            'sales_upload_id'=>0,
                                            'product_id' => $mod_inv->id,
                                            'gmc_code' => $gmc_code,
                                            'distributor_code' => $distributer_code,
                                            'distributor_id' => $distributer_model->id,
                                            'sales_quantity' => $qty,
                                            'unit_price' => trim($row[18]),
                                            'currency_code' => trim($row[20]),
                                            'amount_in_usd' => $amt_usd,
                                            'payment_term' => $pay_term,
                                            'remarks' => $remarks,
                                            'sales_year' => $_POST['UploadSales']['year'],
                                            'sales_month' => $_POST['UploadSales']['month'],
                                            'created_by' => Yii::app()->user->id,
                                            'created_date_time' => date('Y-m-d H:i:s'),
                                        ];
                                        $detailsToSave[] = $detail;
                                        
                                    }
                                }
                                        
                            }
                            $n++;
                        }
                        
                    }
                    fclose($handle);
                
                }else{
                    $other[]='File Not Uploaded';
                    $valid = false;
                }
                //echo '<pre>';print_r($detailsToSave);exit;
                $comm =[];
                // 3. Final Validation & Transactional Save
                if ($valid && !empty($detailsToSave) && $model->validate()) {
                    $transaction = Yii::app()->db->beginTransaction();
                    try {
                        $comm = [];
                        if (!empty($arr_dis)) $comm[] = "Distributer codes " . implode(',', $arr_dis) . ' not exists';
                        if (!empty($arr_gmc)) $comm[] = "GMC codes " . implode(',', $arr_gmc_with_models) . ' not exists';
                        $model->comments = implode(',', $comm);
        
                        if ($model->save()) {
                            foreach ($detailsToSave as $detail) {
                                $detail->sales_upload_id = $model->id;
                                $detail->save(false);
                            }
                            $transaction->commit();
                            echo CJSON::encode(['status' => 'success', 'id' => $model->id]);
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        echo CJSON::encode(['status' => 'error', 'message' => 'Database Save Failed']);
                    }
                } else {
                    // Error handling
                    $error1 = json_decode(CActiveForm::validate($model, '', false), true) ?: [];
                    if (empty($detailsToSave)) $other[] = "Please add at least one valid line item";
                    if (!empty($arr_dis)) $other[] = "Missing Dist: " . implode(',', $arr_dis);
                    if (!empty($arr_gmc)) $other[] = "Missing GMC: " . implode(',', $arr_gmc);
                    
                    echo CJSON::encode(array_merge_recursive($error1, $other));
                }
            }
        }else{
              throw new CHttpException(404, 'Page not found.');
        }
        
    }
    
    /*public function actionDownloadUploaded(){
        $_GET  = filter_input_array(INPUT_GET, FILTER_DEFAULT);
        $id = $_GET['id'];
        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="Intial_backlog_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        }else{
            throw new CHttpException(404, 'Page not found.');
        }
    }*/
    public function actionDownload(){
        $_GET  = filter_input_array(INPUT_GET, FILTER_DEFAULT);
        $id = $_GET['id'];
        if(count($_GET) > 0){
            $model = new UploadSales();
            $model = $model->findBypk($id);    
            $filename = 'upload/sales/'. $model->file_name;
            header("Content-Type: application/csv");
            header('Content-Disposition:attachment; filename="Sales_downloadformat.csv"');
            readfile($filename);
            Yii::app()->end();
            return;
        }else{
            throw new CHttpException(404, 'Page not found.');
        }
    }
}