<?php namespace App\Controllers;

use App\Controllers\BaseController ;
use CodeIgniter\I18n\Time;
use App\Models\BoUserModel ;
use App\Models\PatientModel ;
use App\Models\VisiteModel ;

class Visite extends BaseController
{

	public function new()
	{
		$mVI = new VisiteModel() ;
		$mBU = new BoUserModel() ;
		$mPA = new PatientModel() ;
    $data = [] ;

		$data['mois'] = ["","janvier","fevrier","mars","avril","mai","juin","juillet","aout","septembre","octobre","novembre","decembre"] ;
    $data['jours'] = ["","lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"] ;

		$tmp = explode("-",$this->request->getVar('date')) ;
		$data['date'] = Time::createFromDate($tmp[0],$tmp[1],$tmp[2]) ;
		$data['bu'] = $mBU->find(intval(session('id'))) ;
		$tab_deja = $mVI->where('date',$data['date']->toDateString())->findColumn('id_patient') ;
		if($tab_deja) $mPA->whereNotIn('id',$tab_deja) ;
		$data['patients'] = $mPA->orderBy('nom, prenom')->findAll() ;

		$num_jour = $data['date']->getDayOfWeek() ;
		$data['jour'] = $data['jours'][$num_jour] ;

    echo view('visite/new',$data);

	}

	public function make_not_effectuee()
	{
		$mVI = new VisiteModel() ;
		$mVI->where('id',$this->request->getVar('id'))->set('effectuee',0)->update() ;
	}
	public function make_effectuee()
	{
		$mVI = new VisiteModel() ;
		$mVI->where('id',$this->request->getVar('id'))->set('effectuee',1)->update() ;
	}

	public function trait_new()
	{
		$mVI = new VisiteModel() ;
		$mBU = new BoUserModel() ;
		$mPA = new PatientModel() ;
    $data = [] ;

		$bu = $mBU->find($this->request->getVar('id_bo_user')) ;
		$pa = $mPA->find($this->request->getVar('id_patient')) ;
		$date = $this->request->getVar('date') ;

		$max = $mVI->where('id_bo_user',$bu['id'])->orderBy('ordre DESC')->first() ;
    if($max) $ordre = $max['ordre']+1 ;
		else $ordre = 1 ;
		$vi = [
			'id_bo_user'=>$bu['id'],
			'id_patient'=>$pa['id'],
			'date'=>$date,
			'ordre'=>$ordre
		] ;
		$mVI->insert($vi) ;
	}

}
