/**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = WorkloadPtdisc::find()->byward();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['ref' => $this->ref, 'ward' => $this->ward, 'lastupdate' => $this->lastupdate]);
     $query->andFilterWhere(['like', 'hn', $this->hn])->andFilterWhere(['like', 'an', $this->an])->andFilterWhere(['like', 'title', $this->title])->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'surname', $this->surname])->andFilterWhere(['like', 'movestatus', $this->movestatus]);
     return $dataProvider;
 }
    /**
     * Creates a new NursePatient model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($event_ref)
    {
        $ward = Yii::$app->user->identity->ward;
        $ward2 = Yii::$app->user->identity->ward2;
        $event = NurseEvent::findOne($event_ref);
        $event_patient = NursePatient::find()->where(['event_ref' => $event_ref, 'disc_type' => 0])->orderBy('bed_no asc')->all();
        //        echo $event_patient->createCommand()->getRawSql();
        //        die();
        $event_patient2 = NursePatient::find()->where("event_ref = {$event_ref} and an not in (select an from workload_ptdisc where ward = '{$ward}' and lastupdate <= '{$event->date} 23:59:59' ) ")->orderBy('bed_no asc')->all();
        $event_prevp = 0;
        $event_prevd = '';
        $patient_no = 0;
        $diag = new WorkloadDiag();
        $diag_an = WorkloadDiag::find()->all();
        $event_date = new DateTime($event->date);
        if ($event->period == 1) {
            // ถ้าเป็นเวรดึก เวรก่อนหน้า จะเป็นเวรเช้าของวันก่อนหน้า
            $event_prevp = 3;
            $event_date->modify('-1 day');
            $event_prevd = $event_date->format('Y-m-d');
        } else {
            $event_prevp = $event->period - 1;
            $event_prevd = $event->date;
        }
        $event_prev = NurseEvent::find()->where(['date' => $event_prevd, 'period' => $event_prevp, 'ward' => $ward])->one();
        $prev_data = null;
        $check_prev = "";
        if ($event_patient == null) {
            if ($event_prev == null) {
                $prev_data = null;
                $check_prev = "no eventprev no prev no patient";
                Yii::$app->getSession()->setFlash('alert', ['body' => 'ไม่มีข้อมูลย้อนหลัง กรุณากรอกข้อมูล', 'options' => ['class' => 'alert-danger']]);
            } else {
                $prev_data = NursePatient::find()->where(['event_ref' => $event_prev->ref])->orderBy('bed_no asc')->all();
                if ($prev_data == null) {
                    $check_prev = "no prev no patient";
                    Yii::$app->getSession()->setFlash('alert', ['body' => 'ไม่มีข้อมูลย้อนหลัง กรุณากรอกข้อมูล', 'options' => ['class' => 'alert-warning']]);
                } else {
                    $check_prev = "have prev no patient";
                    Yii::$app->getSession()->setFlash('alert', ['body' => 'มีข้อมูลย้อนหลัง กรุณาบันทึกข้อมูล', 'options' => ['class' => 'alert-warning']]);
                }
            }
        } else {
            $prev_data = NursePatient::find()->where(['event_ref' => $event_ref])->orderBy('bed_no asc')->all();
            $check_prev = "have patient";
            Yii::$app->getSession()->setFlash('alert', ['body' => 'มีข้อมูลแล้ว', 'options' => ['class' => 'alert-info']]);
        }
        $sql = 'select distinct * from (select * from ipd_ipd i
where i.ward in (' . $ward . ', ' . $ward2 . ')
and (i.disc is null or i.disc = "0000-00-00" or i.disc = "" or i.disc = "' . $event->date . '")
and i.admite <= "' . $event->date . '"
and not exists (
select "x" from db_nurse.workload_ptdisc p 
where p.ward in (' . $ward . ', ' . $ward2 . ') and i.an = p.an ' . 'and (p.lastupdate < "' . $event->date . '" 
                    or lastupdate between "' . $event->date . ' 00:00:00" and "' . $event->date . ' 23:59:59"))
union all
select * from ipd_ipd i
where an in (select an 
from hospdata.ipd_moveward 
where oldward in (' . $ward . ', ' . $ward2 . ')
and date	>= "' . $event->date . '" )
and i.admite <= "' . $event->date . '"
and (i.disc is null or i.disc = "0000-00-00" or i.disc = "" or i.disc = "' . $event->date . '")
and not exists (
select "x" from db_nurse.workload_ptdisc p 
where p.ward in (' . $ward . ', ' . $ward2 . ') and i.an = p.an ' . 'and (p.lastupdate < "' . $event->date . '" ' . 'or lastupdate between "' . $event->date . ' 00:00:00" and "' . $event->date . ' 23:59:59"))) nurse_db';
        $patient = '';
        if ($event->patient_flag == 1) {
            $patient = $event_patient;
            //ถ้ามีข้อมูลคนไข้ใน วันที่และเวรนี้แล้ว ให้ดึงข้อมูลที่มีอยู่มาแก้ไข
        } else {
            $patient = IpdIpd::findBySql($sql)->all();
            //ถ้าไม่มีข้อมูลคนไข้ หรือไม่เคยบันทึกเลย ให้ดึงจากฐานข้อมูลใน ipd_ipd
        }
        $model = new NursePatient();
        if (isset($_POST['NursePatient'])) {
            if ($event_patient != null) {
                if ($model->validate()) {
                    foreach ($event_patient as $v) {
                        if (isset($_POST['pt_id'][$v->hn])) {
                            // ถ้า checkbox = ture ให้บันทึกข้อมูล ถ้าไม่มีให้ข้าม
                            $model = NursePatient::find()->where(['event_ref' => $v->event_ref, 'hn' => $v->hn])->one();
                            $model->attributes = $_POST['NursePatient'][$v->hn];
                            $model->save();
                            $event->patient_flag = 1;
                            $event->save();
                            if (isset($_POST['NursePatient'][$v->hn]) && $_POST['NursePatient'][$v->hn]['disc_type'] != 0) {
                                $model_ptdisc = new WorkloadPtdisc();
                                $model_ptdisc->hn = $v->hn;
                                $model_ptdisc->an = $v->an;
                                $model_ptdisc->title = $v->title;
                                $model_ptdisc->name = $v->name;
                                $model_ptdisc->surname = $v->surname;
                                $model_ptdisc->ward = $ward;
                                $model_ptdisc->movestatus = $_POST['NursePatient'][$v->hn]['disc_type'];
                                if ($model_ptdisc->validate()) {
                                    $model_ptdisc->save();
                                }
                            }
                        }
                    }
                    Yii::$app->getSession()->setFlash('alert', ['body' => 'บันทึกข้อมูลเรียบร้อยแล้ว', 'options' => ['class' => 'alert-success']]);
                    return $this->redirect(['/nurse-event']);
                }
            } else {
                if ($model->validate()) {
                    foreach ($patient as $v) {
                        //                       print_r($_POST['pt_id']);
                        if (isset($_POST['pt_id'][$v->hn])) {
                            //                       print_r($_POST['NursePatient']);
                            $model = new NursePatient();
                            $model->attributes = $_POST['NursePatient'][$v->hn];
                            $model->save();
                            $event->patient_flag = 1;
                            $event->save();
                            if (isset($_POST['NursePatient'][$v->hn]) && $_POST['NursePatient'][$v->hn]['disc_type'] != 0) {
                                $model_ptdisc = new WorkloadPtdisc();
                                $model_ptdisc->hn = $v->hn;
                                $model_ptdisc->an = $v->an;
                                $model_ptdisc->title = $v->title;
                                $model_ptdisc->name = $v->name;
                                $model_ptdisc->surname = $v->surname;
                                $model_ptdisc->ward = $ward;
                                $model_ptdisc->movestatus = $_POST['NursePatient'][$v->hn]['disc_type'];
                                if ($model_ptdisc->validate()) {
                                    $model_ptdisc->save();
                                }
                            }
                        }
                    }
                    Yii::$app->getSession()->setFlash('alert', ['body' => 'บันทึกข้อมูลเรียบร้อยแล้ว', 'options' => ['class' => 'alert-success']]);
                    return $this->redirect(['/nurse-event']);
                }
            }
        } else {
            return $this->render('create', ['model' => $model, 'patient' => $patient, 'prev_data' => $prev_data, 'event' => $event, 'patient_no' => $patient_no, 'check_prev' => $check_prev, 'event_prevp' => $event_prevp, 'event_prevd' => $event_prevd, 'diag' => $diag, 'diag_an' => $diag_an]);
        }
        //        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        //            return $this->redirect(['view', 'id' => $model->pt_ref]);
        //        } else {
        //            return $this->render('create', [
        //                'model' => $model,
        //            ]);
        //        }
    }
    public function actionCreateP3()
    {
        $ward = Yii::$app->session->get('user.ward');
        $prev_data = WorkloadEvent2::find()->where(['ward' => $ward, 'event_date' => date('Y-m-d'), 'event_period' => 2])->all();
        $sql = 'select i.hn,i.an,i.title,i.name,i.surname from ipd_ipd i
where i.ward = ' . $ward . ' and (i.disc="" or i.disc is null or i.disc = "0000-00-00" or i.disc = curdate())
and not exists (select "x" from workload_ptdisc p where p.ward = ' . $ward . ' and i.an = p.an )';
        $patient = IpdIpd::findBySql($sql)->all();
        $model = new WorkloadEvent2();
        if (isset($_POST['WorkloadEvent2'])) {
            if ($model->validate()) {
                foreach ($patient as $v) {
                    $model = new WorkloadEvent2();
                    $model->attributes = $_POST['WorkloadEvent2'][$v->hn];
                    $model->save();
                    if (isset($_POST['WorkloadEvent2'][$v->hn]) && $_POST['WorkloadEvent2'][$v->hn]['disc_type'] != 0) {
                        $model_ptdisc = new WorkloadPtdisc();
                        $model_ptdisc->hn = $v->hn;
                        $model_ptdisc->an = $v->an;
                        $model_ptdisc->title = $v->title;
                        $model_ptdisc->name = $v->name;
                        $model_ptdisc->surname = $v->surname;
                        $model_ptdisc->ward = $ward;
                        $model_ptdisc->movestatus = $_POST['WorkloadEvent2'][$v->hn]['disc_type'];
                        if ($model_ptdisc->validate()) {
                            $model_ptdisc->save();
                        }
                    }
                }
            }
            return $this->redirect(['workload-event2/index']);
        } else {
            return $this->render('create-p3', ['model' => $model, 'patient' => $patient, 'prev_data' => $prev_data]);
        }
    }
 /**
  * Finds the WorkloadPtdisc model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return WorkloadPtdisc the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = WorkloadPtdisc::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }