<?php namespace App\Controllers;

use App\Controllers\BaseController ;
use App\Models\BoUserModel ;


class BoUser extends BaseController
{
	public function index($orderBy="pseudo",$sens="ASC")
	{
		$mBU = new BoUserModel() ;
    $data = [] ;
		/*
		$session = session() ;
		$data['sens_inverse'] = (($sens=="ASC")?"DESC":"ASC") ;
    if ($this->request->getMethod() == 'post' && $this->request->getVar('action')=="ajouter") {
     $rules = [
       'pseudo' => [
         'rules' => 'required|min_length[3]|max_length[20]|is_unique[bo_user.pseudo]',
         'label' => 'pseudo',
         'errors' => [
           'required' => "Le pseudo est obligatoire...",
           'min_length' => "Le pseudo doit contenir au minimum 3 caractères...",
           'is_unique' => "Ce pseudo existe déja...",
         ]
       ],
       'code' => [
         'rules' => 'required|min_length[3]|max_length[10]|is_unique[bo_user.code]',
         'label' => 'code',
         'errors' => [
           'required' => "Le code est obligatoire...",
           'min_length' => "Le code doit contenir au minimum 3 caractères...",
           'max_length' => "Le code ne doit pas dépasser 10 caractères...",
           'is_unique' => "Ce code est déja pris...",
         ]
       ],
       'temps_deco' => [
         'rules' => 'required|integer',
         'label' => 'temps avant déco',
         'errors' => [
           'required' => 'Veuillez saisir le temps avant déco...',
           'required' => 'Le temps avant déco doit être un nombre entier...',
         ]
       ]
     ];

      if(!$this->validate($rules)) $data['valid_add'] = $this->validator ;
			else{
				$newData = [
					'pseudo' => $this->request->getVar('pseudo'),
					'code' => $this->request->getVar('code'),
					'temps_deco' => $this->request->getVar('temps_deco'),
					'admin' => (($this->request->getVar('admin'))?1:0),
					'admin_produit' => (($this->request->getVar('admin_produit'))?1:0),
					] ;
				$model->save($newData) ;
				$data['lastQuery'][] = $model->getLastQuery() ;
				$session->setFlashData('success','Insertion réussie') ;
			}
    }
		else if ($this->request->getMethod() == 'post' && $this->request->getVar('action')=="dialog_modifier_liste") {
      $data['champ'] = $this->request->getVar('champ') ;
      $data['liste'] = $this->request->getVar('liste') ;
			return view('admin/bibli/dialog_modifier_liste',$data) ;
		}
		else if ($this->request->getMethod() == 'post' && $this->request->getVar('action')=="modifier_liste") {

     $tab_id = explode(",",$this->request->getVar('liste'))  ;
		 $champ = $this->request->getVar('champ') ;
		 $val = $this->request->getVar('val') ;
     foreach($tab_id as $idtmp){
       $model->set($champ,$val) ;
			 $model->where('id',$idtmp) ;
			 $model->update();
			 $data['lastQuery'][] = $model->getLastQuery() ;
		 }
		 $session->setFlashData('success','Mise à jour de la colonne '.$champ.' effectuée, '.count($tab_id).' lignes affectées.') ;
     // $model->where("id IN (".$this->request->getVar('liste').") ");
		 // $donnees = [ $champ => $val ];
     // $model->update($donnees);

			// $data[''] ;
			// echo view('admin/bo_user/get_val_modifier_liste',$data) ;
			// exit() ;
		}
    else if ($this->request->getMethod() == 'post' && $this->request->getVar('action')=="modifier") {
      $rules = [
        'pseudo' => [
          'rules' => 'required|min_length[3]|max_length[20]|is_unique[bo_user.pseudo,id,{id}]',
          'label' => 'pseudo',
          'errors' => [
            'required' => "Le pseudo est obligatoire...",
            'min_length' => "Le pseudo doit contenir au minimum 3 caractères...",
            'max_length' => "Le pseudo ne doit pas dépasser 20 caractères...",
            'is_unique' => "Ce pseudo existe déja...",
          ]
        ],
        'code' => [
          'rules' => 'required|min_length[3]|max_length[10]|is_unique[bo_user.code,id,{id}]',
          'label' => 'code',
          'errors' => [
            'required' => "Le code est obligatoire...",
            'min_length' => "Le code doit contenir au minimum 3 caractères...",
            'max_length' => "Le code ne doit pas dépasser 10 caractères...",
            'is_unique' => "Ce code est déja pris...",
          ]
        ],
        'temps_deco' => [
          'rules' => 'required|integer',
          'label' => 'temps avant déco',
          'errors' => [
            'required' => 'Veuillez saisir le temps avant déco...',
            'required' => 'Le temps avant déco doit être un nombre entier...',
          ]
        ]
      ];

      if(!$this->validate($rules)){
        $data['valid_modif'] = $this->validator ;
        $data['id_valid_modif'] = $this->request->getVar('id') ;
      }
			else{
				$newData = [
					'id' => $this->request->getVar('id'),
					'pseudo' => $this->request->getVar('pseudo'),
					'code' => $this->request->getVar('code'),
					'temps_deco' => $this->request->getVar('temps_deco'),
					'admin' => (($this->request->getVar('admin'))?1:0),
					'admin_produit' => (($this->request->getVar('admin_produit'))?1:0),
					] ;
				$model->save($newData) ;
				$data['lastQuery'][] = $model->getLastQuery() ;
				$session = session() ;
				$session->setFlashData('success','Modification réussie') ;
			}
    }
    else if ($this->request->getMethod() == 'post' && $this->request->getVar('action')=="supprimer") {
      $model->delete($this->request->getVar('id')) ;
			$data['lastQuery'][] = $model->getLastQuery() ;
    }
    else if ($this->request->getMethod() == 'post' && $this->request->getVar('action')=="recherche") {
      if($this->request->getVar('rech_id')) $model->where('id',$this->request->getVar('rech_id')) ;
      if($this->request->getVar('rech_pseudo')) $model->like('pseudo',$this->request->getVar('rech_pseudo')) ;
      if($this->request->getVar('rech_code')) $model->like('code',$this->request->getVar('rech_code')) ;
      if($this->request->getVar('rech_temps_deco')) $model->like('temps_deco',$this->request->getVar('rech_temps_deco')) ;
      if($this->request->getVar('rech_admin')) $model->where('admin',(($this->request->getVar('rech_admin')=="oui")?1:0)) ;
      if($this->request->getVar('rech_admin_produit')) $model->where('admin_produit',(($this->request->getVar('rech_admin_produit')=="oui")?1:0)) ;
    }

		*/
    $mBU->orderBy($orderBy,$sens) ;
    $data['tab_bo_user'] = $mBU->findAll() ;
		// $data['lastQuery'][] = $mBU->getLastQuery() ;

		// RECUPERATION DU CONTENU DU MENU
    // $menuHeader = new BoMenuModel() ;
	  // $data['tab_menu_header'] = $menuHeader->getMenuHeader() ;
    $data['footer_js'] = "bo_user" ;
    echo view('header',$data);
		echo view('bo_user/index',$data);
		echo view('footer',$data);

	}

  public function trait_form()
  {
		$mBU = new BoUserModel() ;
		if(intval($this->request->getVar('id'))>0){
			$bu = [
				'id'=>$this->request->getVar('id'),
				'nom'=>$this->request->getVar('nom'),
				'prenom'=>$this->request->getVar('prenom'),
				'adresse'=>$this->request->getVar('adresse'),
				'complement'=>$this->request->getVar('complement'),
				'cp'=>$this->request->getVar('cp'),
				'id_ville'=>$this->request->getVar('id_ville'),
				'pseudo'=>$this->request->getVar('pseudo'),
				'email'=>$this->request->getVar('email'),
				'tel'=>$this->request->getVar('tel'),
				'mdp'=>$this->request->getVar('mdp'),
				'couleur'=>$this->request->getVar('couleur'),
				'admin'=>$this->request->getVar('admin')
				] ;
			$mBU->save($bu) ;
			echo $bu['id'] ;
		}
		else{
			$bu = [
				'nom'=>$this->request->getVar('nom'),
				'prenom'=>$this->request->getVar('prenom'),
				'adresse'=>$this->request->getVar('adresse'),
				'complement'=>$this->request->getVar('complement'),
				'cp'=>$this->request->getVar('cp'),
				'id_ville'=>$this->request->getVar('id_ville'),
				'pseudo'=>$this->request->getVar('pseudo'),
				'email'=>$this->request->getVar('email'),
				'tel'=>$this->request->getVar('tel'),
				'mdp'=>$this->request->getVar('mdp'),
				'couleur'=>$this->request->getVar('couleur'),
				'admin'=>$this->request->getVar('admin')
				] ;
			$mBU->insert($bu) ;
			echo $mBU->getInsertID() ;
		}

  }

	public function form()
	{
		helper(['form']) ;
		$mBU = new BoUserModel() ;
		$data = [] ;
		$data['bo_user'] = $mBU->find(intval($this->request->getVar('id'))) ;
		if(!$data['bo_user']){
			$data['bo_user'] = ['id'=>0,'nom'=>'','prenom'=>'','adresse'=>'','complement'=>'','cp'=>'','id_ville'=>0,'pseudo'=>'','email'=>'','mdp'=>''] ;
		}
		echo view('bo_user/form',$data) ;
	}

	public function liste()
	{
		$mBU = new BoUserModel() ;
		$data = [] ;
		$data['bo_users'] = $mBU->orderBy('pseudo')->findAll() ;
		echo view('bo_user/liste',$data);
	}

  public function droits(){
    $data = [] ;
		helper(['form']) ;

		// RECUPERATION DU CONTENU DU MENU
		$menuHeader = new BoMenuModel() ;
		$data['tab_menu_header'] = $menuHeader->getMenuHeader() ;

		// RECUPERATION DE LA LISTE DES USER
		$model = new BoUserModel() ;
		$data['tab_bo_user'] = $model->getUserAndMenu() ;

		echo view('admin/templates/header',$data);
		echo view('admin/bo_user/tableau_droits',$data) ;
		echo view('admin/templates/footer',$data);

	}

	public function check_droit(){
		$id_user = $this->request->getVar('id_user') ;
		$id_menu = $this->request->getVar('id_menu') ;
		$droit = $this->request->getVar('droit') ;

		$db      = \Config\Database::connect() ;
		$builder = $db->table('bo_l_menu_user') ;
		$where = [
			'id_user'=>$id_user,
			'id_menu'=>$id_menu
		];
    $builder->delete($where) ;
		if($droit>0) $builder->insert($where) ;
	}

	public function ident(){
		$data = [] ;
    helper(['form']) ;

		if ($this->request->getMethod() == 'post') {
      // les rules de validation
			$rules = [
        'email' => [
          'rules' => 'required|valid_email|validateEmail[email]',
          'label' => 'Adresse email',
          'errors' => [
            'required' => "Merci de saisir votre adresse email...",
            'valid_email' => "Adressse email non valide...",
            'validateEmail' => "Adressse email inconnue..."
          ]
        ],
        'mdp' => [
          'rules' => 'required|validateMdp[mdp]',
          'label' => 'Mot de passe',
          'errors' => [
            'required' => "Merci de saisir votre mot de passe...",
            'validateMdp' => "Mot de passe incorrect..."
          ]
        ]
      ];

			if(!$this->validate($rules)){
			  $data['validation'] = $this->validator ;
			}
			else{
				$mBU = new BoUserModel() ;
				$user = $mBU->where('email', $this->request->getVar('email'))->first() ;
				$this->setBoUserSession($user) ;
				$mBU->where('id',$user['id'])->set('last_co',date('Y-m-d H:i:s'))->update() ;
				//$session->setFlashData('success','Enregistrement réussi') ;
				return redirect()->to(base_url().'/agenda');
			}
    }
		
		echo view('header',$data);
		echo view('bo_user/ident',$data) ;
		echo view('footer',$data);
	}

	private function setBoUserSession($user){
		$user['isLoggedIn'] = true ;
    session()->set($user) ;
		return true ;
	}

	public function logout(){
		session()->destroy();
		return redirect()->to('ident') ;
	}

	public function profile($id=0){
    $data = [] ;

		$model = new BoUserModel() ;
		$data['bo_user'] = $model->where('id',$id)->findAll() ;

		echo view('admin/templates/header',$data);
		echo view('admin/bo_user/profile',$data) ;
		echo view('admin/templates/footer',$data);
	}

	//--------------------------------------------------------------------

}
