<?php

namespace app\controllers;

use Yii;
use app\models\Voucherref;
use app\models\Reimbursementmaster;
use app\models\ReimbursementmasterSearch;
use app\base\Converter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\filters\AccessControl;
use app\models\Visitschedule;
use app\models\VVisitstatus;
use app\models\Attandance;

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

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

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

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

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

      // $model = Visitschedule::find()->where(["participant_i" => "DH10344"])->andWhere('act_window_end >= `visit_date`')->andWhere(["IS NOT", "visit_date",Null])->andWhere('visit_date >= `act_window_start`')->andWhere(['OR', ["=", "visit_code", -3],["=", "visit_code", -4]])->orderBy(['visit_date' => SORT_DESC])->one();	
		         
        if ($model->load(Yii::$app->request->post())) {
            $VModel = Voucherref::generateVoucherno($model->reimburse_master_survey, $model->reimburse_master_part_id, Voucherref::REIMBURSEMENT);
            // if(!$VModel->save())
           //      print_r($VModel->errors);
           //      print_r($VModel->attributes);		  
		 
          //  $model->reimburse_master_visitcode = "1";
		    $model->reimburse_master_visitcode = $model->reimburse_master_visitcode;
            $model->reimburse_master_q1 = 1;
			
			if ($model->reimburse_master_visitcode == -3 || $model->reimburse_master_visitcode == -4) {
             $model->reimburse_master_q2 = 450;
			}
			else
			{
			 $model->reimburse_master_q2 = 250;
			}	
			
            $model->reimburse_master_q4 = $VModel->vchr_ref_loc."-".$VModel->vchr_ref_type."-".$VModel->vchr_ref_code;
            // print_r($model->attributes);
            // exit;
        }
        if (Yii::$app->request->isPost && $model->save()) {
            $VModel->save();
            return $this->redirect(['view', 'id' => $model->reimburse_master_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Reimbursementmaster 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->reimburse_master_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Reimbursementmaster 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();

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

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

    public function actionAjax()
    {
        $today = strtotime(date("Y/m/d"));
        $request = Yii::$app->request;
        $view = true;
        if ($request->isGet) {
            $id = $request->get('id');			
        }
        if ($request->isPost) {
            $view = false;
            $id = $request->post('id');		
        }

       // $model = VVisitstatus::find()->where(["participant_id" => $id]);
	  
	   $today = strtotime(date("Y/m/d"));		
        $model = Attandance::find()->where(["participant_id" => $id])->andWhere(["<=", "visit", 1])->andWhere(["record_date" => $today])->orderBy(['record_date' => SORT_DESC])->one();
		
		if ($model !== null) 	
         $visit= $model->visit;		 
		else
		  $visit= "";
		
		$model = VVisitstatus::find()->where(["participant_id" => $id,'visit' => $visit]);
        if($model !== null) {
            $dataProvider8 = new ActiveDataProvider(['query' => $model, 'pagination' => ['pagesize' => 10]]);
            if(Yii::$app->request->isAjax) {
                if($view)
                    return $this->renderPartial('status', ['dataProvider' => $dataProvider8]);
                else {
                    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                    $model = $model->one();
                    if(isset($model->linkage))
                        return $model->getStatus($model->participant_id,$model->visit,$model->linkage->hiv_linkage_q5, true);
                    else
                        return 0;
                }
            } else
                return $this->render('status', ['dataProvider' => $dataProvider8]);
        }
    }

    public function actionPdf($id)
    {
        $model = $this->findModel($id);
        $pmodel = ["pid" => $model->reimburse_master_part_id, "vno" => $model->reimburse_master_q4, "vdt" => $model->reimburse_master_q3, "amt" => $model->reimburse_master_q2, "summary" => "Reimbursement"];
        return $content = $this->renderPartial('/layouts/print', ['model' => $pmodel]);

        $pdf = Yii::$app->pdf; // or new Pdf();
        $mpdf = $pdf->api; // fetches mpdf api
        // $mpdf->SetHeader('Kartik Header'); // call methods or set any properties
        $mpdf->WriteHtml($content); // call mpdf write html
        // echo $mpdf->Output('filename.pdf', 'F'); // call the mpdf api output as needed
        // return $pdf->render(); 

        // $pdf = new Pdf([
        //     'mode' => Pdf::MODE_CORE,
        //     'format' => Pdf::FORMAT_A4,
        //     'orientation' => Pdf::ORIENT_PORTRAIT,
        //     'destination' => Pdf::DEST_BROWSER,
        //     'content' => $content,
        //     'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
        //     'cssInline' => '.kv-heading-1{font-size:18px}',
        //     'options' => ['title' => 'Krajee Report Title'],
        //     'methods' => [
        //         'SetHeader'=>['Krajee Report Header'],
        //         'SetFooter'=>['{PAGENO}'],
        //     ]
        // ]);
        
        // return the pdf output as per the destination setting
        echo $mpdf->Output('filename.pdf', 'I'); // call the mpdf api output as needed
    }
	
	public function actionVisit()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('pid');
        if ($request->isPost)
            $id = $request->post('pid');
		$today = strtotime(date("Y/m/d"));
		
        $model = Attandance::find()->where(["participant_id" => $id])->andWhere(["<=", "visit", 1])->andWhere(["record_date" => $today])->orderBy(['record_date' => SORT_DESC])->one();
		if ($model !== null) {	
         return $model;
		} 
    }
	
	public function actionVisitsch()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('pid');
        if ($request->isPost)
            $id = $request->post('pid');
		$today = strtotime(date("Y/m/d"));		
							
		$VStable = Visitschedule::tableName();
		
		$modelattn = Attandance::find()->where(["participant_id" => $id])->andWhere(["<=", "visit", 1])->andWhere(["record_date" => $today])->orderBy(['record_date' => SORT_DESC])->one();
		
		if ($modelattn !== null) 	
         $visit= $modelattn->visit;		 
		else
		  $visit= "";
	  
		
		$model = Visitschedule::find()->where(["participant_id" => $id])->andWhere(["visit_code" => $visit])->andWhere('act_window_end >= `visit_date`')->andWhere(["IS NOT", "visit_date",Null])->andWhere('visit_date >= `act_window_start`')->andWhere(['OR', ["=", "visit_code", -3],["=", "visit_code", -4]])->orderBy(['visit_date' => SORT_DESC])->one();
								
        						 
		 if ($model !== null) {	
          return '1';
		 }
		 else {
		 return '0'; 
		} 		 
					
		
    }

}
