<?php

class PurchasingOrderController extends Controller
{

    public $layout = 'layout';

    public function accessRules()
    {

        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout', 'Forgotpassword', 'Recover', 'companyFieldDetails'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array(
                    'Index',
                    'Deliverytracker',
                    'Create',
                    'SaveOrder',
                    'GetOrderList',
                    'DeleteDocument',
                    'GetDocumentList',
                    'UploadDocuments',
                    'PrintOrderReportPDF',
                    'DeleteOrderItem',
                    'GetNotesList',
                    'DeleteNotes',
                    'ShortClosure',
                    'GetDeliveryList',
                    'ChangeDate',
                    'SaveDate',
                    'Download',
                    'ItemHistory',
                    'Getunitdrop',
                    'OrderApproval',
                    'SaveApproval',
                    'GetAllProducts',
                    'PurchaseHelper',
                    'StockHelper',
                    'Makeconvert',
                    'UploadDocuments1',
                    'PaymentTracker',
                    'GetPaymentTrackerList',
                    'RemovelineItem',
                    'PrintPurchasingOrderWord',
                    'UploadApplicationHiringTemplates',
                    'DeleteApplicationTemplates',
                    'ConvertToPurchaseOrder',
                    'SaveTracking',
                    'GetTrackingHistory',
                    'CreateTracking',
                    'MovementAnalysis',
                    'GetNewOrderMovementAnalysis',
                    'IndexMovementAnalysis',
                    'CreateMovementAnalysis',
                    'GetNewMovementAnalysisList',
                    'GetMovementAnalysisTableData',
                    'SaveMovementAnalysis',
                    'PrintMovementAnalysisPDF',
                    'EditDeliveryTracker',
                    'UpdateDeliveryTracker',
                    'DeliveryTrackerNotes',
                    'GetDeliveryTrackerNotesList',
                    'GetApprovalHistory',
                    'GetApprovalHistoryList',
                    'getOrderCount'
                ),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function filters()
    {

        return array('accessControl'); // perform access control for CRUD operations
    }

    public function actionUploadDocuments1($folder = null)
    {
        Yii::import("ext.EAjaxUpload.qqFileUploader");

        $field_id = "";
        if (isset($_GET['field_id'])) {
            $field_id = Yii::app()->request->getParam('field_id');
        }

        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';

        // make the directory to store the file
        if (!is_dir($folder)) {
            mkdir($folder, 0777, TRUE);
        }

        $allowedExtensions = array("csv", "png", "txt", "pdf", "doc", "docx", "jpg", "jpeg", "xls");
        $sizeLimit = 2 * 1024 * 1024; // 2 MB

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);

        // 💡 Add date prefix to file name
        if ($result['success']) {
            $originalFile = $result['filename'];
            $datePrefix = date('Y-m-d') . '-';
            $newFileName = $datePrefix . $originalFile;

            $oldPath = $folder . $originalFile;
            $newPath = $folder . $newFileName;

            // Rename the file on the server
            if (file_exists($oldPath)) {
                rename($oldPath, $newPath);
                $result['filename'] = $newFileName;
            }
        }

        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
        $result['field_id'] = $field_id;

        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    }



    public function actionIndex()
    {

        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['purchase_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['purchase_order_view']) &&
                Yii::app()->user->havePermissionOn['purchase_menu_view'] &&
                Yii::app()->user->havePermissionOn['purchase_order_view']
            )
        ) {
            $this->render('index');
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }

    public function actionDeliverytracker()
    {

        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['purchase_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['pur_deliverytrack_view']) &&
                Yii::app()->user->havePermissionOn['purchase_menu_view'] &&
                Yii::app()->user->havePermissionOn['pur_deliverytrack_view']
            )
        ) {
            // Authorized: render the main view
            $this->render('deliverytracker');
        } else {
            // Unauthorized: show custom unauthorized page
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }

    public function actionCreate()
    {

        $model = new PurchasingOrder();
        $enq_id = (int) Yii::app()->request->getParam('enq_id');
        $req_id = (int) Yii::app()->request->getParam('req_id');
        $vendor_id = (int) Yii::app()->request->getParam('vendor_id');
        $file_id = (int) Yii::app()->request->getParam('file_id');
        $id = (int) Yii::app()->request->getParam('id');
        $type = Yii::app()->request->getParam('type');
        $viewtype = Yii::app()->request->getParam('viewtype');
        $temp_id = (int) Yii::app()->request->getParam('temp_id');
        $frm = (int) Yii::app()->request->getParam('frm');
        $project_id = (int) Yii::app()->request->getParam('project_id');
        $modelOrderStockItem = array(new PurchasingOrderStockItem);
        // $modelOrderAdditions = array(new PurchasingOrderAddition);
        // $modelOrderDeduction = array(new PurchasingOrderDeduction);
        //$modelDocument = new Document();
        //$modelNotes = new FileNotes();
       // $modelNotes = array(new FileNotes);
       // $modelDocument = array(new Document());
        if ($id > 0) {
            $model = $model->findByPk($id);
            $modelOrderStockItem = PurchasingOrderStockItem::model()->findAll(array('condition' => 'purchasing_order_id="' . $id . '"'));
            if (empty($modelOrderStockItem)) {
                $modelOrderStockItem = array(new PurchasingOrderStockItem);
            }
            // $modelOrderAdditions = PurchasingOrderAddition::model()->findAll(array('condition' => 'purchasing_order_id="' . $id . '"'));
            // if (empty($modelOrderAdditions)) {
            //     $modelOrderAdditions = array(new PurchasingOrderAddition);
            // }
            // $modelOrderDeduction = PurchasingOrderDeduction::model()->findAll(array('condition' => 'purchasing_order_id="' . $id . '"'));
            // if (empty($modelOrderDeduction)) {
            //     $modelOrderDeduction = array(new PurchasingOrderDeduction);
            // }
            // $modelNotes = FileNotes::model()->findAll(array('condition' => 'file_id="' . $model->file_id . '"'));
            // if (empty($modelNotes)) {
            //     $modelNotes = array(new FileNotes);
            // }
            // $modelDocument = Document::model()->findAll(array('condition' => 'file_id="' . $model->file_id . '"'));
            // if (empty($modelDocument)) {
            //     $modelDocument = array(new Document);
            // }
        } else if ($temp_id > 0) {
            $modeltemp = PurchasingOrdertemp::model()->findByPk($temp_id);
            $model = new PurchasingOrder;
            $model->file_id = $modeltemp->file_id;
            $model->title = $modeltemp->title;
            $model->vendor_id = $modeltemp->vendor_id;
            //SUPPLIER TYPE
            $model_vendor_details = Vendor::model()->findByPk($modeltemp->vendor_id);
            $model->supplier_type = $model_vendor_details->type;
            $model->enquiry_id = $modeltemp->enquiry_id;
            $model->order_date = $modeltemp->order_date;
            $model->required_date = $modeltemp->required_date;
            $model->expected_delivery_date = $modeltemp->expected_delivery_date;
            $model->currency = $modeltemp->currency;
            $model->stock_grand_total = $modeltemp->stock_grand_total;
            $address = VendorShippingDetails::model()->findAll(array('condition' => 'vendor_id = ' . $modeltemp->vendor_id . ' '));
            if (!empty($address)) {
                $model->shipping_address = $address[0]->street_address . PHP_EOL . $address[0]->city . ',' . $address[0]->po_box . PHP_EOL . $address[0]->state . PHP_EOL . $address[0]->country->country_name;
            }
            $modelItem = PurchasingOrderStockItemtemp::model()->findAll(array('condition' => 'purchasing_order_id="' . $temp_id . '"'));
            if (!empty($modelItem)) {
                foreach ($modelItem as $i => $eachItem) {

                    $modelOrderStockItem[$i] = new PurchasingOrderStockItem;
                    $modelOrderStockItem[$i]->stock_item_id = $eachItem->stock_item_id;
                    $modelOrderStockItem[$i]->stock_item_name = $eachItem->product->part_number;
                    $modelOrderStockItem[$i]->stock_item_description = $eachItem->product->description;
                    $modelOrderStockItem[$i]->stock_item_unit = $eachItem->product->unit->symbol;
                    $modelOrderStockItem[$i]->stock_item_quantity = $eachItem->stock_item_quantity;
                    $modelOrderStockItem[$i]->stock_item_rate = $eachItem->stock_item_rate;
                    $modelOrderStockItem[$i]->stock_item_amount = $eachItem->stock_item_amount;
                }
            } else {
                $modelOrderStockItemtemp = array(new PurchasingOrderStockItem);
            }
            $modelOrderAdditions = array(new PurchasingOrderAddition);
            $modelOrderDeduction = array(new PurchasingOrderDeduction);
        } else if ($enq_id > 0) {
            $modelEnquiry = PurchasingEnquiry::model()->findByPk($enq_id);
            $model->title = $modelEnquiry->title;
            $model->enquiry_id = $enq_id;
            foreach ($modelEnquiry->items as $i => $eachItem) {
                $modelOrderStockItem[$i] = new PurchasingOrderStockItem;
                $modelOrderStockItem[$i]->stock_item_id = $eachItem->stock_item_id;
                $modelOrderStockItem[$i]->stock_item_name = $eachItem->stock_item_name;
                $modelOrderStockItem[$i]->stock_item_description = $eachItem->stock_item_description;
                $modelOrderStockItem[$i]->stock_item_unit = $eachItem->stock_item_unit;
                $modelOrderStockItem[$i]->stock_item_quantity = $eachItem->stock_item_quantity;
            }
            $modelNotes = FileNotes::model()->findAll(array('condition' => 'file_id="' . $model->file_id . '"'));
            if (empty($modelNotes)) {
                $modelNotes = array(new FileNotes);
            }
            $modelDocument = Document::model()->findAll(array('condition' => 'file_id="' . $model->file_id . '"'));
            if (empty($modelDocument)) {
                $modelDocument = array(new Document);
            }
        } else if ($req_id > 0) {
            $modelReq = PurchasingRequisition::model()->findByPk($req_id);
            $model->title = $modelReq->file_title;
            $model->req_id = $modelReq->id;
            foreach ($modelReq->stockitems as $i => $eachItem) {
                $modelOrderStockItem[$i] = new PurchasingOrderStockItem;
                $modelOrderStockItem[$i]->stock_item_id = $eachItem->stock_item_id;
                $modelOrderStockItem[$i]->stock_item_name = $eachItem->stock_item_name;
                $modelOrderStockItem[$i]->stock_item_description = $eachItem->stock_item_description;
                $modelOrderStockItem[$i]->stock_item_unit = $eachItem->stock_item_unit;
                $modelOrderStockItem[$i]->stock_item_quantity = $eachItem->stock_item_quantity;
            }
        }
        if ($project_id > 0) {
            // echo 'hii';
            $modelProject = WsProject::model()->findByPk($project_id);
            // var_dump($modelProject->estimationDetails);
            foreach ($modelProject->estimationDetails as $i => $eachItem) {
                // var_dump($eachItem);
                $modelOrderStockItem[$i] = new PurchasingOrderStockItem;
                $modelOrderStockItem[$i]->stock_item_id = $eachItem->product_id;
                // $modelOrderStockItem[$i]->stock_item_rate = $eachItem->rate;
                $modelOrderStockItem[$i]->stock_item_description = $eachItem->description;
                $modelOrderStockItem[$i]->stock_item_unit = $eachItem->unit;
                $modelOrderStockItem[$i]->stock_item_quantity = $eachItem->quantity;
            }
        }
        if ($model->expected_delivery_date != '' && $model->expected_delivery_date != '0000-00-00') {
            $model->expected_delivery_date = date('d/m/Y', strtotime($model->expected_delivery_date));
        } else {
            $model->expected_delivery_date = date('d/m/Y', strtotime('+1 Week'));
        }
        if ($model->required_date != '' && $model->required_date != '0000-00-00') {
            $model->required_date = date('d/m/Y', strtotime($model->required_date));
        } else {
            $model->required_date = date('d/m/Y', strtotime('+1 Week'));
        }
        if ($model->order_date != '') {
            $model->order_date = date('d/m/Y', strtotime($model->order_date));
        } else {
            $model->order_date = date('d/m/Y');
        }

        // die();
        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.min.js' => false);
        $this->render('create', array(
            'model' => $model,
            'file_id' => $file_id,
            'enq_id' => $enq_id,
            'modelEnquiry' => $modelEnquiry,
            'modelOrderStockItem' => $modelOrderStockItem,
           // 'modelDocument' => $modelDocument,
           // 'modelNotes' => $modelNotes,
            // 'modelOrderAdditions' => $modelOrderAdditions,
            // 'modelOrderDeduction' => $modelOrderDeduction,
            'vendor_id' => $vendor_id,
            'type' => $type,
            'viewtype' => $viewtype,
            'temp_id' => $temp_id,
            'project_id' => $project_id,
            'frm' => $frm,
        ));
    }

    public function actionSaveOrder()
    {

        $model = new PurchasingOrder;
        $modelfile = new MasterFile();
        $modelOrderStockItem = array(new PurchasingOrderStockItem);
        //$modelNotes = new FileNotes();
        //$modelDocument = new Document();
        $other = [];
        if (isset($_POST['PurchasingOrder'])) {
            $scenario = '';
            if ((int) $_POST['PurchasingOrder']['id'] > 0) {
                $model = $model->findByPK($_POST['PurchasingOrder']['id']);
                $model->scenario = 'update';
                $scenario = 'update';
                $audit_type = 'UPDATED'; // for audit log changes
            } else {
                $model->created_by = Yii::app()->user->id;
                $model->created_datetime = date('Y-m-d H:i:s');
                $model->convert_status = 'Y';
                $model->scenario = 'add';
                $scenario = 'add';
                $audit_type = 'CREATED'; // for audit log changes
            }
            $model->convert_status = 'Y';
            $model->enquiry_id = $_POST['PurchasingOrder']['enquiry_id'];
            $model->req_id = $_POST['PurchasingOrder']['req_id'];
            $model->updated_by = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d h:i:s');
            $model->attributes = $_POST['PurchasingOrder'];
            $model->start_text = $_POST['PurchasingOrder']['start_text'];
            $model->ticket_id = $_POST['PurchasingOrder']['ticket_id'];
            $model->project_classification_id = $_POST['PurchasingOrder']['project_classification_id'];
            $model->contract_id = $_POST['PurchasingOrder']['contract_id'];
            $model->billing_address=$_POST['PurchasingOrder']['billing_address'];
            //$model->approved_level=3;
            $model->terms_and_conditions = $_POST['PurchasingOrder']['terms_and_conditions'];
            //Code modified by mereena on-10/2/2020 for ckeditor
            //$model->terms_and_conditions = $_POST['terms_and_conditions'];
            //end
            $model->remarks = $_POST['PurchasingOrder']['remarks'];
            $model->notes = $_POST['PurchasingOrder']['notes'];
            $model->currency = $_POST['PurchasingOrder']['currency'];
            $model->crm_user_id = Yii::app()->user->id;
            $model->terms_id = $_POST['PurchasingOrder']['terms_id'];
            if ($_POST['PurchasingOrder']['order_date'] != '00/00/0000' && $_POST['PurchasingOrder']['order_date'] != '') {
                $model->order_date = str_replace('/', '-', $_POST['PurchasingOrder']['order_date']);
                $model->order_date = date("Y-m-d", strtotime($model->order_date));
            }
            if ($_POST['PurchasingOrder']['expected_delivery_date'] != '00/00/0000' && $_POST['PurchasingOrder']['expected_delivery_date'] != '') {
                $model->expected_delivery_date = str_replace('/', '-', $_POST['PurchasingOrder']['expected_delivery_date']);
                $model->expected_delivery_date = date("Y-m-d", strtotime($model->expected_delivery_date));
            }
            if ($_POST['PurchasingOrder']['required_date'] != '00/00/0000' && $_POST['PurchasingOrder']['required_date'] != '') {
                $model->required_date = str_replace('/', '-', $_POST['PurchasingOrder']['required_date']);
                $model->required_date = date("Y-m-d", strtotime($model->required_date));
            }
            $model->file_id = $_POST['hid_file_id'];
            $valid = $model->validate();
            $total_tax_amount = 0;
            $p = 0;
            $arr_service_invoice = array();
            $arr_pdts = [];
            if (!empty($_POST['PurchasingOrderStockItem'])) {
                foreach ($_POST['PurchasingOrderStockItem'] as $k => $rowItem) {
                    if ($rowItem['stock_item_id'] > 0) {
                        //code added by mereena on 16/04/2020
                        $arr_product_details = Store::model()->findByPk($rowItem['stock_item_id']);
                        $arr_service_invoice[] = $arr_product_details->inventory_item_type;
                        //end
                        if (in_array($rowItem['stock_item_id'], $arr_pdts)) {
                            $valid = false;
                            $other[] = 'Product ' . $arr_product_details['part_number'] . ' is duplicated';
                        } else {
                            $arr_pdts[] = $rowItem['stock_item_id'];
                        }
                        $modelOrderStockItem[$p] = new PurchasingOrderStockItem();
                        $modelOrderStockItem[$p]->created_by = Yii::app()->user->id;
                        $modelOrderStockItem[$p]->created_datetime = date('Y-m-d h:i:s');
                        $modelOrderStockItem[$p]->updated_by = Yii::app()->user->id;
                        $modelOrderStockItem[$p]->updated_datetime = date('Y-m-d h:i:s');
                        $modelOrderStockItem[$p]->purchasing_order_id = 0;
                        $modelOrderStockItem[$p]->stock_item_tolerance = $rowItem['stock_item_tolerance'];
                        if ($rowItem['stock_item_tolerance'] == 0 || $rowItem['stock_item_tolerance'] == '') {
                            $modelOrderStockItem[$p]->stock_item_max_qty = $rowItem['stock_item_quantity'];
                        } else {
                            $modelOrderStockItem[$p]->stock_item_max_qty = $rowItem['stock_item_max_qty'];
                        }
                        $modelOrderStockItem[$p]->stock_item_id = $rowItem['stock_item_id'];
                        if ($rowItem['expected_delivery_date'] != '') {
                            $modelOrderStockItem[$p]->expected_delivery_date = date("Y-m-d", strtotime(str_replace('/', '-', $rowItem['expected_delivery_date'])));
                        }
                        $modelOrderStockItem[$p]->stock_item_quantity = str_replace(",", "", $rowItem['stock_item_quantity']);
                        $modelOrderStockItem[$p]->stock_item_name = $rowItem['stock_item_name'];
                        $modelOrderStockItem[$p]->stock_item_description = $rowItem['stock_item_description'];
                        $modelOrderStockItem[$p]->stock_item_unit = $rowItem['stock_item_unit'];

                        $modelOrderStockItem[$p]->stock_item_rate = str_replace(",", "", $rowItem['stock_item_rate']);
                        $modelOrderStockItem[$p]->stock_item_amount = str_replace(",", "", $rowItem['stock_item_amount']);
                        $modelOrderStockItem[$p]->tax_percentage = str_replace(",", "", $rowItem['tax_percentage']);
                        $modelOrderStockItem[$p]->tax_amount = str_replace(",", "", $rowItem['tax_amount']);
                        $total_tax_amount += (int) str_replace(",", "", $rowItem['tax_amount']);
                        $stockgrand_total += str_replace(",", "", $rowItem['stock_item_amount']);
                        $valid = $modelOrderStockItem[$p]->validate() && $valid;
                        $p++;
                    }
                }
                if ($modelOrderStockItem[0]->stock_item_id == '')
                    $valid = false;
            }
            //code added by mereena on 16/04/2020
            $service_invoice = 'N';
            if (in_array(1, $arr_service_invoice)) {
                $service_invoice = "N";
            } else {
                $service_invoice = "Y";
            }
            $model->service_invoice = $service_invoice;
            //end
            /* if (!empty($_POST['PurchasingOrderAddition'])) {

              foreach ($_POST['PurchasingOrderAddition'] as $k => $rowItem) {

              if( $rowItem['particular'] > 0 ){

              $modelPurchasingOrderAddition[$k] = new PurchasingOrderAddition();
              $modelPurchasingOrderAddition[$k]->created_by = Yii::app()->user->id;
              $modelPurchasingOrderAddition[$k]->created_datetime = date('Y-m-d h:i:s');
              $modelPurchasingOrderAddition[$k]->updated_by = Yii::app()->user->id;
              $modelPurchasingOrderAddition[$k]->updated_datetime = date('Y-m-d h:i:s');
              $modelPurchasingOrderAddition[$k]->purchasing_order_id = 0;
              $modelPurchasingOrderAddition[$k]->particular_value  = $rowItem['particular_value'];
              $modelPurchasingOrderAddition[$k]->calculated_value = $rowItem['calculated_value'];
              $modelPurchasingOrderAddition[$k]->particular   = $rowItem['particular'];
              $nonstock_grandtotal += $rowItem['calculated_value'];
              $valid = $modelPurchasingOrderAddition[$k]->validate() && $valid;
              }
              }
              }
              if (!empty($_POST['PurchasingOrderDeduction'])) {

              foreach ($_POST['PurchasingOrderDeduction'] as $k => $rowItem) {

              if( $rowItem['particular'] > 0 ){
              $modelPurchasingOrderDeduction[$k] = new PurchasingOrderDeduction();
              $modelPurchasingOrderDeduction[$k]->created_by = Yii::app()->user->id;
              $modelPurchasingOrderDeduction[$k]->updated_by = Yii::app()->user->id;
              $modelPurchasingOrderDeduction[$k]->updated_datetime = date('Y-m-d h:i:s');
              $modelPurchasingOrderDeduction[$k]->purchasing_order_id = 0;
              $modelPurchasingOrderDeduction[$k]->particular_value  = $rowItem['particular_value'];
              $modelPurchasingOrderDeduction[$k]->calculated_value = $rowItem['calculated_value'];
              $modelPurchasingOrderDeduction[$k]->particular   = $rowItem['particular'];
              $nonstock_grandtotal -= $rowItem['calculated_value'];
              $valid = $modelPurchasingOrderDeduction[$k]->validate() && $valid;
              }
              }
              } */


            if ($valid) {

                if (!$model->isNewRecord) {
                    MasterFile::model()->updateByPk($model->file_id, array('is_approved' => 'N', 'approved_by' => 0, 'current_process_status' => "P_O", 'date_of_approval' => '0000-00-00'));
                    //MasterFile::model()->updateByPk($model->file_id, array('is_approved' => "Y",'approved_by'=>Yii::app()->user->id,'date_of_approval'=>date('Y-m-d'),'current_process_status'=>"P_O"));

                    $modelfile->id = $model->file_id;
                } else {
                    $modelfile->start_from = "P_O";
                    $modelfile->crm_user_id = Yii::app()->user->id;
                    $modelfile->customer_id = $model->vendor_id;
                    $modelfile->file_title = $model->title;
                    $modelfile->current_process_status = "P_O";
                    $modelfile->is_approved = "N";
                    $modelfile->approved_by = 0;
                    $modelfile->date_of_approval = date('Y-m-d');
                    $modelfile->save(false);
                    $model->file_id = $modelfile->id;
                }
                /*                 * *********************************************** */
                if ($_POST['hid_action_type'] == 2) {
                    date_default_timezone_set("Asia/Dubai");
                    $approval_history = new ApprovalHistory;
                    $approval_history->file_id = $modelfile->id;
                    $approval_history->status = "Y";
                    $approval_history->action_by = Yii::app()->user->id;
                    $approval_history->created_by = Yii::app()->user->id;
                    $approval_history->created_datetime = date('Y-m-d H:i:s');
                    $approval_history->date = date('Y-m-d H:i:s');
                    $approval_history->state = 'PO';
                    $approval_history->save();
                }

                /*                 * ************************end********************* */

                if ($model->save()) {
                    // inserting to audit log
                    AuditLog::saveAuditLogs(
                        'PURCHASE_ORDER',
                        Yii::app()->user->id,
                        $audit_type,
                        " PO ID - {$model->id} "
                    );
                    // end audit log
                    $order_id = $model->id;
                    PurchasingOrderStockItem::model()->deleteAll('purchasing_order_id=:refer_id', array(':refer_id' => $order_id));

                    if (!empty($modelOrderStockItem)) {
                        foreach ($modelOrderStockItem as $eachItem) {
                            $eachItem->purchasing_order_id = $model->id;
                            $eachItem->save(false);
                        }
                    }

                    // PurchasingOrderAddition::model()->deleteAll('purchasing_order_id=:refer_id', array(':refer_id' => $order_id));
                    // if (!empty($modelPurchasingOrderAddition)) {
                    //     foreach ($modelPurchasingOrderAddition as $eachItem) {
                    //         $eachItem->purchasing_order_id = $model->id;
                    //         $eachItem->save(false);
                    //     }
                    // }

                    // PurchasingOrderDeduction::model()->deleteAll('purchasing_order_id=:refer_id', array(':refer_id' => $order_id));
                    // if (!empty($modelPurchasingOrderDeduction)) {
                    //     foreach ($modelPurchasingOrderDeduction as $eachItem) {
                    //         $eachItem->purchasing_order_id = $model->id;
                    //         $eachItem->save(false);
                    //     }
                    // }
                    if (is_array($_POST['Document'])) {
                        //Document::model()->deleteAll('file_id=:refer_id', array(':refer_id' => $modelfile->id));
                        foreach ($_POST['Document'] as $i => $each) {
                            if (!empty($each['document_name']) or !empty($each['document_actual_file_name'])) {
                                if ($each['id'] > 0) {
                                    $modelDocument = Document::model()->findByPK($each['id']);
                                } else {
                                    $modelDocument = new Document;
                                }
                                $modelDocument->attributes = $each;
                                $modelDocument->document_name = $each['document_name'];
                                $modelDocument->document_actual_file_name = $each['document_actual_file_name'];
                                $modelDocument->file_id = $modelfile->id;
                                $modelDocument->created_by = Yii::app()->user->id;
                                $modelDocument->created_datetime = date('Y-m-d h:i:s');
                                $modelDocument->save(false);
                            }
                        }
                    }
                    /*if(!empty($_POST['FileNotes'])){
                    FileNotes::model()->deleteAll('file_id=:refer_id', array(':refer_id' => $modelfile->id));
                    foreach( $_POST['FileNotes'] as $i => $each ){
                    if(!empty($each['notes'])){
                    $modelNotes = new FileNotes();
                    $modelNotes->attributes = $each;
                    $modelNotes->notes = $each['notes'];
                    $modelNotes->crm_user_id = Yii::app()->user->id;
                    $modelNotes->customer_vendor_id = $model->vendor_id;
                    $modelNotes->customer_vendor_type=2;
                    $modelNotes->file_note_from=1;
                    $modelNotes->file_id=$modelfile->id;
                    $modelNotes->created_by = Yii::app()->user->id;
                    $modelNotes->created_datetime = date('Y-m-d h:i:s');
                    $modelNotes->save(false);
                    }
                    }
                    } */
                    // if ($scenario == 'add') {
                    //     // $model_mail_setting = Notification::model()->find(array('condition' => 'event_id="13"'));
                    //     // Yii::import('application.controllers.front.MasternotificationController');
                    //     // if ($model_mail_setting->mail_required == 'Y') {
                    //     //     // MasternotificationController::sendmail(13,$model->id);
                    //     // }
                    //     // if ($model_mail_setting->notification_required == 'Y') {
                    //     //     // MasternotificationController::sendnotification(13,$model->id);
                    //     // }
                    //     // if ($model_mail_setting->sms_required == 'Y') {
                    //     //     // MasternotificationController::sendsms(13,$model->id);
                    //     // }
                    // }
                }
                /* if ($_POST['FileNotes']['notes']!='')
                  {
                  if ((int) @$_POST['FileNotes']['id'] > 0)
                  {
                  $notes_id = (int) @$_POST['FileNotes']['id'];
                  $modelNotes = $modelNotes->findByPk($notes_id);
                  $modelNotes->updated_by = Yii::app()->user->id;
                  $modelNotes->updated_datetime = date('Y-m-d h:i:s');
                  }
                  else
                  {
                  $modelNotes->created_by = Yii::app()->user->id;
                  $modelNotes->created_datetime = date('Y-m-d h:i:s');
                  }
                  $modelNotes->notes=$_POST['FileNotes']['notes'];
                  $modelNotes->crm_user_id = Yii::app()->user->id;
                  $modelNotes->customer_vendor_id = $model->vendor_id;
                  $modelNotes->customer_vendor_type=2;
                  $modelNotes->file_note_from=1;
                  $modelNotes->file_id=$modelfile->id;
                  $modelNotes->attributes = $_POST['FileNotes'];
                  $modelNotes->save(false);
                  } */
                /* if($_POST['Icon']['file'] != ''){
                  if(implode(',', $_POST['Icon']['file'])!='')
                  {
                  if ((int) @$_POST['Document']['id'] > 0) {
                  $doc_id = (int) @$_POST['Document']['id'];
                  $modelDocument = Document::model()->findByPk($doc_id);
                  $modelDocument->updated_by = Yii::app()->user->id;
                  $modelDocument->updated_datetime = date('Y-m-d h:i:s');
                  $arr_doc_photos = $_POST['Icon']['file'];
                  if (!empty($arr_doc_photos)) {
                  Document::model()->updateByPk($modelDocument->id, array('document_name' => 'JA'));
                  }
                  }
                  else
                  {
                  $modelDocument = new Document;
                  $arr_doc_photos = $_POST['Icon']['file'];
                  if (!empty($arr_doc_photos)) {
                  $modelDocument->uploaded_from =  "P_O";
                  }
                  $modelDocument->file_id = $model->file_id;
                  $modelDocument->created_by = Yii::app()->user->id;
                  $modelDocument->created_datetime = date('Y-m-d h:i:s');
                  }
                  $modelDocument->document_name = implode(',', $arr_doc_photos);
                  $modelDocument->save(false);
                  }
                  } */
                $stockgrand_total += $total_tax_amount;
                $model->updateByPk($model->id, array('stock_grand_total' => $stockgrand_total, 'total_tax_amount' => $total_tax_amount));
                $model->updateByPk($model->id, array('nonstock_grandtotal' => $nonstock_grandtotal));
                MasterFile::model()->updateByPk($file_id, array('current_process_status' => "P_O"));

                $jsonData['id'] = $model->id;
                $jsonData['file_id'] = $model->file_id;
                $jsonData['order'] = $model->findByPk($model->id);
                $jsonData['status'] = 'success';
                echo CJSON::encode($jsonData);
            } else {
                $error1 = $error2 = $error3 = $error4 = array();
                $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                if ($modelOrderStockItem[0]->stock_item_id != '')
                    $error2 = json_decode(CActiveForm::validateTabular($modelOrderStockItem, '', false), true);
                else
                    $error2[] = "Please add atleast one stock item";
                if (!empty($modelPurchasingOrderAddition))
                    $error3 = json_decode(CActiveForm::validateTabular($modelPurchasingOrderAddition, '', false), true);
                if (!empty($modelPurchasingOrderDeduction))
                    $error4 = json_decode(CActiveForm::validateTabular($modelPurchasingOrderDeduction, '', false), true);
                ////if ($modelNonStock[0]->non_stock_item_name!='')
                //$error3 = json_decode(CActiveForm::validateTabular($modelNonStock, '', false), true);
                $error = CJSON::encode(array_merge_recursive($error4, $error3, $error2, $error1, $other));
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionDownload()
    {
        $filename = Yii::app()->request->getparam('filename');
        $path = Yii::getPathOfAlias('webroot') . "/uploads/documents/" . $filename;
        if (!empty($path)) {
            header("Content-type:application/force-download"); //for txt file
            header('Content-Disposition: attachment; filename="' . basename($path) . '"');
            header('Content-Length: ' . filesize($path));
            readfile($path);
            Yii::app()->end();
        }
    }

    public function actionGetOrderList()
    {

        $model = new PurchasingOrder();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $frm = $_POST['frm'];

        $columns = array(
            // datatable column index  => database column name
            0 => 't.file_id',
            1 => 't.id',
            2 => 'vendor_details.vendor_name',
            3 => 't.order_date', 
            4 => 'currencyname.currency_code',
            5 => 't.stock_grand_total',
            6 => 'file.current_process_status',
            7 => 't.convert_status',
        );

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

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

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

        $condition = "((file.current_process_status = 'P_O' OR t.convert_status = 'Y')  AND completed!='C')";
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

            $searchString = $_POST['search']['value'];

            $condition = " (t.id LIKE '%" . $searchString . "%' OR t.file_id LIKE '%" . $searchString . "%' OR t.title LIKE '%" . $searchString . "%' OR t.required_date LIKE '%" . $searchString . "%' OR t.order_date LIKE '%" . $searchString . "%' OR t.stock_grand_total LIKE '%" . $searchString . "%' OR vendor_details.vendor_name LIKE '%" . $searchString . "%')";
        }
        /* if (!(Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["other_view_international_products"] ))) {
          $condition .= " AND nonlocal_qty=0";
          } */

        $sql = "SELECT t.id,t.project_ids,t.project_classification_id,t.ticket_id,t.file_id,t.title,t.order_date,t.required_date,t.expected_delivery_date,t.completed,t.stock_grand_total,t.nonstock_grandtotal,t.exchange_rate,t.convert_status,
                t.vendor_id,t.service_invoice,t.vendor_contact_id,t.created_by,currencyname.currency_code,vendor_details.vendor_name,t.approved_level,
                file.current_process_status,file.is_approved,IFNULL(A.nonlocal_qty,0) AS nonlocal_qty
                FROM `erp_purchasing_order` t
                LEFT JOIN
                (SELECT purchasing_order_id,IFNULL(COUNT(S.id),0) AS nonlocal_qty FROM erp_purchasing_order_stock_item PEI
                LEFT JOIN erp_store S ON (PEI.stock_item_id =S.id) GROUP BY purchasing_order_id)A
                ON t.id = A.purchasing_order_id
                LEFT JOIN {{master_file}} file ON file.id=t.file_id
                LEFT JOIN {{vendor}} vendor_details ON vendor_details.id=t.vendor_id
                LEFT JOIN {{mas_currency}} currencyname ON currencyname.id=t.currency
                WHERE A.purchasing_order_id=t.id";
        $SQL1 = $sql . " AND ($condition) ORDER BY " . $orderBy . " LIMIT $offset,$limit";
        //echo $SQL1;
        $model = Yii::app()->db->createCommand($SQL1)->queryAll();
        $SQL_CNT = "SELECT COUNT(*) FROM(" . $sql . " AND ($condition) ORDER BY " . $orderBy . ")B";
        $count = Yii::app()->db->createCommand($SQL_CNT)->queryScalar();

        //$count = Yii::app()->db->createCommand($SQL1)->queryScalar();

        /* $count = $model->with('file','vendor_details','user')->count(array('condition' => $condition));

          $model = $model->with('file','vendor_details','user')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset,'order'=>'t.id DESC')); */

        $recordsTotal = $count;

        $recordsFiltered = $count;

        $data['draw'] = $draw;

        $data['recordsTotal'] = $recordsTotal;

        $data['recordsFiltered'] = $recordsFiltered;

        $rowData = array();

        $i = 1;
        foreach ($model as $row) {
            $order_date = date("d/m/Y", strtotime($row['order_date']));
            $required_date = date("d/m/Y", strtotime($row['expected_delivery_date']));
            if ($row['nonlocal_qty'] == 0) {
                $ptype = 'L';
            } else {
                $ptype = 'I';
            }
            if ($row['current_process_status'] == 'P_O') {
                $status = 'Order';
            } else if ($row['current_process_status'] == 'M_R') {
                $status = 'Material Reciept';
            } else if ($row['current_process_status'] == 'Q_C') {
                $status = 'Quality Checked';
            } else if ($row['current_process_status'] == 'P_I') {
                $status = 'Invoice';
            } else {
                $status = '';
            }
            if ($row['completed'] == 'P') {
                $status = 'Material Reciept (Partial)';
            }
            if ($row['completed'] == 'C') {
                $status = 'Short Closure';
            }

            $state = 0;
            if (strtotime($row['required_date']) < strtotime(date('Y-m-d'))) {
                $state = 1;
            } elseif ($row['is_approved'] == 'N') {
                $state = 2;
            }
            $created_user = User::model()->findByPK($row['created_by'])->fullname;
            $grand_total = $row['stock_grand_total'] + $row['nonstock_grandtotal'];
            $grand_total_bc = ($grand_total * $row['exchange_rate']);
            //$project_details = WsProject::model()->findByPK($row['project_ids'])->project_name;
            $rowData[] = array(
                $row['file_id'],//0
                $row['id'], //1
               // $project_details . ' - ' . $row['project_ids'],//2
                $row['vendor_name'], //3
                $order_date, //4
               // $required_date, //5
                $row['currency_code'], //6
                Yii::app()->numberFormatter->formatCurrency($grand_total, ""),//7
                Yii::app()->numberFormatter->formatCurrency($grand_total_bc, ""),//8
                $status, //9
                $state, //10
                $row['is_approved'], //11
                //$row['approved_level'], //11
                $row['convert_status'], //12
                $row['completed'], //13
                $row['vendor_id'], //14
                $row['service_invoice'], //15
                $row['vendor_contact_id'], //16
                $created_user, //17
                $ptype,//18
                $row['approved_level'],//19
                $row['current_process_status']//20
            );
            $i++;
        }

        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionDeleteDocument()
    {
        $id = $_POST['id'];
        $modelDocument = new Document();
        $model_doc = Document::model()->findbyPK($id);
        $document_details = explode(',', $model_doc->document_name);
        foreach ($document_details as $value) {
            $path = Yii::getPathOfAlias('webroot') . "/uploads/documents/" . $value;
            unlink($path);
        }
        $modelDocument->deleteByPk($id);
        echo "success";
    }

    public function actionGetDocumentList()
    {
        $model = new Document();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $file_id = $_POST['file_id'];
        $columns = array(
            // datatable column index  => database column name
            0 => 't.file_id',
            1 => 't.document_name',
            2 => 't.created_by',
            3 => 't.created_datetime',
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.isActive="Y" and (t.file_id = "' . $file_id . '" AND t.file_id > 0)';
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " and (document_name LIKE '%" . $searchString . "%' OR file_id 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) {
            $model2 = User::model()->find(array('condition' => 't.id = "' . $row['created_by'] . '"'));
            $button_string = ' <a href ="' . Yii::app()->createUrl("purchasingorder/download") . '&filename=' . $row['document_name'] . ' " class="btn btn-primary btn-xs"><i class="fa fa-download" title="Download"></i></a>';
            if (isset(Yii::app()->user->havePermissionOn['allow_delete_document']) || Yii::app()->user->authorised_user == 1) {
                $button_string .= ' <a href ="#" class="btn btn-danger btn-xs" onclick="deleteDocument(' . $row['id'] . ')"><i class="fa fa-trash-o "></i></a> ';
            }

            $rowData[] = array($m, $row['document_name'], $model2->username, date("d/m/Y h:m:s", strtotime($row['created_datetime'])), '<div class="btn-wrap text-center">' . $button_string . '</div>');
            $m++;
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionGetNotesList()
    {
        $id = $_POST['id'];
        $model = new FileNotes();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'id',
            1 => 'notes',
            2 => 'created_datetime',
            3 => 'id'
        );

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

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

        $orderBy = $filterColumn . " " . $filterOrder;
        if ($id == '') {
            $id = 0;
        }
        $condition = 't.file_id="' . $id . '"';
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

            $searchString = $_POST['search']['value'];

            $condition .= " and (notes 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) {

            $rowData[] = array(
                $m,
                $row->notes,
                date('d/m/Y', STRTOTIME($row->created_datetime)),
                '<div class="btn-wrap">
                            <a href ="#" class="btn btn-danger btn-xs" onclick="deleteNotes(' . $row['id'] . ')"><i class="fa fa-trash-o "></i></a></div>'
            );

            $m++;
        }

        $data['data'] = $rowData;

        echo json_encode($data);
    }

    public function actionPrintOrderReportPDF()
    {
        $model = new PurchasingOrder();
        $id = Yii::app()->request->getParam('id');
        $frm = Yii::app()->request->getParam('frm');
        $mPDF1 = Yii::app()->ePdf->mpdf('', 'A4');
        if ($id > 0) {
            $model = PurchasingOrder::model()->findByPk($id);
            if ($model->file->is_approved == 'N') {
                $mPDF1->SetWatermarkText('NOT APPROVED');
                $mPDF1->showWatermarkText = true;
            }
        }
        /* $mPDF1->SetWatermarkImage('images/watermark.jpg');
          //$mPDF1->showWatermarkImage = true; */
        $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/pdf_style.css');
        $mPDF1->WriteHTML($stylesheet, 1);
        $mPDF1->WriteHTML($this->renderPartial('application.views.front.pdf.purchase_order_list_individual', array('model' => $model, 'id' => $id, 'frm' => $frm, 'title' => $title), true));
        $mPDF1->Output("PurchaseOrder.pdf", 'I');
    }

    public function actionDeleteOrderItem()
    {
        $id = $_POST['id'];
        $model = new PurchasingOrderStockItem();
        $model->deleteByPk($id);
        $jsonData['status'] = 'success';
        $jsonData['id'] = $id;
        echo CJSON::encode($jsonData);
    }

    public function actionDeleteNotes()
    {
        $id = $_POST['id'];
        $model = new FileNotes();
        $model->deleteByPk($id);
        echo "success";
    }

    public function actionShortClosure()
    {
        $id = $_POST['PurchasingOrder']['id'];
        if ($id > 0) {
            $model = PurchasingOrder::model()->findByPk($id);
            $model->completed = 'C';
            $model->convert_status = 'N';
            //Code added by mereena on-10/2/2020 for ckeditor
            $model->terms_and_conditions = $_POST['terms_and_conditions'];
            //end
            if ($model->save()) {
                if (is_array($_POST['PurchasingOrderStockItem'])) {
                    foreach ($_POST['PurchasingOrderStockItem'] as $item) {
                        if ($item['id'] > 0) {
                            $modelItem = PurchasingOrderStockItem::model()->findByPk($item['id']);
                            $modelItem->notes = $item['notes'];
                            $modelItem->received = $item['received'];
                            $modelItem->remaining_qty = $item['remaining_qty'];
                            $modelItem->save(false);
                        }
                    }
                }
            }
        }
        $jsonData['status'] = 'success';
        echo CJSON::encode($jsonData);
    }

    public function actionGetDeliveryList()
    {
        $model = new PurchasingOrderStockItem();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];

        $condition = "C.stock_item_quantity != 0";

        if (!empty($_POST['search']['value'])) {
            $searchString = $_POST['search']['value'];
            $condition .= " AND ( vendor_name LIKE '%" . $searchString . "%' 
                         OR purchasing_order_id LIKE '%" . $searchString . "%' 
                         OR stock_item_name LIKE '%" . $searchString . "%' 
                         OR expected_delivery_date LIKE '%" . $searchString . "%')";
        }

        $model_settings = MasCompanySettings::model()->find();
        $qualitycontrol = $model_settings->qualitycontrol;
        $stockupdate = $model_settings->stock_updates_on;

        if ($stockupdate == "PI") {
            $sql_quantity = 'SELECT IFNULL(SUM(quantity),0) as quantity, order_item_id
                         FROM erp_purchasinginvoice_item GROUP BY order_item_id';
        } else {
            $sql_quantity = ($qualitycontrol == "Y")
                ? 'SELECT IFNULL(SUM(qc_checked_quantity),0) as quantity, order_item_id
               FROM erp_purchasing_material_receipt_item GROUP BY order_item_id'
                : 'SELECT IFNULL(SUM(received_quantity),0) as quantity, order_item_id
               FROM erp_purchasing_material_receipt_item GROUP BY order_item_id';
        }

        $sql = 'SELECT * FROM (
                SELECT 
                    (A.stock_item_quantity - IFNULL(B.quantity, 0)) AS stock_item_quantity,
                    A.id, purchasing_order_id, stock_item_name, stock_item_description,
                    stock_item_unit, A.expected_delivery_date, PO.file_id, 
                    V.vendor_name, PO.convert_status, PO.completed,
                    UOM.name AS unit_name
                FROM erp_purchasing_order_stock_item A
                INNER JOIN erp_purchasing_order PO ON PO.id = A.purchasing_order_id
                INNER JOIN erp_vendor V ON PO.vendor_id = V.id
                LEFT JOIN erp_unit_of_measurement UOM ON UOM.id = stock_item_unit
                LEFT JOIN (' . $sql_quantity . ') B ON A.id = B.order_item_id
                WHERE PO.completed NOT IN ("C", "Y")
            ) C
            WHERE ' . $condition . '
            ORDER BY expected_delivery_date DESC
            LIMIT ' . $offset . ', ' . $limit;

        $rows = Yii::app()->db->createCommand($sql)->queryAll();

        $rowData = [];
        foreach ($rows as $i => $row) {
            $order_date = ($row['expected_delivery_date'] == '0000-00-00') ? '' : date("d/m/Y", strtotime($row['expected_delivery_date']));
            $flag = ($row['expected_delivery_date'] != '0000-00-00' && $row['expected_delivery_date'] < date('Y-m-d')) ? 1 : 0;

            $rowData[] = [
                $i + 1,
                $row['purchasing_order_id'],
                $row['vendor_name'],
                $row['stock_item_name'],
                $row['stock_item_description'],
                '<div class="text-right">' . $row['stock_item_quantity'] . '</div>',
                $row['unit_name'],
                $order_date,
                '', // no action buttons
                $flag,
                $row['id'],            // index 10
                $row['file_id'],       // index 11
                $row['convert_status'] // index 12
            ];
        }

        echo json_encode([
            'draw' => $draw,
            'recordsTotal' => count($rows),
            'recordsFiltered' => count($rows),
            'data' => $rowData
        ]);
    }


    public function actionChangeDate()
    {
        $id = Yii::app()->request->getParam('id');
        $frm = Yii::app()->request->getParam('frm');
        if ($id > 0) {
            $dateModel = PurchasingOrderStockItem::model()->findBypk($id);
            $dateModel->expected_delivery_date = date("d/m/Y", strtotime($dateModel->expected_delivery_date));
        }
        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.min.js' => false);
        $this->render('change_date', array('model' => $dateModel, 'frm' => $frm));
    }

    public function actionSaveDate()
    {
        $id = $_POST['PurchasingOrderStockItem']['id'];
        if ($id > 0) {
            PurchasingOrderStockItem::model()->updateByPk($id, array('expected_delivery_date' => date("Y-m-d", strtotime(str_replace('/', '-', $_POST['PurchasingOrderStockItem']['expected_delivery_date'])))));
            $jsonData['status'] = 'success';
        } else {
            $jsonData['status'] = 'error';
        }
        echo CJSON::encode($jsonData);
    }

    public function actionItemHistory()
    {
        $vendor = $_POST['vendor_id'];
        $product = $_POST['product_id'];
        $order_id = $_POST['order_id'];
        $jsonData = array();
        if ($product > 0 && $vendor > 0) {
            $condition_1 = 'stock_item_id= ' . $product . ' AND purchaseorder.vendor_id = ' . $vendor;
            if ($order_id > 0)
                $condition_1 .= ' AND purchaseorder.id < ' . $order_id;
            $condition_2 = 'stock_item_id= ' . $product . ' AND purchaseorder.vendor_id != ' . $vendor;
            if ($order_id > 0)
                $condition_2 .= ' AND purchaseorder.id < ' . $order_id;
            $modelOrder = PurchasingOrderStockItem::model()->with('purchaseorder')->findAll(array('condition' => $condition_1, 'limit' => 3, 'order' => 't.id desc'));
            $modelOrderAll = PurchasingOrderStockItem::model()->with('purchaseorder')->findAll(array('condition' => $condition_2, 'limit' => 3, 'order' => 't.id desc'));
            if (empty($modelOrder) && empty($modelOrderAll)) {
                $jsonData['table'] = '
                    <table class="table table-sm table-theme table-bordered">
                              <thead>
                                <tr>
                                  <th>Vendor</th>
                                  <th>Order Number</th>
                                  <th>Date</th>
                                  <th>Price</th>
                                  <th>Unit</th>

                                </tr>
                              </thead>
                              <tbody>
                                <tr">
                                  <td colspan="5" class="text-center">No History</td>
                                </tr>
                              </tbody>
                    </table>';
            } else {
                $jsonData['table'] = '
                    <table class="table table-sm table-theme table-bordered">
                              <thead>
                                <tr>
                                    <th>Vendor</th>
                                    <th>Order Number</th>
                                    <th>Date</th>
                                    <th>Price</th>
                                    <th>Unit</th>
                                </tr>
                              </thead>
                              <tbody>';
                if (!empty($modelOrder)) {
                    foreach ($modelOrder as $each) {
                        $jsonData['table'] .= '<tr>
                                                <td>' . $each->purchaseorder->vendor_details->vendor_name . '</td>
                                                <td class="text-right">' . $each->purchaseorder->id . '</td>
                                                <td class="text-right">' . date_format(date_create($each->purchaseorder->order_date), 'd/m/Y') . '</td>
                                                <td class="text-right">' . $each->stock_item_rate . '</td>
                                                <td class="text-right">' . $each->unitdetails->name . '</td>
                                            </tr>';
                    }
                }
                if (!empty($modelOrderAll)) {
                    if (!empty($modelOrderAll)) {
                        foreach ($modelOrderAll as $each) {
                            $jsonData['table'] .= '<tr class="bg-success">
                                                        <td>' . $each->purchaseorder->vendor_details->vendor_name . '</td>
                                                        <td class="text-right">' . $each->purchaseorder->id . '</td>
                                                        <td class="text-right">' . date_format(date_create($each->purchaseorder->order_date), 'd/m/Y') . '</td>
                                                        <td class="text-right">' . $each->stock_item_rate . '</td>
                                                        <td class="text-right">' . $each->unitdetails->name . '</td>
                                                  </tr>';
                        }
                    }
                }
                $jsonData['table'] .= '</tbody>
                        </table>';
            }
        }
        echo CJSON::encode($jsonData);
    }

    /* modified by jisha since iscountable not working-- 24/03/23 */

    public function actionGetunitdrop()
    {
        $row = $_POST['row_field'];
        $product_id = (int) $_POST['product_id'];
        $drop = array();
        $modelOrder = new PurchasingOrderStockItem;
        // $modelUOM = new UnitOfMeasurement();
        // if ($product_id > 0) {

        //     //code added by mereena on 07/09/2022 to get default purchase unit_id
        //     $modelStore = new Store();
        //     $modelStore = $modelStore->findByPk($product_id);
        //     //end

        //     $modelOrder->stock_item_unit = $modelUOM->getSecondaryBaseunit($product_id);

        //     $drop['drop'] = CHtml::activedropdownlist($modelOrder, "[" . $row . "]stock_item_unit", $modelUOM->getUnits($product_id), array('class' => 'unit go'));
        // }
        echo CJSON::encode($drop);
    }

    /* end */

    public function actionOrderApproval()
    {
        $model = new PurchasingOrder();
        $file_id = (int) Yii::app()->request->getParam('file_id');
        $id = (int) Yii::app()->request->getParam('id');
        $modelOrderStockItem = array(new PurchasingOrderStockItem);
        // $modelOrderAdditions = array(new PurchasingOrderAddition);
        // $modelOrderDeduction = array(new PurchasingOrderDeduction);
        //$modelDocument = new Document();
        //$modelNotes = new FileNotes();
        //$modelNotes = array(new FileNotes);
        //$modelDocument = array(new Document());
        if ($id > 0) {
            $model = $model->findByPk($id);
            $modelOrderStockItem = PurchasingOrderStockItem::model()->findAll(array('condition' => 'purchasing_order_id="' . $id . '"'));
            if (empty($modelOrderStockItem)) {
                $modelOrderStockItem = array(new PurchasingOrderStockItem);
            }
            // $modelOrderAdditions = PurchasingOrderAddition::model()->findAll(array('condition' => 'purchasing_order_id="' . $id . '"'));
            // if (empty($modelOrderAdditions)) {
            //     $modelOrderAdditions = array(new PurchasingOrderAddition);
            // }
            // $modelOrderDeduction = PurchasingOrderDeduction::model()->findAll(array('condition' => 'purchasing_order_id="' . $id . '"'));
            // if (empty($modelOrderDeduction)) {
            //     $modelOrderDeduction = array(new PurchasingOrderDeduction);
            // }

            // $modelNotes = FileNotes::model()->findAll(array('condition' => 'file_id="' . $model->file_id . '"'));
            // if (empty($modelNotes)) {
            //     $modelNotes = array(new FileNotes);
            // }
            // $modelDocument = Document::model()->findAll(array('condition' => 'file_id="' . $model->file_id . '"'));
            // if (empty($modelDocument)) {
            //     $modelDocument = array(new Document);
            // }
        }
        if ($model->expected_delivery_date != '' && $model->expected_delivery_date != '0000-00-00') {
            $model->expected_delivery_date = date('d/m/Y', strtotime($model->expected_delivery_date));
        } else {
            $model->expected_delivery_date = date('d/m/Y', strtotime('+5 days'));
        }
        if ($model->required_date != '' && $model->required_date != '0000-00-00') {
            $model->required_date = date('d/m/Y', strtotime($model->required_date));
        } else {
            $model->required_date = date('d/m/Y', strtotime('+1 Week'));
        }
        if ($model->order_date != '') {
            $model->order_date = date('d/m/Y', strtotime($model->order_date));
        } else {
            $model->order_date = date('d/m/Y');
        }
        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.min.js' => false);
        $this->render('approval', array(
            'model' => $model,
            'file_id' => $file_id,
            'enq_id' => $enq_id,
            'modelEnquiry' => $modelEnquiry,
            'modelOrderStockItem' => $modelOrderStockItem,
           // 'modelDocument' => $modelDocument,
           // 'modelNotes' => $modelNotes,
            // 'modelOrderAdditions' => $modelOrderAdditions,
            // 'modelOrderDeduction' => $modelOrderDeduction,
            'vendor_id' => $vendor_id,
            'type' => $type
        ));
    }

    /* jisha copied save order as save approval */

    public function actionSaveApproval()
    {
        $file_id = $_POST['hid_file_id'];
        $model = new PurchasingOrder;
        $modelfile = new MasterFile();
        $modelOrderStockItem = array(new PurchasingOrderStockItem);
        $modelNotes = new FileNotes();
        $modelDocument = new Document();
        if ($file_id > 0) {
            $modelfile = MasterFile::model()->findByPk($file_id);
        }
        if (isset($_POST['PurchasingOrder'])) {
            if ((int) $_POST['PurchasingOrder']['id'] > 0) {
                $model = $model->findByPK($_POST['PurchasingOrder']['id']);
                $model->scenario = 'update';
            } else {
                $model->created_by = Yii::app()->user->id;
                $model->created_datetime = date('Y-m-d h:i:s');
            }

            $model->enquiry_id = $_POST['PurchasingOrder']['enquiry_id'];
            $model->req_id = $_POST['PurchasingOrder']['req_id'];
            $model->updated_by = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d h:i:s');
            $model->attributes = $_POST['PurchasingOrder'];
            $model->start_text = $_POST['PurchasingOrder']['start_text'];
            $model->approved_level = 2;
            //$model->terms_and_conditions = $_POST['PurchasingOrder']['terms_and_conditions'];
            //Code modified by mereena on-10/2/2020 for ckeditor
            $model->terms_and_conditions = $_POST['PurchasingOrder']['terms_and_conditions'];
            //end
            $model->remarks = $_POST['PurchasingOrder']['remarks'];
            $model->notes = $_POST['PurchasingOrder']['notes'];
            $model->currency = $_POST['PurchasingOrder']['currency'];
            $model->crm_user_id = Yii::app()->user->id;
            if ($_POST['PurchasingOrder']['order_date'] != '00/00/0000' && $_POST['PurchasingOrder']['order_date'] != '') {
                $model->order_date = str_replace('/', '-', $_POST['PurchasingOrder']['order_date']);
                $model->order_date = date("Y-m-d", strtotime($model->order_date));
            }
            if ($_POST['PurchasingOrder']['expected_delivery_date'] != '00/00/0000' && $_POST['PurchasingOrder']['expected_delivery_date'] != '') {
                $model->expected_delivery_date = str_replace('/', '-', $_POST['PurchasingOrder']['expected_delivery_date']);
                $model->expected_delivery_date = date("Y-m-d", strtotime($model->expected_delivery_date));
            }
            if ($_POST['PurchasingOrder']['required_date'] != '00/00/0000' && $_POST['PurchasingOrder']['required_date'] != '') {
                $model->required_date = str_replace('/', '-', $_POST['PurchasingOrder']['required_date']);
                $model->required_date = date("Y-m-d", strtotime($model->required_date));
            }
            $model->file_id = $file_id;

            $valid = $model->validate();
            $total_tax_amount = 0;
            $p = 0;
            $arr_service_invoice = array();
            if (!empty($_POST['PurchasingOrderStockItem'])) {
                foreach ($_POST['PurchasingOrderStockItem'] as $k => $rowItem) {
                    if ($rowItem['stock_item_id'] > 0) {
                        //code added by mereena on 16/04/2020
                        $arr_product_details = Store::model()->findByPk($rowItem['stock_item_id']);
                        $arr_service_invoice[] = $arr_product_details->inventory_item_type;
                        //end
//                        if(empty($rowItem['id']))
//                        {
                        $modelOrderStockItem[$p] = new PurchasingOrderStockItem();
                        $modelOrderStockItem[$p]->created_by = Yii::app()->user->id;
                        $modelOrderStockItem[$p]->created_datetime = date('Y-m-d h:i:s');
                        //                        }else{
//                            $modelOrderStockItem[$p] = PurchasingOrderStockItem::model()->findByPk($rowItem['id']);
//                        }
                        $modelOrderStockItem[$p]->updated_by = Yii::app()->user->id;
                        $modelOrderStockItem[$p]->updated_datetime = date('Y-m-d h:i:s');
                        $modelOrderStockItem[$p]->purchasing_order_id = 0;
                        $modelOrderStockItem[$p]->stock_item_tolerance = $rowItem['stock_item_tolerance'];
                        if ($rowItem['stock_item_tolerance'] == 0 || $rowItem['stock_item_tolerance'] == '') {
                            $modelOrderStockItem[$p]->stock_item_max_qty = $rowItem['stock_item_quantity'];
                        } else {
                            $modelOrderStockItem[$p]->stock_item_max_qty = $rowItem['stock_item_max_qty'];
                        }
                        $modelOrderStockItem[$p]->stock_item_id = $rowItem['stock_item_id'];
                        if ($rowItem['expected_delivery_date'] != '') {
                            $modelOrderStockItem[$p]->expected_delivery_date = date("Y-m-d", strtotime(str_replace('/', '-', $rowItem['expected_delivery_date'])));
                        }
                        $modelOrderStockItem[$p]->stock_item_quantity = str_replace(",", "", $rowItem['stock_item_quantity']);
                        $modelOrderStockItem[$p]->stock_item_name = $rowItem['stock_item_name'];
                        $modelOrderStockItem[$p]->stock_item_description = $rowItem['stock_item_description'];
                        $modelOrderStockItem[$p]->stock_item_unit = $rowItem['stock_item_unit'];
                        $modelOrderStockItem[$p]->stock_item_rate = str_replace(",", "", $rowItem['stock_item_rate']);
                        $modelOrderStockItem[$p]->stock_item_amount = str_replace(",", "", $rowItem['stock_item_amount']);
                        $modelOrderStockItem[$p]->tax_percentage = str_replace(",", "", $rowItem['tax_percentage']);
                        $modelOrderStockItem[$p]->tax_amount = str_replace(",", "", $rowItem['tax_amount']);

                        $total_tax_amount += str_replace(",", "", $rowItem['tax_amount']);
                        $stockgrand_total += str_replace(",", "", $rowItem['stock_item_amount']);
                        $valid = $modelOrderStockItem[$p]->validate() && $valid;
                        $p++;
                    }
                }
                if ($modelOrderStockItem[0]->stock_item_id == '')
                    $valid = false;
            }
            //code added by mereena on 16/04/2020
            $service_invoice = 'N';
            if (in_array(1, $arr_service_invoice)) {
                $service_invoice = "N";
            } else {
                $service_invoice = "Y";
            }
            $model->service_invoice = $service_invoice;
            //end
            if (!empty($_POST['PurchasingOrderAddition'])) {

                foreach ($_POST['PurchasingOrderAddition'] as $k => $rowItem) {
                    if ($rowItem['particular'] > 0) {
                        if (empty($rowItem['id'])) {
                            $modelPurchasingOrderAddition[$k] = new PurchasingOrderAddition();
                            $modelPurchasingOrderAddition[$k]->created_by = Yii::app()->user->id;
                            $modelPurchasingOrderAddition[$k]->created_datetime = date('Y-m-d h:i:s');
                        } else {
                            $modelPurchasingOrderAddition[$k] = PurchasingOrderAddition::model()->findByPk($rowItem['id']);
                        }
                        $modelPurchasingOrderAddition[$k]->updated_by = Yii::app()->user->id;
                        $modelPurchasingOrderAddition[$k]->updated_datetime = date('Y-m-d h:i:s');
                        $modelPurchasingOrderAddition[$k]->purchasing_order_id = 0;
                        $modelPurchasingOrderAddition[$k]->particular_value = $rowItem['particular_value'];
                        $modelPurchasingOrderAddition[$k]->calculated_value = $rowItem['calculated_value'];
                        $modelPurchasingOrderAddition[$k]->particular = $rowItem['particular'];
                        $nonstock_grandtotal += $rowItem['calculated_value'];
                        $valid = $modelPurchasingOrderAddition[$k]->validate() && $valid;
                    }
                }
            }
            if (!empty($_POST['PurchasingOrderDeduction'])) {

                foreach ($_POST['PurchasingOrderDeduction'] as $k => $rowItem) {
                    if ($rowItem['particular'] > 0) {
                        if (empty($rowItem['id'])) {
                            $modelPurchasingOrderDeduction[$k] = new PurchasingOrderDeduction();
                            $modelPurchasingOrderDeduction[$k]->created_by = Yii::app()->user->id;
                            $modelPurchasingOrderDeduction[$k]->created_datetime = date('Y-m-d h:i:s');
                        } else {
                            $modelPurchasingOrderDeduction[$k] = PurchasingOrderDeduction::model()->findByPk($rowItem['id']);
                        }
                        $modelPurchasingOrderDeduction[$k]->updated_by = Yii::app()->user->id;
                        $modelPurchasingOrderDeduction[$k]->updated_datetime = date('Y-m-d h:i:s');
                        $modelPurchasingOrderDeduction[$k]->purchasing_order_id = 0;
                        $modelPurchasingOrderDeduction[$k]->particular_value = $rowItem['particular_value'];
                        $modelPurchasingOrderDeduction[$k]->calculated_value = $rowItem['calculated_value'];
                        $modelPurchasingOrderDeduction[$k]->particular = $rowItem['particular'];
                        $nonstock_grandtotal -= $rowItem['calculated_value'];
                        $valid = $modelPurchasingOrderDeduction[$k]->validate() && $valid;
                    }
                }
            }
            if ($valid) {
                $exist = PurchasingOrder::model()->findAll();
                if (empty($exist)) {
                    $value = MasNumberSettings::model()->findByPk(9)->value;
                    Yii::app()->db->createCommand("ALTER TABLE crm_purchasing_order AUTO_INCREMENT=" . $value . " ")->query();
                }
                switch ($model->approved_level) {
                    case 0:
                        if ((Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["purchase_order_approve1"]))) {
                            $model->approved_level++;
                            $model->level1_approved_by = Yii::app()->user->id;
                            $model->level1_approved_time = date('Y-m-d H:i:s');
                        }
                        break;
                    case 1:
                        if ((Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["purchase_order_approve2"]))) {
                            $model->approved_level++;
                            $model->level2_approved_by = Yii::app()->user->id;
                            $model->level2_approved_time = date('Y-m-d H:i:s');
                        }
                        break;
                    case 2:
                        if ((Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["purchase_order_approve3"]))) {
                            $model->approved_level++;
                            $model->level3_approved_by = Yii::app()->user->id;
                            $model->level3_approved_time = date('Y-m-d H:i:s');
                        }
                        break;
                }
                if ($model->save()) {

                    /*                     * *************** START code added by mereena on 22-10-2019 for approval history******************* */
                    date_default_timezone_set("Asia/Dubai");
                    $approval_history = new ApprovalHistory;
                    $approval_history->file_id = $model->file_id;
                    $approval_history->status = "Y";
                    $approval_history->action_by = Yii::app()->user->id;
                    $approval_history->created_by = Yii::app()->user->id;
                    $approval_history->created_datetime = date('Y-m-d H:i:s');
                    $approval_history->date = date('Y-m-d H:i:s');
                    $approval_history->state = 'PO';
                    $approval_history->save();

                    // inserting to audit log
                    AuditLog::saveAuditLogs(
                        'PURCHASE_ORDER',
                        Yii::app()->user->id,
                        'UPDATED',
                        " with APPRVL LVL " . $model->approved_level . " for No: - {$model->id} "
                    );
                    // end audit log
                    //if ($model->approved_level == 3) {//$file_id >0 &&
                    if ($file_id > 0) {
                        MasterFile::model()->updateByPk($file_id, array('is_approved' => "Y", 'approved_by' => Yii::app()->user->id, 'date_of_approval' => date('Y-m-d'), 'current_process_status' => "P_O"));
                        $modelfile->id = $model->file_id;
                    }/* else{
                  $modelfile->start_from ="P_O";
                  $modelfile->crm_user_id = Yii::app()->user->id;
                  $modelfile->customer_id = $model->vendor_id;
                  $modelfile->file_title = $model->title;
                  $modelfile->current_process_status="P_O";
                  $modelfile->is_approved = "Y";
                  $modelfile->approved_by=Yii::app()->user->id;
                  $modelfile->date_of_approval=date('Y-m-d');
                  $modelfile->save(false);
                  $model->updateByPk($model->id, array('file_id' => $modelfile->id));
                  } */
                    $order_id = $model->id;
                    PurchasingOrderStockItem::model()->deleteAll('purchasing_order_id=:refer_id', array(':refer_id' => $order_id));

                    if (!empty($modelOrderStockItem)) {
                        foreach ($modelOrderStockItem as $eachItem) {
                            $eachItem->purchasing_order_id = $model->id;
                            $eachItem->save(false);
                        }
                    }
                    if (!empty($modelPurchasingOrderAddition)) {
                        foreach ($modelPurchasingOrderAddition as $eachItem) {
                            $eachItem->purchasing_order_id = $model->id;
                            $eachItem->save(false);
                        }
                    }
                    if (!empty($modelPurchasingOrderDeduction)) {
                        foreach ($modelPurchasingOrderDeduction as $eachItem) {
                            $eachItem->purchasing_order_id = $model->id;
                            $eachItem->save(false);
                        }
                    }

                    if (is_array($_POST['Document'])) {
                        Document::model()->deleteAll('file_id=:refer_id', array(':refer_id' => $modelfile->id));
                        foreach ($_POST['Document'] as $i => $each) {
                            if (!empty($each['document_name']) or !empty($each['document_actual_file_name'])) {
                                $modelDocument = new Document();
                                $modelDocument->attributes = $each;
                                $modelDocument->document_name = $each['document_name'];
                                $modelDocument->document_actual_file_name = $each['document_actual_file_name'];
                                $modelDocument->file_id = $modelfile->id;
                                $modelDocument->created_by = Yii::app()->user->id;
                                $modelDocument->created_datetime = date('Y-m-d h:i:s');
                                $modelDocument->save(false);
                            }
                        }
                    }
                    if (!empty($_POST['FileNotes'])) {
                        FileNotes::model()->deleteAll('file_id=:refer_id', array(':refer_id' => $modelfile->id));
                        foreach ($_POST['FileNotes'] as $i => $each) {
                            if (!empty($each['notes'])) {
                                $modelNotes = new FileNotes();
                                $modelNotes->attributes = $each;
                                $modelNotes->notes = $each['notes'];
                                $modelNotes->crm_user_id = Yii::app()->user->id;
                                $modelNotes->customer_vendor_id = $model->vendor_id;
                                $modelNotes->customer_vendor_type = 2;
                                $modelNotes->file_note_from = 1;
                                $modelNotes->file_id = $modelfile->id;
                                $modelNotes->created_by = Yii::app()->user->id;
                                $modelNotes->created_datetime = date('Y-m-d h:i:s');
                                $modelNotes->save(false);
                            }
                        }
                    }
                    $model_mail_setting = Notification::model()->find(array('condition' => 'event_id="14"'));
                    Yii::import('application.controllers.front.MasternotificationController');
                    if ($model_mail_setting->mail_required == 'Y') {
                        // MasternotificationController::sendmail(14,$model->id);
                    }
                    if ($model_mail_setting->notification_required == 'Y') {
                        // MasternotificationController::sendnotification(14,$model->id);
                    }
                    if ($model_mail_setting->sms_required == 'Y') {
                        // MasternotificationController::sendsms(14,$model->id);
                    }
                }
                /* if ($_POST['FileNotes']['notes']!='')
                  {
                  if ((int) @$_POST['FileNotes']['id'] > 0)
                  {
                  $notes_id = (int) @$_POST['FileNotes']['id'];
                  $modelNotes = $modelNotes->findByPk($notes_id);
                  $modelNotes->updated_by = Yii::app()->user->id;
                  $modelNotes->updated_datetime = date('Y-m-d h:i:s');
                  }
                  else
                  {
                  $modelNotes->created_by = Yii::app()->user->id;
                  $modelNotes->created_datetime = date('Y-m-d h:i:s');
                  }
                  $modelNotes->notes=$_POST['FileNotes']['notes'];
                  $modelNotes->crm_user_id = Yii::app()->user->id;
                  $modelNotes->customer_vendor_id = $model->vendor_id;
                  $modelNotes->customer_vendor_type=2;
                  $modelNotes->file_note_from=1;
                  $modelNotes->file_id=$model->file_id;
                  $modelNotes->attributes = $_POST['FileNotes'];
                  $modelNotes->save(false);
                  }
                  if($_POST['Icon']['file'] != ''){
                  if(implode(',', $_POST['Icon']['file'])!='')
                  {
                  if ((int) @$_POST['Document']['id'] > 0) {
                  $doc_id = (int) @$_POST['Document']['id'];
                  $modelDocument = Document::model()->findByPk($doc_id);
                  $modelDocument->updated_by = Yii::app()->user->id;
                  $modelDocument->updated_datetime = date('Y-m-d h:i:s');
                  $arr_doc_photos = $_POST['Icon']['file'];
                  if (!empty($arr_doc_photos)) {
                  Document::model()->updateByPk($modelDocument->id, array('document_name' => 'JA'));
                  }
                  }
                  else
                  {
                  $modelDocument = new Document;
                  $arr_doc_photos = $_POST['Icon']['file'];
                  if (!empty($arr_doc_photos)) {
                  $modelDocument->uploaded_from =  "P_O";
                  }
                  $modelDocument->file_id = $model->file_id;
                  $modelDocument->created_by = Yii::app()->user->id;
                  $modelDocument->created_datetime = date('Y-m-d h:i:s');
                  }
                  $modelDocument->document_name = implode(',', $arr_doc_photos);
                  $modelDocument->save(false);
                  }
                  } */
                $stockgrand_total += $total_tax_amount;
                $model->updateByPk($model->id, array('stock_grand_total' => $stockgrand_total, 'total_tax_amount' => $total_tax_amount));
                $model->updateByPk($model->id, array('nonstock_grandtotal' => $nonstock_grandtotal));
                MasterFile::model()->updateByPk($file_id, array('current_process_status' => "P_O"));
                $jsonData['id'] = $model->id;
                $jsonData['order'] = $model->findByPk($model->id);
                $jsonData['status'] = 'success';
                echo CJSON::encode($jsonData);
            } else {
                $error1 = $error2 = $error3 = $error4 = array();
                $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                if ($modelOrderStockItem[0]->stock_item_id != '')
                    $error2 = json_decode(CActiveForm::validateTabular($modelOrderStockItem, '', false), true);
                else
                    $error2[] = "Please add atleast one stock item";
                if (!empty($modelPurchasingOrderAddition))
                    $error3 = json_decode(CActiveForm::validateTabular($modelPurchasingOrderAddition, '', false), true);
                if (!empty($modelPurchasingOrderDeduction))
                    $error4 = json_decode(CActiveForm::validateTabular($modelPurchasingOrderDeduction, '', false), true);
                ////if ($modelNonStock[0]->non_stock_item_name!='')
                //$error3 = json_decode(CActiveForm::validateTabular($modelNonStock, '', false), true);
                $error = CJSON::encode(array_merge_recursive($error4, $error3, $error2, $error1));
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionGetAllProducts()
    {
        $from = $_GET['frm'];
        $product_ids = $_GET['products'];
        $vendor_id = $_GET['vendor_id'];
        $searchTerm = $_GET['term'];
        //if(Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["other_view_international_products"])){
        $condition = 't.isActive = "Y" AND ( inventory_item_type =1 OR inventory_item_type=3 OR inventory_item_type=2) AND (  t.description LIKE "%' . $searchTerm . '%" OR part_number LIKE "%' . $searchTerm . '%"  )';
        /* }
          else{
          $condition = 't.isActive = "Y" AND ( inventory_item_type =1 OR inventory_item_type=3 OR inventory_item_type=2) AND (oem_number LIKE "%' . $searchTerm . '%" OR t.description LIKE "%' . $searchTerm . '%" OR part_number LIKE "%' . $searchTerm . '%" OR brand_detail.product_class LIKE "%' . $searchTerm . '%")  AND purchase_from="L"';
          } */

        $model = new Store();
        $model = $model->findAll(array('condition' => $condition, 'limit' => 300));
        $i = 0;
        foreach ($model as $eachModel) {
            $rate = 0.00;
            $data[$i]['value'] = $eachModel->id;
            //$data[$i]['label'] = $eachModel->oem_number.' : '.$eachModel->brand_detail->product_class.' : '. $eachModel->description;
            //$data[$i]['part_number'] = $eachModel->oem_number;
            $part_number = "";
            if (!empty($eachModel->part_number)) {
                $part_number .= $eachModel->part_number . ' : ';
            }
            /* if(!empty($eachModel->brand_detail->product_class)){
              $part_number.=$eachModel->brand_detail->product_class.' : ';
              } */
            $part_number .= $eachModel->description;

            $data[$i]['label'] = $part_number;

            $data[$i]['part_number'] = $eachModel->part_number;
            $data[$i]['description'] = $eachModel->description;
            // $data[$i]['unit_id'] = $eachModel->unit->id;
            // $data[$i]['unit_name'] = $eachModel->unit->symbol;
           // $data[$i]['tax_code'] = $eachModel->tax;
            if ((int) $vendor_id > 0) {
                $mod_his = PurchasingOrderStockItem::model()->with('purchaseorder')->find(array('condition' => 'stock_item_id = ' . $eachModel->id . ' AND purchaseorder.vendor_id=' . (int) $vendor_id . '', 'order' => 't.id DESC', 'limit' => '1'));
                if (!empty($mod_his)) {
                    $rate = $mod_his->stock_item_rate;
                }
            }
            $data[$i]['rate'] = $rate;

            $cubicmeter = "";

            // if ((float) $eachModel->cubic_meter > 0) {
            //     $cubicmeter = $eachModel->cubic_meter;
            // } else {
            //     if ((float) $eachModel->height > 0) {
            //         $cubicmeter = $eachModel->height;
            //     }

            //     if ((float) $eachModel->width > 0) {
            //         if (!empty($cubicmeter)) {
            //             $cubicmeter = $cubicmeter * $eachModel->width;
            //         } else {
            //             $cubicmeter = $eachModel->width;
            //         }
            //     }

            //     if ((float) $eachModel->length > 0) {
            //         if (!empty($cubicmeter)) {
            //             $cubicmeter = $cubicmeter * $eachModel->length;
            //         } else {
            //             $cubicmeter = $eachModel->length;
            //         }
            //     }
            // }

            //$data[$i]['cubicmeter'] = $cubicmeter;
            //$data[$i]['other'] = $eachModel->weight;
            $i++;
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

    public function actionPurchaseHelper()
    {
        $product_id = (int) $_POST['id'];
        $company_id = (int) $_POST['company_id'];
        $this->renderPartial('purchase_helper', array('id' => $product_id, 'company_id' => $company_id), false, true);
    }

    public function actionStockHelper()
    {
        $product_id = (int) $_POST['id'];
        $this->renderPartial('stock_helper', array('id' => $product_id), false, true);
    }

    public function actionMakeconvert()
    {

        $id = $_POST['id'];
        if ((int) $id > 0) {
            PurchasingOrder::model()->updateByPk($id, array('convert_status' => "Y"));
            $data['status'] = 'success';
        } else {
            $data['status'] = 'fail';
        }
        echo CJSON::encode($data);
    }

    public function actionPaymentTracker()
    {
        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['purchase_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['pur_receipttrack_view']) &&
                Yii::app()->user->havePermissionOn['purchase_menu_view'] &&
                Yii::app()->user->havePermissionOn['pur_receipttrack_view']
            )
        ) {
            $this->render('paymenttracker');
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }

    public function actionGetPaymentTrackerList()
    {

        $model = new PurchasingInvoice();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => '',
            1 => 't.id',
            2 => 'vendor_details.vendor_name',
            3 => 't.invoice_date',
            4 => 'currencyname.currency_code',
            5 => 'paymentTerm.payment_terms',
            6 => 't.invoice_date',
            7 => 't.id'
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.isActive="Y" ';
        if (!isset(Yii::app()->user->havePermissionOn["invoice_view_all"]) && Yii::app()->user->authorised_user != 1) {
            $condition .= ' AND (t.lead_owner_id= "' . Yii::app()->user->id . '" OR file.lead_owner_id="' . Yii::app()->user->id . '")';
        }
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " AND ( t.id LIKE '%" . $searchString . "%' OR vendor_details.vendor_name LIKE '%" . $searchString . "%' OR paymentTerm.payment_terms LIKE '%" . $searchString . "%' OR t.invoice_date LIKE '%" . $searchString . "%' OR currencyname.currency_code LIKE '%" . $searchString . "%')";
        }
        $count = $model->with('vendor_details', 'paymentTerm', 'currencyname')->count(array('condition' => $condition));
        $model = $model->with('vendor_details', 'currencyname', 'paymentTerm')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 't.id DESC'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $status = '';
        $m = 0;
        foreach ($model as $row) {
            if ((int) $row['paymentTerm']['no_of_days'] > 0) {
                $receipt_date = date("d/m/Y", strtotime($row['invoice_date'] . "+" . $row['paymentTerm']['no_of_days'] . " days"));
            } else {
                $receipt_date = date("d/m/Y", strtotime($row['invoice_date']));
            }
            $d1 = strtotime(date("Y-m-d"));
            $date_to = date("Y-m-d", strtotime($row['invoice_date'] . "+" . $row['paymentTerm']['no_of_days'] . " days"));
            $d2 = strtotime($date_to);
            $datediff = $d1 - $d2;
            $diff = floor($datediff / (60 * 60 * 24));
            $m++;
            $rowData[] = array($m, $row['id'], $row['vendor_details']['vendor_name'], date("d/m/Y", strtotime($row['invoice_date'])), '<div class="text-right">' . $row['currencyname']['currency_code'] . ' ' . Yii::app()->numberFormatter->formatCurrency($row['grand_total'], "") . '</div>', $row['paymentTerm']['payment_terms'], $receipt_date, $diff);
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionRemovelineItem()
    {
        $id = $_POST['id'];
        if ($id > 0) {
            Document::model()->deleteByPk($id);
            $status['status'] = 'success';
        } else {
            $status['status'] = 'error';
        }

        echo CJSON::encode($status);
    }

    public function actionPrintPurchasingOrderWord()
    {
        $model = new PurchasingOrder;
        $modelOrderStockItem = new PurchasingOrderStockItem();
        $id = Yii::app()->request->getParam('id');

        header("Location: https://cumuluserp.me/development/acecentro_staging/upload/msoffice/word/purchaseorder.php?id=" . $id);
    }

    //upload document
    public function actionUploadApplicationHiringTemplates($folder = null)
    {
        Yii::import("ext.EAjaxUpload.qqFileUploader");
        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
        // make the directory to store the pic:
        if (!is_dir($folder)) {
            mkdir($folder, 0777, TRUE);
        }
        $allowedExtensions = array("doc", "docx");
        $sizeLimit = 8 * 1024 * 1024; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
        $result['field_id'] = $field_id;
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        //$fileName = $result['filename']; //GETTING FILE NAME
        //$template_name	=	Yii::app()->basePath.'/../upload/msoffice/word/'.$fileName;
        echo $return; // it's array
    }

    //delete document
    public function actionDeleteApplicationTemplates()
    {
        $deletefilename = Yii::app()->request->getparam('deletefilename');
        $templates = Yii::app()->request->getparam('templates');
        $id = (int) Yii::app()->request->getparam('id');
        $model = PurchasingOrder::model()->findByPk($id);
        $new_image_array = array();
        if (!empty($templates)) {
            $model->template_file_name = '';
            $path = Yii::getPathOfAlias('webroot') . "/upload/msoffice/uploadfiles/" . $deletefilename;
            if (file_exists($path)) {
                unlink($path);
            }

            $model->save(false);
            $json['new_file_name'] = '';
            $json['status'] = 'success';
        } else {
            $json['status'] = 'error';
        }
        echo CJSON::encode($json);
    }

    //order from other section
    public function actionConvertToPurchaseOrder()
    {
        $product_ids = Yii::app()->request->getparam('product_ids');
        $model = new PurchasingOrder();
        $modelOrderStockItem = array(new PurchasingOrderStockItem);
        $modelOrderAdditions = array(new PurchasingOrderAddition);
        $modelOrderDeduction = array(new PurchasingOrderDeduction);
        $modelNotes = array(new FileNotes);
        $modelDocument = array(new Document());
        if ($product_ids != '') {
            $modelProducts = Store::model()->findAll(array('condition' => 'id IN (' . $product_ids . ')'));
            foreach ($modelProducts as $i => $eachItem) {
                $modelOrderStockItem[$i] = new PurchasingOrderStockItem;
                $modelOrderStockItem[$i]->stock_item_id = $eachItem['id'];
                $modelOrderStockItem[$i]->stock_item_name = $eachItem['part_number'];
                $modelOrderStockItem[$i]->stock_item_description = $eachItem['description'];
                $modelOrderStockItem[$i]->stock_item_unit = $eachItem['unit'];
                $modelOrderStockItem[$i]->stock_item_quantity = 1;
            }
        }
        $model->expected_delivery_date = date('d/m/Y', strtotime('+5 days'));
        $model->required_date = date('d/m/Y', strtotime('+1 Week'));
        $model->order_date = date('d/m/Y');

        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.min.js' => false);
        $this->render('create', array(
            'model' => $model,
            'file_id' => $file_id,
            'enq_id' => $enq_id,
            'modelEnquiry' => $modelEnquiry,
            'modelOrderStockItem' => $modelOrderStockItem,
            'modelDocument' => $modelDocument,
            'modelNotes' => $modelNotes,
            'modelOrderAdditions' => $modelOrderAdditions,
            'modelOrderDeduction' => $modelOrderDeduction,
            'vendor_id' => $vendor_id,
            'type' => $type,
            'viewtype' => $viewtype
        ));
    }

    public function actionCreateTracking()
    {
        $po_id = (int) Yii::app()->request->getparam('id');
        $model = new PurchasingOrderShipmentDetails();
        $modelDocument = array(new PurchasingOrderShipmentDocument());
        $model = $model->find(array('condition' => 'purchasing_order_id="' . $po_id . '"'));
        if ($model->id > 0) {

            $model = $model->findByPk($model->id);
            $modelDocument = PurchasingOrderShipmentDocument::model()->findAll(array('condition' => 'purchasing_order_id="' . $model->purchasing_order_id . '"'));
            if (empty($modelDocument)) {
                $modelDocument = array(new PurchasingOrderShipmentDocument);
            }
        } else {
            $model = new PurchasingOrderShipmentDetails();
        }
        $model->purchasing_order_id = $po_id;
        if ($model->arrived_date != '' && $model->arrived_date != '0000-00-00') {
            $model->arrived_date = date('d/m/Y', strtotime($model->arrived_date));
        } else {
            $model->arrived_date = date('d/m/Y', strtotime('+5 days'));
        }
        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.min.js' => false);
        $this->render('tracking_create', array('model' => $model, 'modelDocument' => $modelDocument));
    }

    public function actionSaveTracking()
    {
        $model = new PurchasingOrderShipmentDetails();
        if (isset($_POST['PurchasingOrderShipmentDetails'])) {
            $existing_arrived_date = "";
            if ((int) @$_POST['PurchasingOrderShipmentDetails']['id'] > 0) {
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d h:i:s');
                $id = (int) @$_POST['PurchasingOrderShipmentDetails']['id'];
                $model = $model->findByPk($id);
                $existing_arrived_date = date("d/m/Y", strtotime($model->arrived_date));
                $audit_type = 'UPDATED';
                $edit_flag = 1;
            } else {
                $audit_type = 'CREATED';
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date('Y-m-d h:i:s');
            }
            $model->attributes = $_POST['PurchasingOrderShipmentDetails'];
            if ($_POST['PurchasingOrderShipmentDetails']['arrived_date'] != '') {
                $model->arrived_date = str_replace('/', '-', $_POST['PurchasingOrderShipmentDetails']['arrived_date']);
                $model->arrived_date = date("Y-m-d", strtotime($model->arrived_date));
            } else {
                $model->arrived_date = date('Y-m-d');
            }
            if ($model->save()) {

                if (is_array($_POST['PurchasingOrderShipmentDocument'])) {
                    PurchasingOrderShipmentDocument::model()->deleteAll('shipment_id=:refer_id', array(':refer_id' => $model->id));
                    foreach ($_POST['PurchasingOrderShipmentDocument'] as $i => $each) {
                        if (!empty($each['document_name']) or !empty($each['document_actual_file_name'])) {
                            $modelDocument = new PurchasingOrderShipmentDocument();
                            $modelDocument->attributes = $each;
                            $modelDocument->document_name = $each['document_name'];
                            $modelDocument->document_actual_file_name = $each['document_actual_file_name'];
                            $modelDocument->shipment_id = $model->id;
                            $modelDocument->purchasing_order_id = $model->purchasing_order_id;
                            $modelDocument->created_by = Yii::app()->user->id;
                            $modelDocument->created_datetime = date('Y-m-d h:i:s');
                            $modelDocument->save(false);
                        }
                    }
                }

                // inserting to audit log
                $audit_content = " with PO #: - {$model->purchasing_order_id}  and Arrived Date {$_POST['PurchasingOrderShipmentDetails']['arrived_date']}";
                if ($model > 0) {
                    $audit_content = " with PO #: - {$model->purchasing_order_id}  and Arrived Date {$existing_arrived_date} changed to  {$_POST['PurchasingOrderShipmentDetails']['arrived_date']}";
                }

                AuditLog::saveAuditLogs(
                    'PO_TRACK_SHIPMENT',
                    Yii::app()->user->id,
                    $audit_type,
                    $audit_content,
                    $model->purchasing_order_id,
                    "POS"
                );
                // end audit log
                $jsonData['status'] = 'success';
                $jsonData['frm'] = $_POST['shipping-tracking-form'];
                $jsonData['id'] = $model->id;
                echo CJSON::encode($jsonData);
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionGetTrackingHistory()
    {
        $po_id = (int) Yii::app()->request->getparam('po_id');
        $model = new AuditLog();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.functionality=95 AND header_id=' . $po_id . ' AND action="POS"'; //Purchasing Order Shipment -- PO_TRACK_SHIPMENT
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
        }
        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 'performed_datetime DESC'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;

        foreach ($model as $row) {
            $div = '';
            $rowData[] = array($m, User::getName($row['performed_by']), date("d/m/Y h:i a", strtotime($row['performed_datetime'])), $row['changes']);

            $m++;
        }

        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionMovementAnalysis()
    {

        $this->render('movement_analysis');
    }

    public function actionGetNewOrderMovementAnalysis()
    {

        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];

        $columns = array(
            // datatable column index  => database column name
            /* 0 => 't.file_id',
              1 => 't.id',
              2 => 't.title',
              3 => 't.order_date',
              4 => 't.order_date',
              5 => 't.required_date',
              6 =>'t.stock_grand_total',
              7 =>'file.current_process_status',
              8 => 't.convert_status', */
        );

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

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

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

        $to_date = $_POST['to_date'];
        $arr_generic_id = $_POST['generic_id'];

        $generic_id = implode(",", $arr_generic_id);

        $to_date = str_replace('/', '-', $to_date);
        $to_date = date('Y-m-d', strtotime($to_date));

        $condition = 'inventory_item_type=1';

        if ($generic_id != "") {
            $condition .= ' AND t.generic_id IN("' . $generic_id . '")';
        }
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

            $searchString = $_POST['search']['value'];

            $condition .= " AND (t.part_number LIKE '%" . $searchString . "%' OR t.description LIKE '%" . $searchString . "%')";
        }

        $model = new Store;

        $count = $model->count(array('condition' => $condition));

        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 'part_number ASC')); //$model->with('file','vendor_details','user')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset,'order'=>'t.id DESC'));

        $recordsTotal = $count;

        $recordsFiltered = $count;

        $data['draw'] = $draw;

        $data['recordsTotal'] = $recordsTotal;

        $data['recordsFiltered'] = $recordsFiltered;

        $rowData = array();

        $i = 1;
        foreach ($model as $k => $eachItem) {

            $SQL_CURRENT_QTY = 'SELECT SUM(quantity) FROM `erp_stock_ledger` WHERE `product_id` = ' . $eachItem->id;
            $current_quantity = Yii::app()->db->createCommand($SQL_CURRENT_QTY)->queryScalar();

            if ($current_quantity > 0) {

                if ($date != '') {
                    $current_date = str_replace('/', '-', $date);
                    $current_date = date('Y-m-d', strtotime($current_date));
                } else {
                    $current_date = date('Y-m-d');
                }
            }


            $arr_stock_ledger = StockLedger::model()->findAll(array('condition' => 'product_id=' . $eachItem->id . ' AND (transaction_type="OUT" ||  transaction_type="IN") AND (transaction_from="DELIVERY_NOTE" || transaction_from="CREDIT_NOTE")'));

            //START 365 days
            $from_date_365 = date('Y-m-d', strtotime($to_date . '-365 days'));
            $SQL_delivery_note_365 = 'SELECT SUM(-1*quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="OUT" AND transaction_from="DELIVERY_NOTE" AND (transaction_date>="' . $from_date_365 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_delivery_note_365 = Yii::app()->db->createCommand($SQL_delivery_note_365)->queryScalar();

            $SQL_credit_note_365 = 'SELECT SUM(quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="IN" AND transaction_from="CREDIT_NOTE" AND (transaction_date>="' . $from_date_365 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_credit_note_365 = Yii::app()->db->createCommand($SQL_credit_note_365)->queryScalar();

            $quantity_sale_365 = $quantity_delivery_note_365 - $quantity_credit_note_365;
            //END 365 days
            //START 180 Days
            $from_date_180 = date('Y-m-d', strtotime($to_date . '-180 days'));
            $SQL_delivery_note_180 = 'SELECT SUM(-1*quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="OUT" AND transaction_from="DELIVERY_NOTE" AND (transaction_date>="' . $from_date_180 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_delivery_note_180 = Yii::app()->db->createCommand($SQL_delivery_note_180)->queryScalar();

            $SQL_credit_note_180 = 'SELECT SUM(quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="IN" AND transaction_from="CREDIT_NOTE" AND (transaction_date>="' . $from_date_180 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_credit_note_180 = Yii::app()->db->createCommand($SQL_credit_note_180)->queryScalar();

            $quantity_sale_180 = $quantity_delivery_note_180 - $quantity_credit_note_180;
            //END 180 Days
            //START 90 Days
            $from_date_90 = date('Y-m-d', strtotime($to_date . '-90 days'));
            $SQL_delivery_note_90 = 'SELECT SUM(-1*quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="OUT" AND transaction_from="DELIVERY_NOTE" AND (transaction_date>="' . $from_date_90 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_delivery_note_90 = Yii::app()->db->createCommand($SQL_delivery_note_90)->queryScalar();

            $SQL_credit_note_90 = 'SELECT SUM(quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="IN" AND transaction_from="CREDIT_NOTE" AND (transaction_date>="' . $from_date_90 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_credit_note_90 = Yii::app()->db->createCommand($SQL_credit_note_90)->queryScalar();

            $quantity_sale_90 = $quantity_delivery_note_90 - $quantity_credit_note_90;
            //END 90 Days
            //START 30 Days
            $from_date_30 = date('Y-m-d', strtotime($to_date . '-30 days'));
            $SQL_delivery_note_30 = 'SELECT SUM(-1*quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="OUT" AND transaction_from="DELIVERY_NOTE" AND (transaction_date>="' . $from_date_30 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_delivery_note_30 = Yii::app()->db->createCommand($SQL_delivery_note_30)->queryScalar();

            $SQL_credit_note_30 = 'SELECT SUM(quantity) FROM `erp_stock_ledger` WHERE product_id=' . $eachItem->id . ' AND transaction_type="IN" AND transaction_from="CREDIT_NOTE" AND (transaction_date>="' . $from_date_30 . '" AND transaction_date<="' . $to_date . '")';

            $quantity_credit_note_30 = Yii::app()->db->createCommand($SQL_credit_note_30)->queryScalar();

            $quantity_sale_30 = $quantity_delivery_note_30 - $quantity_credit_note_30;
            //END 30 Days

            $SQL_purchase_order_qty = 'SELECT SUM(stock_item_quantity) FROM `erp_purchasing_order_stock_item`
                                                                    INNER JOIN erp_purchasing_order AS PO ON purchasing_order_id=PO.id
                                                                    INNER JOIN erp_master_file AS MF ON file_id=MF.id WHERE stock_item_id=' . $eachItem->id . ' AND is_approved="Y"';

            $purchase_order_qty = Yii::app()->db->createCommand($SQL_purchase_order_qty)->queryScalar();

            $SQL_purchase_invoice_qty = 'SELECT SUM(quantity) FROM `erp_purchasinginvoice_item` WHERE product_id=' . $eachItem->id;

            $purchase_invoice_qty = Yii::app()->db->createCommand($SQL_purchase_invoice_qty)->queryScalar();

            $upcoming_shipment_qty = $purchase_order_qty - $purchase_invoice_qty;

            $average_movement = ($quantity_sale_90 / 3);

            $expected_2_month_movement = (($quantity_sale_365 / 12) * 2);

            $expected_closing_stock_2_month = ($current_quantity + $upcoming_shipment_qty) - $expected_2_month_movement;

            $rowData[] = array($i, substr($eachItem->description, 0, 40) . '..', $eachItem->unit->symbol, round($quantity_sale_365), round($quantity_sale_180), round($quantity_sale_90), round($quantity_sale_30), round($current_quantity), round($upcoming_shipment_qty), round($average_movement), round($expected_2_month_movement), round($expected_closing_stock_2_month));
            $i++;
            ?>


            <?php

        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionIndexMovementAnalysis()
    {
        $model = new PurchaseMovementAnalysis();

        $this->render('index_movement_analysis');
    }

    public function actionCreateMovementAnalysis()
    {
        $id = (int) Yii::app()->request->getparam('id');
        $type = Yii::app()->request->getparam('type');
        $model = new PurchaseMovementAnalysis();

        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.min.js' => false);
        $this->render('create_movement_analysis', array('model' => $model, 'type' => $type, 'id' => $id));
    }

    public function actionGetNewMovementAnalysisList()
    {

        $model = new PurchaseMovementAnalysis();

        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];

        $columns = array(
            // datatable column index  => database column name
            0 => 't.id',
            1 => 't.analysis_date',
            2 => 't.generic_ids',
            3 => 't.approved_by',
            4 => 't.order_date',
            5 => 't.approvedd_date',
            6 => 't.created_by'
        );

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

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

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

        $to_date = $_POST['to_date'];
        //$arr_generic_id = $_POST['generic_id'];
        //$generic_id = implode(",",$arr_generic_id);

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

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

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

        $condition = "";
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

            $searchString = $_POST['search']['value'];

            $condition = " t.id 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();

        $i = 1;
        foreach ($model as $row) {
            $modelGeneric = MasGeneric::model()->findAll(array('condition' => 'id IN(' . $row["generic_ids"] . ')'));
            $str_generic_name = "";
            foreach ($modelGeneric as $i => $generic_name) {
                if ($str_generic_name == "") {
                    $str_generic_name = $generic_name['generic_name'];
                } else {
                    $str_generic_name .= "," . $generic_name['generic_name'];
                }
            }
            $rowData[] = array($row['id'], date("d/m/Y", strtotime($row->analysis_date)), $str_generic_name, $row['approvedby']['first_name'] . " " . $row['approvedby']['last_name'], ($row['approved_date'] != "0000-00-00 00:00:00") ? date("d/m/Y", strtotime($row['approved_date'])) : "", $row['createdby']['first_name'] . " " . $row['createdby']['last_name'], $row['approved_by'], $row['is_converted']);
            $i++;
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionGetMovementAnalysisTableData()
    {
        $to_date = $_POST['analysis_date'];
        $generic_ids = $_POST['generic_ids'];
        $type = $_POST['type'];
        $analysis_id = (int) $_POST['analysis_id'];
        $part_no = $_POST['part_no'];
        //$generic_id = implode(",",$arr_generic_id);



        $to_date = str_replace('/', '-', $to_date);
        $to_date = date('Y-m-d', strtotime($to_date));

        $condition = 'inventory_item_type=1 AND isActive="Y"';

        if ($part_no != "") {
            $condition .= ' AND (part_number LIKE "%' . $part_no . '%" OR description LIKE "%' . $part_no . '%")';
        }

        if ($generic_ids != "") {
            $condition .= ' AND t.generic_id IN(' . $generic_ids . ')';
        }
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

            $searchString = $_POST['search']['value'];

            $condition .= " AND (t.part_number LIKE '%" . $searchString . "%' OR t.description LIKE '%" . $searchString . "%')";
        }
        //echo $condition;
        $model = new Store;

        $model = $model->findAll(array('condition' => $condition, 'order' => 'part_number ASC'));
        //echo '<pre>';
        //print_r($model);
        //echo $condition;
        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.min.js' => false);
        $this->render('load_movement_analysis', array('model' => $model, 'to_date' => $to_date, 'generic_ids' => $generic_ids, 'analysis_id' => $analysis_id, 'type' => $type));
    }

    public function actionSaveMovementAnalysis()
    {
        $model = new PurchaseMovementAnalysis();
        $analysis_id = $_POST['PurchaseMovementAnalysis_analysis_id'];
        if ((int) $analysis_id > 0) {
            $model = $model->findByPK($analysis_id);
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d H:i:s');
        } else {
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d H:i:s');
        }

        $model->analysis_date = $_POST['PurchaseMovementAnalysis_analysis_date'];
        $model->generic_ids = $_POST['PurchaseMovementAnalysis_generic_ids'];
        if ($_POST['PurchaseMovementAnalysis_type'] == 'approve') {
            $model->approved_by = Yii::app()->user->id;
            $model->approved_date = date('Y-m-d H:i:s');
        } else {
            $model->approved_by = 0;
            $model->approved_date = "0000-00-00";
        }
        $model->save(false);

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

            foreach ($_POST['PurchaseMovementAnalysisDetails'] as $k => $rowItem) {
                if ($rowItem['product_id'] > 0) {

                    $modelMovementAnalysisDetails = new PurchaseMovementAnalysisDetails();
                    if ($rowItem['id'] > 0) {
                        $modelMovementAnalysisDetails = $modelMovementAnalysisDetails->findByPk($rowItem['id']);
                    }


                    $modelMovementAnalysisDetails->analysis_id = $model->id;
                    $modelMovementAnalysisDetails->product_id = $rowItem['product_id'];
                    $modelMovementAnalysisDetails->part_number = $rowItem['part_number'];
                    $modelMovementAnalysisDetails->description = $rowItem['description'];
                    $modelMovementAnalysisDetails->unit_id = $rowItem['unit_id'];
                    $modelMovementAnalysisDetails->current_stock = $rowItem['current_stock'];
                    $modelMovementAnalysisDetails->days_365 = $rowItem['days_365'];
                    $modelMovementAnalysisDetails->days_180 = $rowItem['days_180'];
                    $modelMovementAnalysisDetails->days_90 = $rowItem['days_90'];
                    $modelMovementAnalysisDetails->days_30 = $rowItem['days_30'];
                    $modelMovementAnalysisDetails->upcoming_shipment_qty = $rowItem['upcoming_shipment_qty'];
                    $modelMovementAnalysisDetails->average_movement = $rowItem['average_movement'];
                    $modelMovementAnalysisDetails->expected_2_months_movement = $rowItem['expected_2_months_movement'];
                    $modelMovementAnalysisDetails->expected_closing_stock_after_2_months = $rowItem['expected_closing_stock_after_2_months'];
                    $modelMovementAnalysisDetails->proposal_qty = $rowItem['proposal_qty'];
                    $modelMovementAnalysisDetails->approval_current_stock = $rowItem['approval_current_stock'];
                    $modelMovementAnalysisDetails->remarks = $rowItem['remarks'];
                    $modelMovementAnalysisDetails->save(false);
                }
            }
        }

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

        echo CJSON::encode($jsonData);
    }

    public function actionPrintMovementAnalysisPDF()
    {
        $model = new PurchaseMovementAnalysis();
        $id = Yii::app()->request->getParam('id');
        if ($id > 0) {
            $model = PurchaseMovementAnalysis::model()->findByPk($id);
        }
        $mPDF1 = Yii::app()->ePdf->mpdf('', 'A4');
        $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/pdf_style.css');
        $mPDF1->WriteHTML($stylesheet, 1);
        $mPDF1->WriteHTML($this->renderPartial('application.views.front.pdf.purchase_order_movement_analysis', array('model' => $model, 'id' => $id, 'frm' => $frm, 'title' => $title), true));
        $mPDF1->Output("New_Order_Movement_Analysis.pdf", 'I');
    }

    public function actionEditDeliveryTracker()
    {
        $id = Yii::app()->request->getParam('id');
        $frm = Yii::app()->request->getParam('frm');
        if ($id > 0) {
            $dateModel = PurchasingOrderStockItem::model()->findBypk($id);
            $dateModel->expected_delivery_date = date("d/m/Y", strtotime($dateModel->expected_delivery_date));
        }
        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.min.js' => false);
        $this->render('edit_delivery_tracker', array('model' => $dateModel, 'frm' => $frm));
    }

    public function actionUpdateDeliveryTracker()
    {
        $id = $_POST['PurchasingOrderStockItem']['id'];
        if ($id > 0) {
            PurchasingOrderStockItem::model()->updateByPk($id, array('expected_delivery_date' => date("Y-m-d", strtotime(str_replace('/', '-', $_POST['PurchasingOrderStockItem']['expected_delivery_date']))), 'notes' => $_POST['PurchasingOrderStockItem']['notes']));
            $jsonData['status'] = 'success';
        } else {
            $jsonData['status'] = 'error';
        }
        echo CJSON::encode($jsonData);
    }

    public function actionDeliveryTrackerNotes()
    {
        $id = (int) Yii::app()->request->getParam('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.min.js' => false);
        $this->render('delivery_tracker_note_list', array('purchasing_order_id' => $id));
    }

    public function actionGetDeliveryTrackerNotesList()
    {
        $id = (int) Yii::app()->request->getParam('purchasing_order_id');
        $model = new PurchasingOrderStockItem();

        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $file_id = $_POST['file_id'];
        $columns = array(
            // datatable column index  => database column name
            0 => 't.id',
            1 => 't.purchasing_order_id',
            2 => 't.expected_delivery_date',
            3 => 't.notes',
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.purchasing_order_id=' . $id;
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " and (stock_item_name LIKE '%" . $searchString . "%' OR notes 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) {
            $rowData[] = array($m, $row['stock_item_name'], date("d/m/Y", strtotime(str_replace('/', '-', $row['expected_delivery_date']))), $row['notes']);
            $m++;
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionGetApprovalHistory()
    {
        $file_id = Yii::app()->request->getparam("file_id");
        $modelHistory = ApprovalHistory::model()->find(array('condition' => 'file_id = "' . $file_id . '" AND state="PO"'));
        if (empty($modelHistory)) {
            $modelHistory = new ApprovalHistory();
        }
        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.min.js' => false, 'jquery-2.1.4.min.js' => false, '*.css' => false);
        $this->renderPartial('approval_history', array('modelHistory' => $modelHistory, 'file_id' => $file_id), false, true);
    }

    public function actionGetApprovalHistoryList()
    {
        $model = new ApprovalHistory();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 't.action_by',
            1 => 't.created_datetime',
            2 => 't.state',
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.file_id = "' . $_POST['file_id'] . '" AND t.state="PO"';
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " AND (approvedby.first_name LIKE '%" . $searchString . "%' OR approvedby.last_name LIKE '%" . $searchString . "%' OR state LIKE '%" . $searchString . "%')";
        }
        $count = $model->with('approvedby')->count(array('condition' => $condition));
        $model = $model->with('approvedby')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 'created_datetime DESC'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        foreach ($model as $row) {
            $button_string = "";
            $status = "Approved";
            if ($row['status'] == 'N') {
                $status = "Un Approved";
            }
            $state = "Quotation";
            if ($row['state'] == 'PO') {
                $state = "Purchase Order";
            }
            $rowData[] = array($m, $row['approvedby']['first_name'] . " " . $row['approvedby']['last_name'], date("d/m/Y h:i:s", strtotime($row['created_datetime'])), $status, $state);
            $m++;
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }
    public function actionGetOrderCount()
    {
        $filter = Yii::app()->request->getPost('filter');

        $model = new PurchasingOrder();

        $qty = 0;
        $total = 0;
        $extra_years = [];
        $current_year = date('Y');

        $getDateRange = function ($filter, $yearOffset = 0) {
            $targetDate = strtotime("-{$yearOffset} year");
            $year = date('Y', $targetDate);

            switch ($filter) {
                case 'today':
                    $date = date('Y-m-d', $targetDate);
                    return [$date, $date, $year];

                case 'yesterday':
                    $date = date('Y-m-d', strtotime('-1 day', $targetDate));
                    return [$date, $date, $year];

                case 'this_month':
                    $month = date('m');
                    $start = "{$year}-{$month}-01";
                    $end = date('Y-m-t', strtotime($start));
                    return [$start, $end, $year];

                case 'this_year':
                    return ["{$year}-01-01", "{$year}-12-31", $year];

                case 'this_week':
                    $monday = date('Y-m-d', strtotime("monday this week", $targetDate));
                    $sunday = date('Y-m-d', strtotime("sunday this week", $targetDate));
                    return [$monday, $sunday, $year];

                case 'last_week':
                    $monday = date('Y-m-d', strtotime("monday last week", $targetDate));
                    $sunday = date('Y-m-d', strtotime("sunday last week", $targetDate));
                    return [$monday, $sunday, $year];

                case 'quarterly':
                    $month = date('n', $targetDate); // 1-12
                    if ($month >= 1 && $month <= 3) {
                        $start = "$year-01-01";
                        $end = "$year-03-31";
                    } elseif ($month >= 4 && $month <= 6) {
                        $start = "$year-04-01";
                        $end = "$year-06-30";
                    } elseif ($month >= 7 && $month <= 9) {
                        $start = "$year-07-01";
                        $end = "$year-09-30";
                    } else {
                        $start = "$year-10-01";
                        $end = "$year-12-31";
                    }
                    return [$start, $end, $year];

                default:
                    return [null, null, null];
            }
        };

        list($startDate, $endDate, $current_year) = $getDateRange($filter, 0);

        if (!$startDate || !$endDate) {
            echo CJSON::encode(['status' => 'error', 'message' => 'Invalid filter']);
            Yii::app()->end();
        }

        // Current data
        $condition = 'order_date >= :startDate AND order_date <= :endDate';
        $params = [':startDate' => $startDate, ':endDate' => $endDate];

        $orders = $model->findAll($condition, $params);
        $qty = count($orders);
        foreach ($orders as $row) {
            $grand_total = $row->stock_grand_total + $row->nonstock_grandtotal;
            $total += $grand_total * $row->exchange_rate;
        }

        // Previous years
        for ($i = 1; $i <= 2; $i++) {
            list($prevStart, $prevEnd, $yearLabel) = $getDateRange($filter, $i);

            $conditionPrev = 'order_date >= :startDate AND order_date <= :endDate';
            $paramsPrev = [':startDate' => $prevStart, ':endDate' => $prevEnd];

            $prevOrders = $model->findAll($conditionPrev, $paramsPrev);
            $prevQty = count($prevOrders);
            $prevTotal = 0;

            foreach ($prevOrders as $row) {
                $grand_total = $row->stock_grand_total + $row->nonstock_grandtotal;
                $prevTotal += $grand_total * $row->exchange_rate;
            }

            $extra_years[] = [
                'year' => $yearLabel,
                'qty' => $prevQty,
                'total' => $prevTotal,
                'date' => in_array($filter, ['today', 'yesterday']) ? date('d-m-Y', strtotime($prevStart)) : null,
            ];
        }

        echo CJSON::encode([
            'status' => 'success',
            'data' => [
                'qty' => $qty,
                'total' => $total,
                'current_period' => in_array($filter, ['today', 'yesterday'])
                    ? date('d-m-Y', strtotime($startDate))
                    : $current_year,
                'previous_years' => $extra_years,
            ]
        ]);
        Yii::app()->end();
    }


    //end
}
