<?php

namespace app\controllers;

use Yii;
use app\base\Common;
use app\base\Model;
use app\models\Labref;
use app\models\Labresultmapping;
use app\models\Labtestmapping;
use app\models\Labsamplerequest;
use app\models\LabsamplerequestSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\helpers\ArrayHelper;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * LabsamplerequestController implements the CRUD actions for Labsamplerequest model.
 */
class LabsamplerequestController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index', 'create', 'update', 'view', 'delete', 'depajax', 'ajax'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Labsamplerequest models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new LabsamplerequestSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Labsamplerequest model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionDepajax()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = "'" . $request->get('id') . "'";
        if ($request->isPost)
            $id = "'" . $request->post('id') . "'";
        $model = Common::labServiceCheck($id);
        return $model;
    }

    public function actionAjax()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new Labsamplerequest;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = "'" . $request->get('id') . "'";
        if ($request->isPost)
            $id = "'" . $request->post('id') . "'";
        $models = Labtestmapping::find()->innerJoinWith('specimens')->innerJoinWith('tests T')->where("T.lab_dept_code IN ($id)")->orderBy(["T.lab_test_name" => SORT_ASC])->asArray()->all();
        foreach ($models as $key => $value) {
            $Labtests = ArrayHelper::map(Labresultmapping::find()->where(["lab_result_mapng_test" => $value["tests"]["lab_test_code"]])->orderBy(["lab_result_mapng_test" => SORT_ASC])->asArray()->all(), 'lab_result_mapng_id', 'lab_result_mapng_result');
            $models[$key]['testresults'] = $Labtests;
            // $models[$key]['testresults'] = Labresultmapping::find()->where(["lab_result_mapng_test" => $value["tests"]["lab_test_code"]])->orderBy(["lab_result_mapng_test" => SORT_ASC])->asArray()->all();
        }
        return $models;
        // print_r($models);
        return;
        print_r($models[0]->attributes);
        echo "<br>";
        print_r($models[0]->tests->attributes);
        echo "<br>";
        print_r($models[0]->specimens->attributes);

        // echo count($models);
        // return ;
        return $this->render('ajax', [
            'model' => $model,
            'models' => $models,
        ]);
    }

    /**
     * Creates a new Labsamplerequest model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    /*
    public function actionCreate()
    {
        $model = new Labsamplerequest();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->lab_smple_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    */
    
    public function actionCreate()
    {
        $model = new Labsamplerequest;
        $model->scenario = 'create';
        $models = [new Labsamplerequest];

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

            // ajax validation
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $models = [];
                $models = Model::createMultiple(Labsamplerequest::classname());
                Model::loadMultiple($models, Yii::$app->request->post());
                foreach ($models as $key => $value) {
                    if(isset($value->lab_smple_spcmn_clctd[0]))
                        $value->lab_smple_spcmn_clctd = $value->lab_smple_spcmn_clctd[0];
                }
                // return ActiveForm::validateMultiple($models);
                return ArrayHelper::merge(
                    ActiveForm::validateMultiple($models),
                    ActiveForm::validate($model)
                );
            }

            $post = [];
            $formName = $model->formName();
            $formVars = Yii::$app->request->post($formName);
            
            foreach($formVars as $key => $val) {
                if(is_array($val) && is_numeric($key)) :
                    $post[$formName][] = $val;
                    unset($formVars[$key]);
                endif;
            }
            
            $models   = [];
            // $loc = substr($model->lab_smple_part_id, 0, 2);
            $loc = substr($formVars['lab_smple_part_id'], 0, 2);

            if ($loc != "") {
                $Labrefmodel = Labref::find()->where(['lab_ref_loc' => $loc])->one();
                if ($Labrefmodel === null)
                    $Labrefmodel = new Labref;
                $ref_code = $Labrefmodel->lab_ref_code;
                $refid = ($ref_code+1);
            } else {
                $Labrefmodel = new Labref;
                $refid = 1;
            }
            
            if($loc == "")
                $code = 'LA-';
            else
                $code = $loc.'-LA-';

            $vno = str_pad($refid, 5, 0, STR_PAD_LEFT);
            $accs_no_rec = $code.$vno;
            $Labrefmodel->lab_ref_loc = $loc;
            $Labrefmodel->lab_ref_code = $vno;

            foreach($post[$formName] as $k => $p) {
                $models[] = new Labsamplerequest;
                $posts[$formName][$k] = array_merge($p, $formVars);
                $posts[$formName][$k]['lab_smple_acc_no'] = $accs_no_rec;
                if(isset($posts[$formName][$k]['lab_smple_spcmn_clctd'][0]))
                    $posts[$formName][$k]['lab_smple_spcmn_clctd'] = $posts[$formName][$k]['lab_smple_spcmn_clctd'][0];
            }
            
            Model::loadMultiple($models, $posts);
            $valid = Model::validateMultiple($models);
            
            // foreach ($models as $key => $value) {
            //     print_r($value->attributes);
            //     echo "<br/>";
            //     print_r($value->errors);
            //     echo "<br/>";
            // }
            // exit;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    foreach ($models as $modelAddress) {
                        if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                    $Labrefmodel->save();
                    $flag = Common::saveLabResults($models);

                    if ($flag) {
                        $transaction->commit();
                        Yii::$app->session->setFlash('success', 'Lab Test has been Saved Successfully with the Request Number is '.$accs_no_rec);
                        return $this->redirect(['/'.Yii::$app->controller->id]);
                        // return $this->redirect(['view', 'id' => $models[0]->lab_smple_id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
        
        return $this->render('create', [
            'model' => $model,
            'models' => (empty($models)) ? [new Labsamplerequest] : $models,
        ]);
    }

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

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->lab_smple_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    */

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        // $models = [$this->findModel($id)];
        $models = $this->findModels($id);

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

            // ajax validation
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $models = [];
                $models = Model::createMultiple(Labsamplerequest::classname());
                Model::loadMultiple($models, Yii::$app->request->post());
                foreach ($models as $key => $value) {
                    if(isset($value->lab_smple_spcmn_clctd[0]))
                        $value->lab_smple_spcmn_clctd = $value->lab_smple_spcmn_clctd[0];
                }
                // return ActiveForm::validateMultiple($models);
                return ArrayHelper::merge(
                    ActiveForm::validateMultiple($models),
                    ActiveForm::validate($model)
                );
            }

            $post = [];
            $formName = $model->formName();
            $formVars = Yii::$app->request->post($formName);
            
            foreach($formVars as $key => $val) {
                if(is_array($val) && is_numeric($key)) :
                    $post[$formName][] = $val;
                    unset($formVars[$key]);
                endif;
            }
            
            $recmodels = $models;
            $models   = [];
            foreach($post[$formName] as $k => $p) {
                if(empty($p["lab_smple_id"])) {
                    $models[] = new Labsamplerequest;
                    $p["create_user"] = $model->create_user;
                    $p["lab_smple_sur_id"] = $model->lab_smple_sur_id;
                }
                else
                    $models[] = $this->findModel($p["lab_smple_id"]);

                if(isset($p['lab_smple_spcmn_clctd'][0]))
                    $p['lab_smple_spcmn_clctd'] = $p['lab_smple_spcmn_clctd'][0];
                $posts[$formName][$k] = array_merge($p, $formVars);
            }
            
            Model::loadMultiple($models, $posts);
            $valid = Model::validateMultiple($models);
            
            // foreach ($models as $key => $value) {
            //     print_r($value->attributes);
            //     echo "<br/>";
            // }
            // exit;

            if(count($recmodels) > count($posts[$formName])) {
                $delid = substr(Yii::$app->request->post()[$formName]["delrec"], 0, -1);
                foreach (array_unique(explode(",", $delid)) as $key => $value) {
                    $this->findModel($value)->delete();
                }
            }

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    foreach ($models as $modelAddress) {
                        if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                    $flag = Common::saveLabResults($models);

                    if ($flag) {
                        $transaction->commit();
                        Yii::$app->session->setFlash('success', 'Lab Test has been Updated Successfully');
                        return $this->redirect(['/'.Yii::$app->controller->id]);
                        // return $this->redirect(['view', 'id' => $models[0]->lab_smple_id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
        
        // foreach ($models as $key => $value) {
        //     print_r($value->attributes);
        //     echo "<br/>";
        // }
        // exit;
        
        return $this->render('update', [
            'model' => $model,
            'models' => (empty($models)) ? [new Labsamplerequest] : $models,
        ]);
    }

    /**
     * Deletes an existing Labsamplerequest model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        // $this->findModel($id)->delete();
        $model = $this->findModel($id);
        $sur_id = $model->lab_smple_sur_id;
        $pid_id = $model->lab_smple_part_id;
        $ref_no = $model->lab_smple_acc_no;
        Labsamplerequest::deleteAll("lab_smple_sur_id = '$sur_id' AND lab_smple_part_id = '$pid_id' AND lab_smple_acc_no = '$ref_no'");

        return $this->redirect(['/'.Yii::$app->controller->id]);
    }

    /**
     * Finds the Labsamplerequest model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Labsamplerequest the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Labsamplerequest::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function findModels($id)
    {
        $model = Labsamplerequest::findOne($id);
        $sur_id = $model->lab_smple_sur_id;
        $pid_id = $model->lab_smple_part_id;
        $ref_no = $model->lab_smple_acc_no;
        $department = $model->tests->lab_dept_code;

        // $DepCodes = ArrayHelper::map(Labsamplerequest::find()->innerJoinWith('tests T')->where(['lab_smple_sur_id' => $sur_id])->andWhere(['lab_smple_part_id' => $pid_id])->orderBy(["T.lab_test_name" => SORT_ASC])->asArray()->all(), 'tests.lab_dept_code', 'tests.lab_dept_code');
        // echo $id = "'" . implode($DepCodes, "','") . "'";

        if (($models = Labsamplerequest::find()->innerJoinWith('tests T')->where(['lab_smple_sur_id' => $sur_id])->andWhere(['lab_smple_part_id' => $pid_id])->andWhere(['lab_smple_acc_no' => $ref_no])->andWhere(['T.lab_dept_code' => $department])->all()) !== null) {
            return $models;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
