Your IP : 216.73.216.79


Current Path : /var/www/html/dyna-crm/controllers/
Upload File :
Current File : /var/www/html/dyna-crm/controllers/StockdeliveryController.php

<?php

namespace app\controllers;

use Yii;
use app\models\StockDelivery;
use app\models\StockDeliverySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use app\models\Log;
use app\models\LogSearch;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use kartik\mpdf\Pdf;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\models\Product;
use yii\helpers\Html;
use app\models\ParamList;
use app\models\DeliveryOrder;
use app\models\DeliveryOrderItem;
use app\models\Company;
use app\models\StockLog;
use app\models\Rider;

/**
 * StockdeliveryController implements the CRUD actions for StockDelivery model.
 */
class StockdeliveryController extends Controller {

    public $menu_id = 84;

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'only' => ['index', 'create', 'update', 'view', 'delete', 'reporting', 'downloadexcel', 'newitem', 'addrider', 'updateforrider', 'reporting2', 'deletewages', 'addwages'],
                'rules' => [
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                // everything else is denied
                ],
            ],
        ];
    }

    /**
     * Lists all StockDelivery models.
     * @return mixed
     */
    public function actionIndex($year = '') {
        Url::remember();
        if (empty($year))
            $year = date('Y');
        $searchModel = new StockDeliverySearch();
        $searchModel->search_year = $year;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                    'menu_id' => $this->menu_id,
                    'year' => $year
        ]);
    }

    /**
     * Displays a single StockDelivery model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($uuid) {
        return $this->render('view', ['model' => $this->findModel($uuid), 'menu_id' => $this->menu_id]);
    }

    /**
     * Creates a new StockDelivery model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new StockDelivery();
        $model->scenario = 'addUpdate';
        $model->created_dt = date("Y-m-d H:i:s");
        $model->created_by = Yii::$app->user->identity->id;
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        $model->uuid = Uuid::uuid4();
        if ($model->load(Yii::$app->request->post())) {

            $model->upload_file = UploadedFile::getInstance($model, 'upload_file');
            if (!empty($model->upload_file)) {
                $upload_file = 'file-' . $model->uuid . '-' . date("YmdHis") . '.' . $model->upload_file->extension;
                if ($model->upload_file->saveAs('uploads/stock_delivery/' . $upload_file))
                    $model->upload_file = $upload_file;
            }

            $model->receive_proof = UploadedFile::getInstance($model, 'receive_proof');
            if (!empty($model->receive_proof)) {
                $receive_proof = 'receive-proof-' . $model->uuid . '-' . date("YmdHis") . '.' . $model->receive_proof->extension;
                if ($model->receive_proof->saveAs('uploads/stock_delivery/' . $receive_proof))
                    $model->receive_proof = $receive_proof;
            }

            $model->delivery_proof = UploadedFile::getInstance($model, 'delivery_proof');
            if (!empty($model->delivery_proof)) {
                $delivery_proof = 'delivery-proof-' . $model->uuid . '-' . date("YmdHis") . '.' . $model->delivery_proof->extension;
                if ($model->delivery_proof->saveAs('uploads/stock_delivery/' . $delivery_proof))
                    $model->delivery_proof = $delivery_proof;
            }

            $remarks_arr = [];
            if (!empty($_POST['newRemarksNo'])) {
                foreach ($_POST['newRemarksNo'] as $newRemarksNo) {
                    $remarks_arr [] = $_POST['new_remarks_' . $newRemarksNo];
                }
            }
            if (!empty($remarks_arr))
                $model->remarks = json_encode($remarks_arr);

            $item_arr = [];
            if (!empty($_POST['newItemNo'])) {
                foreach ($_POST['newItemNo'] as $newItemNo) {
                    $item_arr[] = [
                        'product_id' => $_POST['new_item_name_' . $newItemNo],
                        'product_qty' => $_POST['new_item_qty_' . $newItemNo]
                    ];
                }
            }
            if (!empty($item_arr))
                $model->stock_details = json_encode($item_arr);

            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog($this->menu_id, 'create', $model->uuid);
                $this->getView()->registerJs("swal.fire({
                    position: 'center-center',
                    type: 'success',
                    title: 'Data has been saved',
                    showConfirmButton: false,
                    timer: 2000,
                }).then(function(result){
                    window.location = 'index.php?r=stockdelivery%2Findex';});");
            }
        }
        return $this->render('create', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Updates an existing StockDelivery model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($uuid) {
        $ParamList = new ParamList();
        $model = $this->findModel($uuid);

        $model->scenario = 'addUpdate';
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;

        $original_upload_file = $model->upload_file;
        $original_receive_proof = $model->receive_proof;
        $original_delivery_proof = $model->delivery_proof;

        if ($model->load(Yii::$app->request->post())) {

            $model->upload_file = UploadedFile::getInstance($model, 'upload_file');
            if (!empty($model->upload_file)) {
                $upload_file = 'file-' . $model->uuid . '-' . date("YmdHis") . '.' . $model->upload_file->extension;
                if ($model->upload_file->saveAs('uploads/stock_delivery/' . $upload_file))
                    $model->upload_file = $upload_file;
            } else {
                $model->upload_file = $original_upload_file;
            }

            $model->receive_proof = UploadedFile::getInstance($model, 'receive_proof');
            if (!empty($model->receive_proof)) {
                $receive_proof = 'receive-proof-' . $model->uuid . '-' . date("YmdHis") . '.' . $model->receive_proof->extension;
                if ($model->receive_proof->saveAs('uploads/stock_delivery/' . $receive_proof))
                    $model->receive_proof = $receive_proof;
            } else {
                $model->receive_proof = $original_receive_proof;
            }

            $model->delivery_proof = UploadedFile::getInstance($model, 'delivery_proof');
            if (!empty($model->delivery_proof)) {
                $delivery_proof = 'delivery-proof-' . $model->uuid . '-' . date("YmdHis") . '.' . $model->delivery_proof->extension;
                if ($model->delivery_proof->saveAs('uploads/stock_delivery/' . $delivery_proof))
                    $model->delivery_proof = $delivery_proof;
            } else {
                $model->delivery_proof = $original_delivery_proof;
            }

            $remarks_arr = [];
            if (!empty($_POST['oldRemarksNo'])) {
                foreach ($_POST['oldRemarksNo'] as $oldRemarksNo) {
                    $remarks_arr [] = $_POST['old_remarks_' . $oldRemarksNo];
                }
            }
            if (!empty($_POST['newRemarksNo'])) {
                foreach ($_POST['newRemarksNo'] as $newRemarksNo) {
                    $remarks_arr [] = $_POST['new_remarks_' . $newRemarksNo];
                }
            }
            if (!empty($remarks_arr))
                $model->remarks = json_encode($remarks_arr);


            $item_arr = [];
            if (!empty($_POST['oldItemNo'])) {
                foreach ($_POST['oldItemNo'] as $oldItemNo) {
                    $item_arr[] = [
                        'product_id' => $_POST['old_item_name_' . $oldItemNo],
                        'product_qty' => $_POST['old_item_qty_' . $oldItemNo]
                    ];
                }
            }
            if (!empty($_POST['newItemNo'])) {
                foreach ($_POST['newItemNo'] as $newItemNo) {
                    $item_arr[] = [
                        'product_id' => $_POST['new_item_name_' . $newItemNo],
                        'product_qty' => $_POST['new_item_qty_' . $newItemNo]
                    ];
                }
            }
            
            $model->stock_details = NULL;
            if (!empty($item_arr))
                $model->stock_details = json_encode($item_arr);

            if ($model->courier != 'rider')
                $model->rider_id = NULL;

            if ($model->courier == 'rider') {
                if ($model->delivery_status == 'delivered' || $model->delivery_status == 'undeliver') {
                    $model->wages_status = 1;
                    $model->wages_rider_id = $model->rider_id;
                }
            }

            if ($model->save()) {

                //update delivery order
                if (!empty($model->do_id)) {
                    if (($modelUpdateDO = DeliveryOrder::findOne($model->do_id)) !== null) {
                        $modelUpdateDO->customer_name = $model->company_name;
                        $modelUpdateDO->customer_address1 = $model->customer_address1;
                        $modelUpdateDO->customer_address2 = $model->customer_address2 . ' ' . $model->customer_address3;
                        $modelUpdateDO->customer_postcode = $model->customer_postcode;
                        $modelUpdateDO->customer_city = $model->customer_city;
                        $modelUpdateDO->customer_state = $model->customer_state;
                        $modelUpdateDO->customer_pic = $model->customer_name;
                        $modelUpdateDO->customer_phone = $model->customer_phone;
                        $modelUpdateDO->po_ref = $model->ref_no;
                        $modelUpdateDO->save(false);
                    }
                }

                //generate delivery order
                if (!empty($model->delivery_date) && empty($model->do_id)) {
                    if ($model->delivery_status != 'initiated' || $model->delivery_status != 'checked') {
                        //insert into : delivery_order
                        $modelDO = new DeliveryOrder();
                        $modelDO->uuid = Uuid::uuid4();
                        $modelDO->status = 'In-Transit';

                        $modelDO->doc_dt = date("Y-m-d");
                        $modelDO->po_ref = $model->ref_no;
                        $modelDO->company_id = '1';

                        $Company = new Company();
                        $countdoc = (int) DeliveryOrder::find()->where(['company_id' => $modelDO->company_id])->count() + 1;
                        $modelDO->doc_no = $Company->getshortcode($modelDO->company_id) . '/DO/' . date("y") . '/' . sprintf("%05d", $countdoc);

                        $modelDO->customer_name = $model->company_name;
                        $modelDO->customer_address1 = $model->customer_address1;
                        $modelDO->customer_address2 = $model->customer_address2 . ' ' . $model->customer_address3;
                        $modelDO->customer_postcode = $model->customer_postcode;
                        $modelDO->customer_city = $model->customer_city;
                        $modelDO->customer_state = $model->customer_state;
                        $modelDO->customer_pic = $model->customer_name;
                        $modelDO->customer_phone = $model->customer_phone;

                        $modelDO->sales_pic = Yii::$app->user->identity->id;
                        $modelDO->created_dt = date("Y-m-d H:i:s");
                        $modelDO->created_by = Yii::$app->user->identity->id;
                        $modelDO->updated_dt = date("Y-m-d H:i:s");
                        $modelDO->updated_by = Yii::$app->user->identity->id;
                        $modelDO->deleted_status = 0;
                        $modelDO->save(false);

                        //update do_id at stock_delivery
                        if (($modelUpdate = StockDelivery::findOne(['uuid' => $uuid])) !== null) {
                            $modelUpdate->do_id = $modelDO->id;
                            $modelUpdate->save(false);
                        }
                    }
                }


                //update delivery_item
                if (!empty($model->do_id)) {

                    $do_no = '';
                    if (($modelGetDO = DeliveryOrder::findOne($model->do_id)) !== null) {
                        $do_no = $modelGetDO->doc_no;
                    }

                    DeliveryOrderItem::deleteAll(['doc_id' => $model->do_id]);
                    StockLog::deleteAll(['do_no' => $do_no]);

                    $item_arr2 = json_decode($model->stock_details, true);
                    if (!empty($item_arr2)) {

                        foreach ($item_arr2 as $item_data) {

                            $product_uom = '';
                            $product_unit_price = '';
                            if (($modelProduct = Product::findOne($item_data['product_id'])) !== null) {
                                $product_uom = $ParamList->getlabel(9, $modelProduct->uom);
                                $product_unit_price = $modelProduct->selling_price;
                            }

                            //insert into : delivery_order_item
                            $modelItem = new DeliveryOrderItem();
                            $modelItem->doc_id = $model->do_id;
                            $modelItem->product_id = $item_data['product_id'];
                            $modelItem->quantity = $item_data['product_qty'];

                            $modelItem->uom = $product_uom;
                            $modelItem->unit_price = $product_unit_price;
                            $modelItem->total = $modelItem->unit_price * $modelItem->quantity;

                            $modelItem->discount = 0;
                            $modelItem->created_dt = date("Y-m-d H:i:s");
                            $modelItem->created_by = Yii::$app->user->identity->id;
                            $modelItem->updated_dt = date("Y-m-d H:i:s");
                            $modelItem->updated_by = Yii::$app->user->identity->id;
                            $modelItem->owner_type = 'company';
                            $modelItem->owner_id = 1;
                            if ($modelItem->save(false)) {



                                //insert into : stock_log
                                $modelStockLog = new StockLog();
                                $modelStockLog->product_id = $modelItem->product_id;
                                $modelStockLog->action_type = 'stockout';
                                $modelStockLog->table_related = 'delivery_order_item';
                                $modelStockLog->data_id = $modelItem->id;
                                $modelStockLog->do_no = $do_no;
                                $modelStockLog->action_by = Yii::$app->user->identity->id;
                                $modelStockLog->action_datetime = date("Y-m-d H:i:s");
                                $modelStockLog->owner_type = $modelItem->owner_type;
                                $modelStockLog->owner_id = $modelItem->owner_id;
                                $modelStockLog->save();
                            }
                        }
                    }
                }

                $Log = new Log();
                $Log->insertlog($this->menu_id, 'update', $model->uuid);
                $this->getView()->registerJs("swal.fire({
                    position: 'center-center',
                    type: 'success',
                    title: 'Data has been saved',
                    showConfirmButton: false,
                    timer: 2000,
                }).then(function(result){
                    window.location = '" . Url::previous() . "';
                });");
            }
        }
        return $this->render('update', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Deletes an existing StockDelivery model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete() {
        if (($model = StockDelivery::findOne($_POST['id'])) !== null) {
            $Log = new Log();
            $Log->insertlog($this->menu_id, 'delete', $model->uuid);
            if ($model->delete())
                return 'success';
        }

        //return $this->redirect(['index']);
    }

    /**
     * Finds the StockDelivery model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return StockDelivery the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($uuid) {
        if (($model = StockDelivery::findOne(['uuid' => $uuid])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionNewitem($itemNo) {

        return '<div id="wrapper_new_item_' . $itemNo . '" class="mb-4 row">
            <input type="hidden" name="newItemNo[]" value="' . $itemNo . '">
            <div class="col-8">' . Html::dropDownList('new_item_name_' . $itemNo, null, ArrayHelper::map(Product::find()->where(['=', 'status', '1'])->all(), 'id', 'name'), ['class' => 'form-control kt-selectpicker', 'prompt' => '-- Please choose --']) . '</div>
            <div class="col-3"><input type="text" name="new_item_qty_' . $itemNo . '" class="form-control"></div>
            <div class="col-1"><button type="button" class="btn btn-danger" onclick="deletenewitem(' . $itemNo . ')">Delete</button></div>
        </div>';
    }

    public function actionDownloadexcel($company_name = '', $customer_name = '', $stock_details = '', $delivery_status = '', $courier = '', $tracking_no = '', $customer_postcode = '', $customer_state = '', $details_status = '', $customer_address1 = '', $industry = '') {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->setCellValue('A1', 'Company');
        $sheet->setCellValue('B1', 'Industry');
        $sheet->setCellValue('C1', 'Receiver Name');
        $sheet->setCellValue('D1', 'Phone Number');
        $sheet->setCellValue('E1', 'Email Address');
        $sheet->setCellValue('F1', 'Address Line 1');
        $sheet->setCellValue('G1', 'Address Line 2');
        $sheet->setCellValue('H1', 'Address Line 3');
        $sheet->setCellValue('I1', 'Postcode');
        $sheet->setCellValue('J1', 'City');
        $sheet->setCellValue('K1', 'State');
        $sheet->setCellValue('L1', 'Reference Number');
        $sheet->setCellValue('M1', 'Item');
        $sheet->setCellValue('N1', 'Information Status');
        $sheet->setCellValue('O1', 'Delivery Date');
        $sheet->setCellValue('P1', 'Delivery Status');
        $sheet->setCellValue('Q1', 'Courier');
        $sheet->setCellValue('R1', 'Tracking No');
        $sheet->setCellValue('S1', 'Receive Date');
        $sheet->setCellValue('T1', 'Remarks');
        $sheet->getStyle("A1:T1")->getFont()->setBold(true);

        $query = StockDelivery::find();
        if (!empty($company_name))
            $query->andFilterWhere(['LIKE', 'company_name', $company_name]);
        if (!empty($customer_name))
            $query->andFilterWhere(['LIKE', 'customer_name', $customer_name]);
        if (!empty($delivery_status))
            $query->andFilterWhere(['=', 'delivery_status', $delivery_status]);
        if (!empty($courier))
            $query->andFilterWhere(['=', 'courier', $courier]);
        if (!empty($tracking_no))
            $query->andFilterWhere(['LIKE', 'tracking_no', $tracking_no]);
        if (!empty($customer_postcode))
            $query->andFilterWhere(['=', 'customer_postcode', $customer_postcode]);
        if (!empty($customer_state))
            $query->andFilterWhere(['=', 'customer_state', $customer_state]);
        if (!empty($details_status))
            $query->andFilterWhere(['=', 'details_status', $details_status]);
        if (!empty($stock_details))
            $query->andFilterWhere(['LIKE', 'stock_details', '"product_id":"' . $stock_details . '"']);
        if (!empty($customer_address1)) {
            $query->andFilterWhere(['OR',
                ['LIKE', 'customer_address1', $customer_address1],
                ['LIKE', 'customer_address2', $customer_address1],
                ['LIKE', 'customer_address3', $customer_address1],
                ['LIKE', 'customer_city', $customer_address1],
            ]);
        }
        if (!empty($industry))
            $query->andFilterWhere(['LIKE', 'industry', $industry]);
        $query->orderBy(['id' => SORT_DESC]);
        $model = $query->all();

        $count2 = 0;
        $count = 1;

        $ParamList = new ParamList();

        if (!empty($model)) {
            foreach ($model as $row) {
                $count2++;
                $count++;

                $item_list = '';
                $item_arr = json_decode($row->stock_details, true);
                if (!empty($item_arr)) {
                    foreach ($item_arr as $item_data) {
                        if (($modelProduct = Product::findOne([$item_data['product_id']])) !== null) {
                            $item_list .= $modelProduct->name . ' X ' . $item_data['product_qty'] . PHP_EOL;
                        }
                    }
                }

                $remarks_list = '';
                $remarks_arr = json_decode($row->remarks);
                if (!empty($remarks_arr)) {
                    foreach ($remarks_arr as $remarks) {
                        $remarks_list .= $remarks . PHP_EOL;
                    }
                }

                $sheet->setCellValue('A' . $count, $row->company_name);
                $sheet->setCellValue('B' . $count, $row->industry);
                $sheet->setCellValue('C' . $count, $row->customer_name);
                $sheet->setCellValue('D' . $count, $row->customer_phone);
                $sheet->setCellValue('E' . $count, $row->customer_email);
                $sheet->setCellValue('F' . $count, $row->customer_address1);
                $sheet->setCellValue('G' . $count, $row->customer_address2);
                $sheet->setCellValue('H' . $count, $row->customer_address3);
                $sheet->setCellValue('I' . $count, $row->customer_postcode);
                $sheet->setCellValue('J' . $count, $row->customer_city);
                $sheet->setCellValue('K' . $count, $ParamList->getlabel(3, $row->customer_state));
                $sheet->setCellValue('L' . $count, $row->ref_no);
                $sheet->setCellValue('M' . $count, $item_list);
                $sheet->setCellValue('N' . $count, $ParamList->getlabel(48, $row->details_status));
                $sheet->setCellValue('O' . $count, $row->delivery_date);
                $sheet->setCellValue('P' . $count, $ParamList->getlabel(46, $row->delivery_status));
                $sheet->setCellValue('Q' . $count, $ParamList->getlabel(47, $row->courier));
                $sheet->setCellValue('R' . $count, $row->tracking_no);
                $sheet->setCellValue('S' . $count, $row->receive_date);
                $sheet->setCellValue('T' . $count, $remarks_list);



                $sheet->getStyle('M' . $count)->getAlignment()->setWrapText(true);
                $sheet->getStyle('T' . $count)->getAlignment()->setWrapText(true);
            }
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="Stock Delivery.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        die();
    }

    public function actionReporting($start_date = '', $end_date = '', $year = '') {
        if (empty($year))
            $year = date('Y');
        if (empty($start_date)) {
            if ($year == date('Y'))
                $start_date = $year . date('-m-01');
            else
                $start_date = $year . date('-01-01');
        }
        if (empty($end_date)) {
            if ($year == date('Y'))
                $end_date = $year . date('-m-d');
            else
                $end_date = $year . date('-12-31');
        }
        return $this->render('reporting', ['menu_id' => $this->menu_id, 'start_date' => $start_date, 'end_date' => $end_date, 'year' => $year]);
    }

    public function actionAddrider($rider_name = '', $rider_phone = '') {

        $model = new Rider();
        $model->name = $rider_name;
        $model->phone = $rider_phone;
        if ($model->save(false)) {
            $output = '';
            $model2 = Rider::find()->orderBy(['name' => SORT_ASC])->all();
            if (!empty($model2)) {
                foreach ($model2 as $row) {
                    $output .= '<option value="' . $row->id . '">' . $row->name . '</option>';
                }
            }
            return $output;
        }
    }

    public function actionUpdateforrider($delivery_id, $type, $val) {
        $status = 'failed';
        if (($model = StockDelivery::findOne($delivery_id)) !== null) {
            if ($type == 'rider_wages_status')
                $model->rider_wages_status = $val;
            if ($type == 'rider_wages_amount')
                $model->rider_wages_amount = $val;
            if ($model->save(false))
                $status = 'success';
        }

        return$status;
    }

    public function actionReporting2() {
        $query = StockDelivery::find();
        $request = Yii::$app->request;
        $post = $request->post();
        //print_r($post);
        if (!empty($post)) {
            if (!empty($request->post('search_year')))
                $query->andfilterwhere(['=', 'YEAR(created_dt)', $request->post('search_year')]);
            if (!empty($request->post('company_name')))
                $query->andfilterwhere(['LIKE', 'company_name', $request->post('company_name')]);
            if (!empty($request->post('industry')))
                $query->andfilterwhere(['LIKE', 'industry', $request->post('industry')]);
            if (!empty($request->post('customer_name')))
                $query->andfilterwhere(['LIKE', 'customer_name', $request->post('customer_name')]);
            if (!empty($request->post('customer_phone')))
                $query->andfilterwhere(['LIKE', 'customer_phone', $request->post('customer_phone')]);
            if (!empty($request->post('customer_email')))
                $query->andfilterwhere(['LIKE', 'customer_email', $request->post('customer_email')]);
            if (!empty($request->post('customer_address'))) {
                $query->andfilterwhere(['OR',
                    ['LIKE', 'customer_address1', $request->post('customer_address')],
                    ['LIKE', 'customer_address2', $request->post('customer_address')],
                    ['LIKE', 'customer_address3', $request->post('customer_address')]
                ]);
            }
            if (!empty($request->post('customer_postcode')))
                $query->andfilterwhere(['LIKE', 'customer_postcode', $request->post('customer_postcode')]);
            if (!empty($request->post('customer_city')))
                $query->andfilterwhere(['LIKE', 'customer_city', $request->post('customer_city')]);
            if (!empty($request->post('customer_state')))
                $query->andfilterwhere(['=', 'customer_state', $request->post('customer_state')]);
            if (!empty($request->post('ref_no')))
                $query->andfilterwhere(['LIKE', 'ref_no', $request->post('ref_no')]);
            if (!empty($request->post('stock_details')))
                $query->andfilterwhere(['LIKE', 'stock_details', '"product_id":"' . $request->post('stock_details') . '"']);
            if (!empty($request->post('details_status')))
                $query->andfilterwhere(['=', 'details_status', $request->post('details_status')]);
            if (!empty($request->post('delivery_status')))
                $query->andfilterwhere(['=', 'delivery_status', $request->post('delivery_status')]);
            if (!empty($request->post('delivery_date_start')) && !empty($request->post('delivery_date_end')))
                $query->andfilterwhere(['BETWEEN', 'delivery_date', $request->post('delivery_date_start'), $request->post('delivery_date_end')]);
            if (!empty($request->post('do_id'))) {
                $query->innerJoin('delivery_order', 'delivery_order.id=stock_delivery.do_id');
                $query->andfilterwhere(['LIKE', 'delivery_order.doc_no', $request->post('do_id')]);
            }
            if (!empty($request->post('courier')))
                $query->andfilterwhere(['=', 'courier', $request->post('courier')]);
            if (!empty($request->post('tracking_no')))
                $query->andfilterwhere(['LIKE', 'tracking_no', $request->post('tracking_no')]);
            if (!empty($request->post('receive_date_start')) && !empty($request->post('receive_date_end')))
                $query->andfilterwhere(['BETWEEN', 'receive_date', $request->post('receive_date_start'), $request->post('receive_date_end')]);
            if (!empty($request->post('remarks'))) {
                $query->andfilterwhere(['OR',
                    ['LIKE', 'remarks', $request->post('remarks')],
                    ['LIKE', 'rider_remarks', $request->post('remarks')]
                ]);
            }
            if (!empty($request->post('rider_id')))
                $query->andfilterwhere(['OR', ['=', 'rider_id', $request->post('rider_id')], ['=', 'wages_rider_id', $request->post('rider_id')]]);

            if (!empty($request->post('rider_wages_status'))) {
                $query->andfilterwhere(['AND',
                    ['=', 'wages_status', 1],
                    ['=', 'rider_wages_status', $request->post('rider_wages_status')]
                ]);
            }
            if (!empty($request->post('rider_wages_amount'))) {
                $query->andfilterwhere(['AND',
                    ['=', 'wages_status', 1],
                    ['=', 'rider_wages_amount', $request->post('rider_wages_amount')]
                ]);
            }

            $data_list_arr = $request->post('data_list');
            $header_attr = [];
            $result_arr = [];
            if (!empty($data_list_arr)) {
                foreach ($data_list_arr as $data_list_code) {
                    if ($data_list_code == 'company_name')
                        $header_attr[] = 'Company';
                    if ($data_list_code == 'industry')
                        $header_attr[] = 'Industry';
                    if ($data_list_code == 'customer_name')
                        $header_attr[] = 'Receiver Name';
                    if ($data_list_code == 'customer_phone')
                        $header_attr[] = 'Phone Number';
                    if ($data_list_code == 'customer_email')
                        $header_attr[] = 'Email Address';
                    if ($data_list_code == 'customer_address1')
                        $header_attr[] = 'Address Line 1';
                    if ($data_list_code == 'customer_address2')
                        $header_attr[] = 'Address Line 2';
                    if ($data_list_code == 'customer_address3')
                        $header_attr[] = 'Address Line 3';
                    if ($data_list_code == 'customer_postcode')
                        $header_attr[] = 'Postcode';
                    if ($data_list_code == 'customer_city')
                        $header_attr[] = 'City';
                    if ($data_list_code == 'customer_state')
                        $header_attr[] = 'State';
                    if ($data_list_code == 'ref_no')
                        $header_attr[] = 'Reference Number';
                    if ($data_list_code == 'stock_details') {
                        $header_attr[] = 'Product Name';
                        $header_attr[] = 'Quantity';
                    }
                    if ($data_list_code == 'details_status')
                        $header_attr[] = 'Information Status';
                    if ($data_list_code == 'delivery_status')
                        $header_attr[] = 'Delivery Status';
                    if ($data_list_code == 'delivery_date')
                        $header_attr[] = 'Delivery Date';
                    if ($data_list_code == 'do_id')
                        $header_attr[] = 'DO Number';
                    if ($data_list_code == 'courier')
                        $header_attr[] = 'Courier';
                    if ($data_list_code == 'tracking_no')
                        $header_attr[] = 'Tracking No';
                    if ($data_list_code == 'receive_date')
                        $header_attr[] = 'Receive Date';
                    if ($data_list_code == 'remarks')
                        $header_attr[] = 'Remarks';
                    if ($data_list_code == 'rider_id')
                        $header_attr[] = 'Rider';
                    if ($data_list_code == 'rider_wages_status')
                        $header_attr[] = 'Rider Wages Status';
                    if ($data_list_code == 'rider_wages_amount')
                        $header_attr[] = 'Rider Wages Amount(RM)';
                }
            }

            $ParamList = new ParamList();

            $query->orderBy(['id' => SORT_DESC]);
            $query->groupby('id');
            //echo $query->createCommand()->getRawSql();
            $model = $query->all();
            if (!empty($model)) {
                foreach ($model as $row) {


                    $item_arr = json_decode($row->stock_details, true);
                    if (!empty($item_arr)) {
                        foreach ($item_arr as $item_data) {
                            $data_arr = [];
                            if (!empty($data_list_arr)) {
                                foreach ($data_list_arr as $data_list_code) {

                                    if ($data_list_code == 'company_name')
                                        $data_arr[] = strtoupper($row->company_name);
                                    if ($data_list_code == 'industry')
                                        $data_arr[] = strtoupper($row->industry);
                                    if ($data_list_code == 'customer_name')
                                        $data_arr[] = strtoupper($row->customer_name);
                                    if ($data_list_code == 'customer_phone')
                                        $data_arr[] = strtoupper($row->customer_phone);
                                    if ($data_list_code == 'customer_email')
                                        $data_arr[] = $row->customer_email;
                                    if ($data_list_code == 'customer_address1')
                                        $data_arr[] = strtoupper($row->customer_address1);
                                    if ($data_list_code == 'customer_address2')
                                        $data_arr[] = strtoupper($row->customer_address2);
                                    if ($data_list_code == 'customer_address3')
                                        $data_arr[] = strtoupper($row->customer_address3);
                                    if ($data_list_code == 'customer_postcode')
                                        $data_arr[] = strtoupper($row->customer_postcode);
                                    if ($data_list_code == 'customer_city')
                                        $data_arr[] = strtoupper($row->customer_city);
                                    if ($data_list_code == 'customer_state')
                                        $data_arr[] = strtoupper($ParamList->getlabel(3, $row->customer_state));
                                    if ($data_list_code == 'ref_no')
                                        $data_arr[] = strtoupper($row->ref_no);
                                    if ($data_list_code == 'stock_details') {
                                        $product_name = '';
                                        if (($modelProduct = Product::findOne([$item_data['product_id']])) !== null) {
                                            $product_name = $modelProduct->name;
                                        }
                                        $data_arr[] = strtoupper($product_name);
                                        $data_arr[] = $item_data['product_qty'];
                                    }
                                    if ($data_list_code == 'details_status')
                                        $data_arr[] = strtoupper($ParamList->getlabel(48, $row->details_status));
                                    if ($data_list_code == 'delivery_status')
                                        $data_arr[] = strtoupper($ParamList->getlabel(46, $row->delivery_status));
                                    if ($data_list_code == 'delivery_date')
                                        $data_arr[] = $row->delivery_date;
                                    if ($data_list_code == 'do_id') {
                                        $do_number = '';
                                        if (($modelDO = DeliveryOrder::findOne($row->do_id)) !== null) {
                                            $do_number = $modelDO->doc_no;
                                        }
                                        $data_arr[] = strtoupper($do_number);
                                    }
                                    if ($data_list_code == 'courier')
                                        $data_arr[] = strtoupper($ParamList->getlabel(47, $row->courier));
                                    if ($data_list_code == 'tracking_no')
                                        $data_arr[] = strtoupper($row->tracking_no);
                                    if ($data_list_code == 'receive_date')
                                        $data_arr[] = $row->receive_date;
                                    if ($data_list_code == 'remarks') {

                                        $remarks_list = '';
                                        if (!empty($row->rider_remarks)) {
                                            $remarks_list .= $row->rider_remarks . PHP_EOL;
                                        }

                                        $remarks_arr = json_decode($row->remarks);
                                        if (!empty($remarks_arr)) {
                                            foreach ($remarks_arr as $remarks) {
                                                $remarks_list .= $remarks . PHP_EOL;
                                            }
                                        }


                                        $data_arr[] = strtoupper($remarks_list);
                                    }
                                    if ($data_list_code == 'rider_id') {
                                        $rider_name = '';
                                        if (($modelRider = Rider::findOne($row->wages_rider_id)) !== null) {
                                            $rider_name = $modelRider->name;
                                        }
                                        $data_arr[] = strtoupper($rider_name);
                                    }
                                    if ($data_list_code == 'rider_wages_status')
                                        $data_arr[] = strtoupper($row->rider_wages_status);
                                    if ($data_list_code == 'rider_wages_amount')
                                        $data_arr[] = $row->rider_wages_amount;
                                }
                            }
                            $result_arr[] = $data_arr;
                        }
                    }
                }
            }

            //print_r($result_arr);
            //die();

            if ($request->post('excel') == '1') {
                $spreadsheet = new Spreadsheet();
                $sheet = $spreadsheet->getActiveSheet();
                $cellNoArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
                if (!empty($header_attr)) {
                    $count_header = 0;
                    foreach ($header_attr as $header_label) {
                        $sheet->setCellValue($cellNoArr[$count_header] . '1', strtoupper($header_label));
                        $count_header++;
                    }
                }
                $sheet->getStyle("A1:Z1")->getFont()->setBold(true);

                $count_row = 1;
                if (!empty($result_arr)) {
                    foreach ($result_arr as $result_data) {
                        $count_row++;
                        $result_data_arr = $result_data;
                        if (!empty($result_data_arr)) {
                            $count_cell = 0;
                            foreach ($result_data_arr as $result_label) {
                                $sheet->setCellValue($cellNoArr[$count_cell] . $count_row, $result_label);
                                $count_cell++;
                            }
                        }
                    }
                }
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="Stock Delivery Report.xlsx"');
                header('Cache-Control: max-age=0');
                header('Cache-Control: max-age=1');
                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save('php://output');
                die();
            }
            if ($request->post('pdf') == '1') {

                $content = '<h4>Stock Delivery Report</h4><table class="table table-bordered table-striped">';
                if (!empty($header_attr)) {
                    $content .= '<thead><tr><th>#</th>';
                    foreach ($header_attr as $header_label) {
                        $content .= '<th>' . strtoupper($header_label) . '</th>';
                    }
                    $content .= '<tr></thead>';
                }

                $count = 0;
                if (!empty($result_arr)) {
                    $content .= '<tbody>';
                    foreach ($result_arr as $result_data) {
                        $count++;
                        $content .= '<tr>';
                        $content .= '<td>' . $count . '</td>';

                        $result_data_arr = $result_data;
                        if (!empty($result_data_arr)) {
                            foreach ($result_data_arr as $result_label) {
                                $content .= '<td>' . $result_label . '</td>';
                            }
                        }
                        $content .= '</tr>';
                    }
                    $content .= '</tbody>';
                }
                $content .= '</table>';

                $pdf = new Pdf([
                    'mode' => Pdf::MODE_CORE,
                    'filename' => 'Stock Delivery Report.pdf',
                    'format' => Pdf::FORMAT_A4,
                    'orientation' => Pdf::ORIENT_LANDSCAPE,
                    'destination' => Pdf::DEST_DOWNLOAD,
                    'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
                    'cssInline' => 'body,table td{font-size:11px;Arial, Helvetica, sans-serif;}',
                    'content' => $content,
                    'options' => ['setAutoTopMargin' => 'stretch'],
                ]);
                return $pdf->render();
            }
        }
        return $this->render('reporting2', ['menu_id' => $this->menu_id]);
    }

    public function actionDeletewages() {
        if (($model = StockDelivery::findOne($_POST['id'])) !== null) {
            $model->wages_status = 0;
            $model->wages_rider_id = NULL;
            if ($model->save(false))
                return 'success';
        }
    }

    public function actionAddwages() {
        $do_number = $_POST['do_number'];
        $rider_id = $_POST['rider_id'];
        $status = 'failed';
        if (($model = DeliveryOrder::findOne(['doc_no' => $do_number])) !== null) {
            $do_id = $model->id;
            if (($model2 = StockDelivery::findOne(['do_id' => $do_id])) !== null) {
                $model2->wages_status = 1;
                $model2->wages_rider_id = $rider_id;
                if ($model2->save(false))
                    $status = 'success';
            }
        }
        return $status;
    }

}