<?php
 class UploadsalesController 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', 'UploadSalesdocument','GetList', 'DownloadSales','UploadDocuments','SaveSalesUpload','Delete',
                'DownloadUploaded','View','GetviewList','Download','DownloadErrorLog'),
                '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_DEFAULT);
        if(count($_POST) > 0){
            $model = new UploadSales();
            $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 => 'created_date_time',
                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 (created_date_time 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["sales_view"])) {
                    $div .= ' <button class="btn btn-primary btn-xs" onclick="viewsales(' . $row['id'] . ');" title="View Sales"><i class="fa fa-eye"></i></button>';
                }
                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["sales_download"])) {
                    $div .= '<button type="button"  class="btn btn-primary btn-xs" onclick="downloadsales(' . $row['id'] . ');" title="Download Raw File"><i class="fa fa-download"></i></button>';
                }
                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["sales_delete"])) {
                    $div .= ' <button type="button"  class="btn btn-primary btn-xs" onclick="deleteSales(' . $row['id'] . ')" title="Delete Sales"><i class="fa fa-trash"></i></button>';
                }
                if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["sales_download"])) {
                    $div .= ' <button type="button"  class="btn btn-danger btn-xs" onclick="DownloadErrorLog(' . $row['id'] . ')" title="Download ErrorLog"><i class="fa fa-download"></i></button>';
                }


                $rowData[] = array($m,
                    date('d/m/Y',strtotime($row['created_date_time'])),$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 actionUploadSalesdocument() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_DEFAULT);
        if(count($_GET) > 0){
            $model = new UploadSales();
            $month = (int) Yii::app()->request->getParam('month');
            $year = (int) Yii::app()->request->getParam('year');
            $supply_confirm_id=(int) Yii::app()->request->getParam('supply_confirm_id');
            $model->supply_confirm_id=$supply_confirm_id;
            $model->month=$month;
            $model->year=$year;
            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 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=[];
                if($file!=''){
                    if (($handle = fopen("upload/sales/" . $file, "r")) !== FALSE) {
                        while (($row = fgetcsv($handle)) !== FALSE) {
                            if ($n > 2) {
                                $gmc_code= trim($row[9]); //gmc
                                $qty= trim($row[16]); //qty
                                //added to get price--15/04/25
                                $amt= trim(str_replace(['$', ','], '', $row[20]) ); //amt
                                //added to get price--15/04/25
                                $type= trim($row[29]); //type
                                $distributer_code= trim($row[61]); //qty
                                $distributer_model = Distributers::model()->find(array('condition'=>'distributer_name="'.$distributer_code.'" OR alias_name="'.$distributer_code.'"'));
                                $mod_inv = Inventory::model()->find(array('condition'=>'gmc_code="'.$gmc_code.'"'));
                                if((int)$qty>0){//($type=="FO"||$type=="3PO")&& --commented since 19-09-2022 for upload sales of all type
                                    if(empty($distributer_model)||empty($mod_inv)){
                                        if(empty($distributer_model)){
                                            if(!in_array($distributer_code,$arr_dis)){
                                                $arr_dis[] = $distributer_code;
                                            }
                                            //$valid = false;
                                        }
                                        if(empty($mod_inv)){
                                            if(!in_array($gmc_code,$arr_gmc)){
                                                $arr_gmc[] = $gmc_code;
                                            }
                                            //$valid = false;
                                        }
                                    }else{
                                        $model_salesorder = Order::model()->find(array('condition'=>'month="'.(int)$_POST['UploadSales']['month'].'" AND year='.(int)$_POST['UploadSales']['year'].' AND distributer_id='.(int)$distributer_model->id));
                                        $model_gmc_exists=OrderDetails::model()->with('parent_det')->find(array('condition'=>'product_id='.(int)$mod_inv['id'].' AND parent_det.id="'.(int)$model_salesorder->id.'"'));
                                        $key =$mod_inv->id.'_'.$distributer_model->id;
                                            
                                        if (!array_key_exists($key, $groups)) {
                                            $groups[$key] = array(
                                                'product_id' => $mod_inv['id'],
                                                'quantity' => $qty,
                                                'amount' => $amt,
                                                'distributer_id' => $distributer_model['id'],
                                                'order_id' => (int)$model_salesorder->id,
                                                'order_detail_id' => (int)$model_gmc_exists->id,
                                            );
                                        } else {
                                            $groups[$key]['quantity'] = (float)$groups[$key]['quantity'] + (float)$qty;
                                             $groups[$key]['amount'] = (float)$groups[$key]['amount'] + (float)$amt;
                                        }
                                    }
                                }
                                        
                            }
                            $n++;
                        }
                        
                    }
                    fclose($handle);
                
                }else{
                    $other[]='File Not Uploaded';
                    $valid = false;
                }
                $comm =[];
                if ($valid) {
                    //echo '<pre>';print_r($groups);exit;
                    if(!empty($arr_dis)){
                        $comm[] = "Distributer codes ".implode(',',$arr_dis).' not exists';
                    }
                    if(!empty($arr_gmc)){
                        $comm[] = "GMC codes ".implode(',',$arr_gmc).' not exists';
                    }
                    $model->comments=implode(',',$comm);
                    $model->save();
                    $mod_his = SupplyConfirmation::model()->find(array('condition'=>'month = "'.$_POST['UploadSales']['month'].'" and year = "'.$_POST['UploadSales']['year'].'"'));
                    if(!empty($groups)){
                        foreach($groups as $each){
                            $modInventory = Inventory::model()->findBYPK((int)$each['product_id']);
                            $modelOrderDetails=new OrderDetails();
                            if((int)$each['order_detail_id']>0){
                                $modelOrderDetails=$modelOrderDetails->findByPK((int)$each['order_detail_id']);
                                $modelOrderDetails->product_id=$each['product_id'];
                                $modelOrderDetails->category_id= (int)$modInventory->product_category_id ;
                                $modelOrderDetails->quantity_shipped=(int)$each['quantity'];
                                $modelOrderDetails->amount_shipped=$each['amount'];
                                $modelOrderDetails->updated_by =Yii::app()->user->id;
                                $modelOrderDetails->updated_date_time =date('Y-m-d H:i:s');
                                $modelOrderDetails->save(false);
                            }else{
                                $distributer_id=$each['distributer_id'];
                                $distributer_model= Distributers::model()->with('region_det')->findByPK((int)$distributer_id);
                                $region_id =(int)$distributer_model->region_id;
                                /*region value*/
                                    $price_date = (int)$_POST['UploadSales']['year'].'-'.(int)$_POST['UploadSales']['month'].'-'.'01';
                                    $price_cnd = 'product_id='.(int)$each['product_id'].' AND region_id='.(int)$region_id.' AND from_date <="'.$price_date.'" AND to_date >="'.$price_date.'"';
                                    $mod_inv_price=InventoryPrice::model()->find(array('condition'=>$price_cnd));
                                    $price_ordered=(float)$mod_inv_price->price;
                                /*region value*/
                                if($each['order_id']>0){
                                    $modelOrderDetails=new OrderDetails();
                                    $modelOrderDetails->order_id=$each['order_id'];
                                    $modelOrderDetails->product_id=$each['product_id'];
                                    $modelOrderDetails->quantity_ordered =0;
                                    $modelOrderDetails->price = $price_ordered;
                                    $modelOrderDetails->order_date =$price_date;
                                    $modelOrderDetails->region_id = (int)$region_id;
                                    $modelOrderDetails->quantity_shipped=(int)$each['quantity'];
                                    $modelOrderDetails->amount_shipped=$each['amount'];
                                    $modelOrderDetails->category_id= (int)$modInventory->product_category_id ;
                                    $modelOrderDetails->model = $modInventory->model_no;
                                    $modelOrderDetails->base_code = $modInventory->base_code;
                                    if($distributer_model->region_det->currency_type == 'USD'){
                                        $modelOrderDetails->exchange_rate = 1;
                                    }else{
                                        $mod_settings = MasSettings::model()->find();
                                        $currency_rate = $mod_settings->currency_rate;
                                        $modelOrderDetails->exchange_rate = (1/$currency_rate);
                                    }
                                    $modelOrderDetails->currency_type = $distributer_model->region_det->currency_type;
                                    $modelOrderDetails->created_by =Yii::app()->user->id;
                                    $modelOrderDetails->created_date_time =date('Y-m-d H:i:s');
                                    $modelOrderDetails->updated_by =Yii::app()->user->id;
                                    $modelOrderDetails->updated_date_time =date('Y-m-d H:i:s');
                                    $modelOrderDetails->supply_confirm_id=(int)$mod_his->id;
                                    $modelOrderDetails->is_done='Y';
                                    $modelOrderDetails->save(false);
                                }else{
                                    $model_salesorder = Order::model()->find(array('condition'=>'month="'.(int)$_POST['UploadSales']['month'].'" AND year='.(int)$_POST['UploadSales']['year'].' AND distributer_id='.(int)$distributer_model->id));
                                    $modelOrder = new Order();
                                    if(empty($model_salesorder)){   
                                        $modelOrder->distributer_id=$distributer_id;
                                        $modelOrder->month =(int)$_POST['UploadSales']['month'];
                                        $modelOrder->year=(int)$_POST['UploadSales']['year'];
                                        $modelOrder->order_date = $price_date;
                                        $modelOrder->region_id = (int)$region_id;
                                        $modelOrder->is_locked = 'Y';
                                        $modelOrder->file_name ='added From Sales';
                                        $modelOrder->created_by =Yii::app()->user->id;
                                        $modelOrder->created_date_time =date('Y-m-d H:i:s');
                                        $modelOrder->updated_by =Yii::app()->user->id;
                                        $modelOrder->updated_date_time =date('Y-m-d H:i:s');
                                        $modelOrder->save(false);
                                        $modelOrder->refresh();
                                    }else{
                                        $modelOrder = $modelOrder->findByPK((int)$model_salesorder->id);
                                    }
                                    $modelOrderDetails=new OrderDetails();
                                    $modelOrderDetails->order_id=$modelOrder->id;
                                    $modelOrderDetails->product_id=$each['product_id'];
                                    $modelOrderDetails->quantity_ordered =0;
                                    $modelOrderDetails->price = $price_ordered;
                                    $modelOrderDetails->order_date =$price_date;
                                    $modelOrderDetails->region_id = (int)$region_id;
                                    $modelOrderDetails->quantity_shipped=(int)$each['quantity'];
                                    $modelOrderDetails->amount_shipped=$each['amount'];
                                    $modelOrderDetails->category_id= (int)$modInventory->product_category_id ;
                                    $modelOrderDetails->model = $modInventory->model_no;
                                    $modelOrderDetails->base_code = $modInventory->base_code;
                                    if($distributer_model->region_det->currency_type == 'USD'){
                                        $modelOrderDetails->exchange_rate = 1;
                                    }else{
                                        $mod_settings = MasSettings::model()->find();
                                        $currency_rate = $mod_settings->currency_rate;
                                        $modelOrderDetails->exchange_rate = (1/$currency_rate);
                                    }
                                    $modelOrderDetails->currency_type = $distributer_model->region_det->currency_type;
                                    $modelOrderDetails->created_by =Yii::app()->user->id;
                                    $modelOrderDetails->created_date_time =date('Y-m-d H:i:s');
                                    $modelOrderDetails->updated_by =Yii::app()->user->id;
                                    $modelOrderDetails->updated_date_time =date('Y-m-d H:i:s');
                                    $modelOrderDetails->supply_confirm_id=(int)$mod_his->id;
                                    $modelOrderDetails->is_done='Y';
                                    $modelOrderDetails->save(false);
                                }
                            }
                            //added on 10-05-23 --start
                            $modSupplyDetails = new SupplyDetails();
                            $modelSupplyDetails = $modSupplyDetails->find(array('condition'=>'supply_confirm_id='.(int)$mod_his->id. ' AND product_id='.(int)$each['product_id']));
                            if(empty($modelSupplyDetails)){
                                $modSupplyDetails = new SupplyDetails();
                                $modSupplyDetails->supply_confirm_id =(int)$mod_his->id;
                                $modSupplyDetails->product_id =(int)$each['product_id'];
                                $modSupplyDetails->month =(int)$_POST['UploadSales']['month'];
                                $modSupplyDetails->year =(int)$_POST['UploadSales']['year'];
                                $modSupplyDetails->total_order =0;
                                $modSupplyDetails->goods_in =0;
                                $modSupplyDetails->inventory =0;
                                $modSupplyDetails->unshipped =0;
                                $modSupplyDetails->backlog =0;
                                $modSupplyDetails->added_from='SA';
                                $modSupplyDetails->created_by =(int)Yii::app()->user->id;
                                $modSupplyDetails->created_date_time =date('Y-m-d H:i:s');
                                $modSupplyDetails->save(false);
                            }
                            //added on 10-05-23 end
                            $modeldetails=new UploadSalesDetails();
                            $modeldetails->sales_upload_id=$model['id'];
                            $modeldetails->su_year=$model['year'];
                            $modeldetails->su_month=$model['month'];
                            $modeldetails->product_id=$each['product_id'];
                            $modeldetails->quantity=$each['quantity'];
                            $modeldetails->amount=$each['amount'];
                            $modeldetails->distributer_id=$each['distributer_id'];
                            $modeldetails->order_id=$each['order_id'];
                            $modeldetails->order_detail_id=$each['order_detail_id'];
                            $modeldetails->created_by =Yii::app()->user->id;
                            $modeldetails->created_date_time =date('Y-m-d H:i:s');
                            $modeldetails->updated_by =Yii::app()->user->id;
                            $modeldetails->updated_date_time =date('Y-m-d H:i:s');
                            $modeldetails->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['UploadSales'];
                    $jsonData['id'] = $model->id;
                    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_dis)){
                        $other[] = "Distributer codes ".implode(',',$arr_dis).' not exists';
                    }
                    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 actionView() {
         if(count($_GET) > 0){
            $model = new UploadSales();
            $id = (int) Yii::app()->request->getParam('id');
            if ($id > 0) {
                $model = $model->findByPk($id);
            }
           $this->render('view_salesform', array('model' => $model));  
         }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
    
    public function actionDelete(){
        $_POST  = filter_input_array(INPUT_POST, FILTER_DEFAULT);
        if(count($_POST)>0){
            $id = (int)$_POST['id'];
            if($id>0){
                $model = new UploadSales();
                //$modelSales = $model->findByPk($id);
                //$month =$modelSales->sales_month;
                //$year =$modelSales->sales_year;
                //$modelOrderDetails=new OrderDetails();
                //$modelOrderDetails->updateAll( array('quantity_shipped' => 0, 'amount_shipped' => 0),'id IN (SELECT order_detail_id FROM ymh_upload_sales_details WHERE sales_upload_id='.$id.')');
                $model->deleteByPk($id);
                $modelItems= new SalesDetails();
                $modelItems->deleteAll('sales_upload_id=:refer_id', array(':refer_id' => $id));
                //$modelOrderDetails=new OrderDetails();
                //$modelOrderDetails->updateAll( array('quantity_shipped' => 0, 'amount_shipped' => 0),'MONTH(order_date)='.$modelSales->month.' AND YEAR(order_date)='.$modelSales->year );
                echo "success";
            } else {
                echo "fail";
            }
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    } 
    
    public function actionGetviewList() {
        $_POST = filter_input_array(INPUT_POST, FILTER_DEFAULT);
        if (count($_POST) > 0) {
            $sales_upload_id = (int)$_POST['order_id'];
            $model = new SalesDetails();
            $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 => 'dis_det.distributer_name',
                4 => 't.sales_quantity',
                5 => 't.amount_in_usd'
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = 'sales_upload_id='.$sales_upload_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 
                         dis_det.distributer_name LIKE '%" . $searchString . "%' OR t.quantity LIKE '%" . $searchString . "%')";
            }
            $count = $model->with('product_det.category_det','product_det','dis_det')->count(array('condition' => $condition));
            $model = $model->with('product_det.category_det','product_det','dis_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['product_det']['gmc_code'], $row['dis_det']['distributer_name'], '<div class="text-right">'.$row['sales_quantity'].'</div>', '<div class="text-right">'.number_format($row['amount_in_usd'],2,'.','').'</div>');
                $m++;
            }
            $data['data'] = $rowData;
            echo json_encode($data);
        } 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){
            $model = new UploadSales();
            $model = $model->findBypk($id); 
            $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.');
        }
    }
    
    public function actionDownloadErrorLog() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_DEFAULT);
        $id = $_GET['id'];
        if ($id>0) {
            $model = UploadSales::model()->findByPk($id);
            
            if (!$model) {
                throw new CHttpException(404, 'Record not found.');
            }
    
            // 1. Clean the data for readability
            // We'll replace the commas with actual new lines for a .txt file
            $content = str_replace(',', "\r\n", $model->comments);
            $content = str_replace('not exists', "NOT EXISTS\r\n", $content);
    
            // 2. Set headers for a Text file download
            $filename = "Error_Log_ID_" . $id . ".txt";
            
            header("Content-type: text/plain");
            header("Content-Disposition: attachment; filename=\"$filename\"");
            header("Pragma: no-cache");
            header("Expires: 0");
    
            echo $content;
            Yii::app()->end();
        } else {
            throw new CHttpException(404, 'Invalid Request.');
        }
    }
}