<?php namespace App\Controllers;

use App\Controllers\BaseController ;
use App\Models\VilleModel ;


class Ville extends BaseController
{

	public function index()
	{
		$mVI = new VilleModel() ;
    $data = [] ;

    // $data['patients'] = $mAC->orderBy('libel')->findAll() ;

    $data['footer_js'] = "ville" ;
    echo view('header',$data);
		echo view('ville/index',$data);
		echo view('footer',$data);

	}

	public function liste()
	{
		$mVI = new VilleModel() ;
		$data = [] ;
		$data['villes'] = $mVI->orderBy('cp, libel')->findAll() ;
		echo view('ville/liste',$data);
	}

	public function form()
	{
		helper(['form']) ;
		$mVI = new VilleModel() ;
		$data = [] ;
		$data['ville'] = $mVI->find(intval($this->request->getVar('id'))) ;
		if(!$data['ville']){
			$data['ville'] = ['id'=>0,'cp'=>'','libel'=>''] ;
		}
		echo view('ville/form',$data) ;
	}

	public function trait_form()
  {
		$mVI = new VilleModel() ;
		if(intval($this->request->getVar('id'))>0){
			$ac = [
				'id'=>$this->request->getVar('id'),
				'cp'=>$this->request->getVar('cp'),
				'libel'=>$this->request->getVar('libel')
				] ;
			$mVI->save($ac) ;
			echo $ac['id'] ;
		}
		else{
			$ac = [
				'cp'=>$this->request->getVar('cp'),
				'libel'=>$this->request->getVar('libel')
				] ;
			$mVI->insert($ac) ;
			echo $mVI->getInsertID() ;
		}

  }

	public function supprime()
	{
		$mV = new VilleModel() ;
		$mV->where('id',$this->request->getVar('id'))->delete() ;
	}

	public function form_inc_new()
	{

		$mVI = new VilleModel() ;
		$vi = ["libel"=>$this->request->getVar('new_ville'),"cp"=>$this->request->getVar('cp')] ;
		$mVI->insert($vi) ;

	}

	public function form_inc_liste()
	{
		$mVI = new VilleModel() ;
		$data = [] ;
		$data['ville'] = $mVI->find(intval($this->request->getVar('id_ville'))) ;
		if(null!==$this->request->getVar('cp')){
			$data['cp'] = $this->request->getVar('cp') ;
			$data['villes'] = $mVI->where('cp',$data['cp'])->orderBy('libel')->findAll() ;
		}
		else{
			$data['cp'] = "" ;
			$data['villes'] = [] ;
		}
		echo view('ville/form_inc_liste',$data);
	}

}
