<?php

defined('BASEPATH') OR exit('No direct script access allowed');



class Lgedit extends CI_Controller {



	/**

	 * Index Page for this controller.

	 *

	 * Maps to the following URL

	 * 		http://example.com/index.php/welcome

	 *	- or -

	 * 		http://example.com/index.php/welcome/index

	 *	- or -

	 * Since this controller is set as the default controller in

	 * config/routes.php, it's displayed at http://example.com/

	 *

	 * So any other public methods not prefixed with an underscore will

	 * map to /index.php/welcome/<method_name>

	 * @see http://codeigniter.com/user_guide/general/urls.html

	 */

	function __construct(){

		parent::__construct();

		$this->load->config('lgedit');

		$this->load->helper('lgedit');

		$this->load->library('lg');

		$this->load->library('Pdf');

		$this->load->helper('lgpdf');
		
      	$this->load->library('user_agent');
		$this->load->helper('url');
		//$this->getLocationInfoByIp();

		//$this->check_db();

	}

//Récuperer le nom du pays de l'utilisateur
    function getLocationInfoByIp(){
        $client  = @$_SERVER['HTTP_CLIENT_IP'];
        $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
        $remote  = @$_SERVER['REMOTE_ADDR'];
        $result  = array('country'=>'', 'city'=>'');
        $data = array();
        if(filter_var($client, FILTER_VALIDATE_IP)){
            $ip = $client;
        }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
            $ip = $forward;
        }else{
            $ip = $remote;
        }
        $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
        if($ip_data && $ip_data->geoplugin_countryName != null){
            /*if ($this->agent->is_browser()) {
                $agent = $this->agent->browser() . ' ' . $this->agent->version();
            } elseif ($this->agent->is_robot()) {
                $agent = $this->agent->robot();
            } elseif ($this->agent->is_mobile()) {
                $agent = $this->agent->mobile();
            } else {
                $agent = 'Unknown';
            }*/
            $data = array(
                'url_page' => current_url(),
                'ip_adresse' => $ip_data->geoplugin_request,
                'date_visite' => date('Y-m-d h:m:s'),
                'pays' => $ip_data->geoplugin_countryName,
                'ville' => $ip_data->geoplugin_city,
                'region' => $ip_data->geoplugin_regionName,
                'plateform' => $this->agent->platform()

            );
        }
        $this->db->insert('visite',$data);
    }

	public function index(){

		echo "11";

	}

    public function add_pvv_user($group)
    {
        $tables = $this->config->item('tables', 'ion_auth');
        $identity_column = 'username';
        $this->data['identity_column'] = $identity_column;
       // $this->data[''] = $id_organisation;

        //if ($this->form_validation->run() == true) {
        $email = strtolower($this->input->post('email'));
        $groups = array($group);
        $identity = $this->input->post('username');
        $password = $this->input->post('password');

        $additional_data = array(
                           'first_name' => $this->input->post('nom'),
							'last_name' => $this->input->post('prenom'),
							'birthdate' => $this->input->post('birthdate'),
							'birthplace' => $this->input->post('birthplace'),
							'sexe' => $this->input->post('sexe'),
							'etatcivil' => $this->input->post('etatcivil'),
							'cnib' => $this->input->post('cnib'),
							'debut_traitement' => $this->input->post('debut_traitement'),
							'nouveau_cas' => $this->input->post('nouveau_cas'),
							'date_depistage' => $this->input->post('date_depistage'),
							'adr_rue' => $this->input->post('adr_rue'),
							'adr_nom' => $this->input->post('adr_nom'),
							'adresse' => $this->input->post('adresse'),
							'phone' => $this->input->post('telephone'),
							'email' => $this->input->post('email'),
							'province' => $this->input->post('province'),
							'ville' => $this->input->post('ville'),
							'zonesante' => $this->input->post('zonesante'),
							'educateur' => $this->input->post('educateur'),
							'username' => $this->input->post('username'),
							'password' => $this->input->post('password'),
							'password_confirm' => $this->input->post('password_confirm')
        );
        //}

        $saved_id = $this->ion_auth->register($identity, $password, $email, $additional_data, $groups);
        if ($saved_id) {
         die('ok');
        	//$last_user_id = get_max_user_id();
        	$additional_data['user_id'] = $saved_id;
        	$additional_data['code'] = $this->generate_cs();
        	$this->lg->save_users_meta($additional_data);
        	var_dump($additional_data); exit;
            // check to see if we are creating the user
            $this->emailNotification($identity, $email, $password);
            // redirect them back to the admin page
            $this->session->set_flashdata('message', $this->ion_auth->messages());
            return 1;
            //redirect("auth", 'refresh');
        }else{
        	//echo 'NON';
        	return "false";
        }/**/
        
    }


	private function generate_cs(){
		$c1="CDVS";
		$c2=rand(1,99999);
		$c2=str_pad($c2, 5, '0', STR_PAD_LEFT);
		$c3=range('a','z');
		shuffle($c3);
		$c3=strtoupper($c3[0]);
		$c = $c1.$c2.$c3;
		return $c;
	}

	public function add($t){

		$tables = $this->config->item('lgedit_tables');

		if(!isset($tables[$t])) die("table doesnt exists");

		$table = $tables[$t];

		$datas=$this->input->post();

		if( isset($datas['username']) && ($datas['username']=='') && ($t=='medecin')){
			$CI =& get_instance();
			$c1="";
			$c2=substr(strtolower($datas['nom']), 0, 1);
			$c3=strtolower($datas['prenom']);
			$c = $c1.$c2.$c3;
			$datas['username']=$c;
		}
		
		 if ($t == 'pvv'){
		     
		        $pvvExist = $this->lg->get_data('pvv',array(
                                    		            'nom' => $_POST['adr_rue'], 
                                        		        'prenom' => $_POST['prenom'], 
                                        		        'birthdate' => $_POST['birthdate'], 
                                        		        'sexe' => $_POST['sexe'], 
                                        		        'etatcivil' => $_POST['etatcivil'], 
                                        		        'cnib' => $_POST['cnib']
                                    		        ),true);
		        //var_dump($pvvExist); echo 'rrrr'; exit;
		        if($pvvExist){ 'Ce pvv existe d&eacute;j&agrave;'; return; }
                    $adresse = $_POST['adr_rue'].' '.$_POST['adr_nom'];
                    $_POST['adresse'] = $adresse;
                    $datas['adresse'] = $_POST['adresse'];
                    //var_dump($_POST['adresse']); die($t);
                }

		if($t=='resultat_examens'){
			//if(!is_numeric($param1) && !is_numeric($value1))
			//	redirect($_SERVER['HTTP_REFERER']);
			//$pvvid = $this->input->post('pvv');
			//$pvv = $this->lg->get_data('pvv',array('id' => $pvvid),true);
			$newdatas['pvv'] = $datas['pvv']; //$pvv['code'];
			$newdatas['medecin'] = $datas['medecin']; //$pvv['code'];
			$newdatas['consultation'] = $datas['consultation'];
			$newdatas['laborantin']=$this->session->userdata('user_id');
			$newdatas['examen']= $datas['examen'];
			$newdatas['prescription']= $datas['prescription'];
			unset($datas['pvv']);
			unset($datas['medecin']);
			unset($datas['consultation']);
			unset($datas['examen']);
			unset($datas['prescription']);
			$newdatas['resultats'] = json_encode($datas);
			$datas = $newdatas;
		}


		if(isset($datas['api'])){

			$datas['id'] = '';

			$datas['etat'] = 'En attente'; 

			if(isset($datas['api_pharmacie'])){

				if(isset($datas['api_medicament'])){
					$ordonnance = $this->lg->get_data('ordonnances',array('id' => $datas['ordonnance']),true);
					$ordonnance['etat'] = 'tobereceived';
					$ordonnance['delivered'] = date('Y-m-d');
				}else{
					$ordonnance = $this->lg->get_data('ordonnances',array('pvv' => $datas['pvv'], 'etat' => 'En attente', 'delivered' => ''),true);
					$ordonnance['etat'] = 'En attente';
				}

				if($ordonnance){
					if(!isset($datas['api_medicament'])){
						$ordonnance['prepose_pharmacie'] = $datas['prepose_pharmacie'];//$this->session->userdata('user_id');
						$ordonnance['etat'] = 'En attente';
					}

					$prdts = is_array($ordonnance["produits"]) ? $ordonnance["produits"]: json_decode($ordonnance["produits"]) ;

					$i=0;
					foreach ($prdts as $prdt) {
						foreach ($prdt as $key => $value) {

							$ordonnance["produits_".$key][$i] = $value;//."_".

						}
						$i++;
					}

					unset($ordonnance["produits"]);


					$datas = $ordonnance;

					$datas['api'] = true;

					$datas['api_pharmacie'] = true;

					if(!isset($datas['api_medicament'])){
						unset($ordonnance["produits"]);
						$ordonnanceToReturn = $ordonnance;
					}

				}else{

					echo json_encode(array('success'=>false, 'message'=>'Aucune ordonnance ne correspond aux criteres'));
					return;
				}
//var_dump($datas); exit;
				//var_dump($ordonnance["produits"]); exit;

			}

			if(isset($datas['api_laborantin'])){
				$prescription = $this->lg->get_data('ordonnances',array('pvv' => $datas['pvv']),true);
				$prescription['laborantin'] = $this->session->userdata('user_id');
				$datas = $prescription;
			}


			/*if(isset($datas['api_medicament'])){
				$id = $datas['id'];
				$return = $this->lg->set_data($t,$id,$datas,false);
				echo json_encode(array(
										'success'=>true,
										'result'=>'DONE!'
									)
								); 
				return;
			}*/

		}

		

//var_dump($datas); exit;

		//var_dump($ordonnance); //exit;

		//echo '<br><br>';

		$res = array();



		foreach($table['fields'] as $k => $f){ //echo ' * '; var_dump($k); echo ' * ';

			if($f['type'] == "date"){

				$v = $datas[$k];

				$v = strtotime($v);

				$v = date('Y-m-d',$v);

				$res[$k]=$v;

			}else if($f['type'] == "list"){ //echo $k;

				$keys = array_keys($f['values']);

				$rr = array();

				$c = count($datas[$k.'_'.$keys[0]]);
//echo $c." -";
				for($i=0;$i<$c;$i++){

					$r=array();

					//var_dump($keys); echo ' -- ';

					foreach($keys as $key){ //echo ' |- '; echo $k.'_'.$key; 

						$r[$key]=$datas[$k.'_'.$key][$i];

					}

					$rr[]=$r;

				}		

				$v = $rr;//json_encode($rr);

				$res[$k]=$v;

			}else{

				$v = isset($datas[$k]) ? $datas[$k] : '';

				if(is_array($v)){

					$v = $v;//json_encode($v);

				}

				$res[$k]=$v;

			}

		}

		// Add customized data to be saved
		if($t=='commandes' && !isset($datas['deliver'])){

			$res['acheteur']=$this->lg->get_current_user_or_company_id();

		}
		if(isset($datas['api'])){

			$res['api'] = 'true';

		}

		if(isset($datas['api_pharmacie'])){

			$res['api_pharmacie'] = 'true';

		}

		if($t=='prescription_examens'){
			//if(!is_numeric($param1) && !is_numeric($value1))
			//	redirect($_SERVER['HTTP_REFERER']);
			//$pvvid = $this->input->post('pvv');
			//$pvv = $this->lg->get_data('pvv',array('id' => $pvvid),true);
			//$datas['pvv'] = $pvv['id'];
			$res['medecin'] = $this->session->userdata('user_id');
		}

		/*	
			var_dump($datas); 
			echo "<br>--------------------------------------------------------<br>";
			var_dump($res); exit;

		foreach($datas as $k => &$v){

			if(is_array($v)){

				$v = json_encode($v);

			}

			if($table['fields'][$k]['type'] == "date"){

				$v = strtotime($v);

				$v = date('Y-m-d',$v);

			}	

		}

		*/

		$id = $table['id'];

		$id = isset($res[$id]) ? $res[$id] : false;

		if(isset($table['hooks']) && is_array($table['hooks'])){

			if(isset($table['hooks']['before_add'])){

				$res=call_user_func($table['hooks']['before_add'],$res);

				//print_r($res);

			}

		}

		//echo $t.' ----- ';

		//var_dump($res); exit;

		//echo ' <br><br> ';

		if($t=='consultation' && isset($_GET['consultid']) && isset($_GET['pvv'])) { 
			if(is_numeric($_GET['consultid']) && is_numeric($_GET['pvv'])):
				$idconsultation = $_GET['consultid'];
				$pvv = $_GET['pvv'];
				$res1=$this->lg->get_data('consultation',array('id' => $idconsultation),true);
				$res1['user'] = $res1['agent'];
				$res1['etat'] = 'done';
				$this->lg->set_data('consultation',$idconsultation,$res1,false);
				redirect('/backend/consultations/');
			endif;
			die('Invalid data entered.');
		}//else{ echo 'yes';

		if($t=='ordonnances' && empty($res['id'])) { //echo 'yes';

			$res1=$this->lg->get_data('consultation',array('id' => $res['consultation']),true);

			$res1['user'] = $res1['agent'];

			//$res1['etat'] = 'done';

			//$this->lg->set_data('consultation',$res['consultation'],$res1,false);
            
            $res['etat'] = 'En attente';

			$res['initiated'] = date('Y-m-d');

			$res['closed'] = date('Y-m-d', strtotime('+1 month'));

			$res['num_renewed'] = 0;

		}//else{ echo 'yes';

		// Vérifier si les constantes existent pour cette consultation
		if($t=='constante'){
			$constante=$this->lg->get_data('constante',array('consultation' => $res['consultation']),true);
			if(!empty($constante)) {
				echo 'Les constantes ont d&eacute;j&agrave; &eacute;t&eacute; prises.';
				exit;
			}
		}

		if($t=='blog_categories'){
			$search = array('é','à','è','ê','î','û',' ');
			$replace = array('e','a','e','e','i','u','-');
			$res['slug'] = str_replace($search, $replace, strtolower($res['nom']));
		}

		if( ($t=='blog_posts')&&(!isset($res['id'])) ){
    		// Sauver l'image d'un article du blog
    		$res['image'] = $this->do_upload();
		}
//var_dump($res['article']); exit;
		// Faire la nouvelle insertion
	   if ($t == 'pvv') {
        	//		$t = 'users';
        	//die($t);
            $adresse = $this->input->post('adr_rue') . ' ' . $this->input->post('adr_nom');
            $_POST['adresse'] = $adresse;
            $res['adresse'] = $_POST['adresse'];
             try {
                //var_dump($data);die();
               // $this->db->insert($t, $data);
                //$return = $this->db->insert_id();
        		//die($t);
                $return = $this->add_pvv_user(12);
                //1;
            } catch (Exception $e) {
                return $e;
            }
        }else{
			$return = $this->lg->set_data($t,$id,$res,false);
        }

		//$arrayOfUsersToCreate = array('pvv','medecin','educateur','zonesante','partenaire','societe_pharma');
		//if($t=='pvv'){
			$datas['entity_id'] = $return;
		//}
		
		/*$arrayOfUsersToCreate = array('pvv','medecin','educateur','infirmier');
		if(in_array($t, $arrayOfUsersToCreate)){
			$login_register = $this->set_pvv_login($t,$datas);
			$return = ($login_register)? '1. '.$return.'<br>2. Utilisateur configuré!':$return;			
		}*/

		//}	

//exit;

		//var_dump($res); exit;

		if(isset($datas['deliver'])){

			//echo $res['id'].' ---';

			redirect('/backend/commandes/deliver/'.$res['id']);

			$this->lg->get_current_user_or_company_id();

			//$res['api'] = 'true';

		}


		//if($t=='constante'){
		//	redirect('/backend/profile_pvv/'.$res['pvv'].'/consultation');
		//}
		//var_dump($res); exit;
       
		if(isset($datas['api_medicament'])){
			header('Content-type: application/json');
			echo json_encode(array(
										'success'=>true,
										'result'=>'DONE!'
									)
								); 
			return;
		}

		if(isset($datas['api'])  && !isset($datas['api_pharmacie'])){

			header('Content-type: application/json');
			if(is_int($return)){
				echo json_encode(array(
										'success'=>true,
										'result'=>'DONE!'
									)
								); 
			}else{
				echo json_encode(array(
										'success'=>false,
										'error'=>'FAILED!'
									)
								); 
			}
			return;
		}

		if(isset($datas['api'])  && isset($datas['api_pharmacie'])){

			if(isset($ordonnanceToReturn)){
				echo json_encode($ordonnanceToReturn);
			}else{
				echo null;
			}
			return;
		}

		else{

			echo (is_integer($return)) ? 'Enregistrement réussi!':'Echec de l\'enregistrement';
			return;

		}


	}


    public function do_upload() { 

        $config['upload_path']          = './images/blog/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 3000;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;
		$this->load->library('upload', $config);
        if ( ! $this->upload->do_upload('image')) { 
            $error = array('error' => $this->upload->display_errors()); 
			echo $error["error"];
			return;
            //$this->load->view('upload_form', $error); 
        }	
        else { 
            $data = array('upload_data' => $this->upload->data()); 
            return 'https://www.landela.org/'.$config['upload_path'].$data["upload_data"]["file_name"];
            /* $data ::
            array(1) {
			  ["upload_data"]=>
			  array(14) {
			    ["file_name"]=>
			    string(40) "3c4ef53d-6e2e-4e93-8f21-ea1c71cca32e.jpg"
			    ["file_type"]=>
			    string(10) "image/jpeg"
			    ["file_path"]=>
			    string(59) "F:/WEBLAB/EasyPHP-Devserver-16.1/eds-www/landela/resources/"
			    ["full_path"]=>
			    string(99) "F:/WEBLAB/EasyPHP-Devserver-16.1/eds-www/landela/resources/3c4ef53d-6e2e-4e93-8f21-ea1c71cca32e.jpg"
			    ["raw_name"]=>
			    string(36) "3c4ef53d-6e2e-4e93-8f21-ea1c71cca32e"
			    ["orig_name"]=>
			    string(40) "3c4ef53d-6e2e-4e93-8f21-ea1c71cca32e.jpg"
			    ["client_name"]=>
			    string(40) "3c4ef53d-6e2e-4e93-8f21-ea1c71cca32e.jpg"
			    ["file_ext"]=>
			    string(4) ".jpg"
			    ["file_size"]=>
			    float(33.87)
			    ["is_image"]=>
			    bool(true)
			    ["image_width"]=>
			    int(800)
			    ["image_height"]=>
			    int(532)
			    ["image_type"]=>
			    string(4) "jpeg"
			    ["image_size_str"]=>
			    string(24) "width="800" height="532""
			  }
			}*/
            //$this->load->view('upload_success', $data); 
        } 

    } 


	private function set_pvv_login($t, $pvv_data){
		$identity = $pvv_data['username'];
		$password = $pvv_data['password'];
		$email = $pvv_data['email'];
		$login_data['first_name'] = $pvv_data['prenom'];
		$login_data['last_name'] = $pvv_data['nom'];
		$login_data['phone'] = $pvv_data['telephone'];
		$login_data['entityid'] = $pvv_data['entity_id'];

		//$login_data['password_confirm'] = $pvv_data['password_confirm'];
		//exit;
		switch ($t) {
			case 'pvv':
				$groups = array('12');
				break;
			case 'educateur':
				$groups = array('11');
				break;			
			case 'medecin':
				$groups = array('9');
				break;			
			case 'infirmier':
				$groups = array('23');
				break;			
			case 'province':
				$groups = array('18');
				break;			
			case 'ville':
				$groups = array('19');
				break;			
			case 'zonesante':
				$groups = array('15');
				break;			
			case 'regionsante':
				$groups = array('14');
				break;			
			case 'ministere':
				$groups = array('17');
				break;			
			case 'societe_pharm':
				$groups = array('16');
				break;			
			case 'partenaire':
				$groups = array('6');
				break;			
			default:
				$groups = array();
				break;
		}
		$login_register = $this->ion_auth->register($identity, $password, $email, $login_data, $groups);
		return $login_register;
	}

	public function duplicate($t){

		$user=0;

		if(isset($this->session)){

			$id = $this->session->userdata('user_id');	

			if(is_numeric($id)){

				$user=$id;

			}	

		}

		

		$tables = $this->config->item('lgedit_tables');

		if(!isset($tables[$t])) die("table doesnt exists");



		$table = $tables[$t];

		$datas=$this->input->post();

		$id = $table['id'];



		$this->db->where($id,$datas[$id]);

		$this->db->where('table_name',$t);

		$ds = $this->db->get('lg_datas')->row_array();

			

		$this->db->insert('lg_datas_log',array('table_name' => $t, 'user' => $user , 'operation' => 'ADD', 'new_datas' => json_encode($ds)));

		

		unset($ds[$id]);



		$ds['table_name']=$t;

		$this->db->insert('lg_datas',$ds);



	}



	public function mod($t){

		return;

		$tables = $this->config->item('lgedit_tables');

		if(!isset($tables[$t])) die("table doesnt exists");



		$table = $tables[$t];

		$datas=$this->input->post();

		$id = $table['id'];

		

		print_r($datas);die();

			

		$this->db->where($id,$datas[$id]);

		$this->db->where('table_name',$t);

		$this->db->update('lg_datas',array('datas' => json_encode($datas)));

	}



	public function del($t){

		$tables = $this->config->item('lgedit_tables');

		if(!isset($tables[$t])) die("table doesnt exists");



		$table = $tables[$t];

		$id=$this->input->post('id');

		

		$datas=$this->db->where($table['id'],$id);

		$this->db->where('table_name',$t);

		$old_datas = $this->db->get('lg_datas')->row_array();

		

		$datas=$this->db->where($table['id'],$id);

		$this->db->where('table_name',$t);

		$this->db->delete('lg_datas');

		

		$user=0;

		if(isset($this->session)){

			$id = $this->session->userdata('user_id');	

			if(is_numeric($id)){

				$user=$id;

			}	

		}

		$this->db->insert('lg_datas_log',array('table_name' => $t, 'user' => $user , 'operation' => 'DEL', 'old_datas' => json_encode($old_datas)));

	}

	



	public function modPage($t,$id){

		$tables = $this->config->item('lgedit_tables');

		if(!isset($tables[$t])) die("table doesnt exists");

		$table = $tables[$t];

		$datas['table']=$t;
		$datas['title']=($t=='diffusions') ? 'Informations':ucfirst($t);

		$k = $table['id'];

		$this->db->where('table_name',$t);

		$this->db->where($k,$id);

		$res=$this->db->get('lg_datas')->row_array();

		$datas['datas']=json_decode($res['datas'],true);

		$datas['id']=$id;

		$datas['referer']=isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false;

		$this->load->view('lgedit/mod',$datas);

	}

	

	public function addPage($t,$param1=false,$value1=false){

		$tables = $this->config->item('lgedit_tables');

		if(!isset($tables[$t])) die("table doesnt exists");



		$table = $tables[$t];

		$datas['table']=$t;

		if($t=='pvv'){ $datas['title']='Inscrire un pvv'; }

		elseif($t=='societe_pharma'){ $datas['title']='Soci&eacute;t&eacute; pharmaceutique'; }

		elseif($t=='regionsante'){ $datas['title']='Centre de Distribution R&eacute;gional'; }

		elseif($t=='zonesante'){ $datas['title']='Zone sanitaire'; }

		elseif($t=='prescription_examens'){ $datas['title']='Prescriptions des examens'; }

		else{ $datas['title']=$t; }

		$datas['title']=strtoupper($datas['title']);

		$datas['datas']=array();

		//$datas['type_destinataire']=$_GET['type_destinataire'];

		if($param1 && $value1){

			$params = explode('_', $param1);

			$values = explode('_', $value1);

			foreach ($params as $k => $v) {

				$v = ($v=='c') ? 'consultation' : $v;

				$datas['datas'][$v]=$values[$k];

			}

		}
		if($t=='constante'){
			$datas['datas']['infirmier']=$this->session->userdata('user_id');
		}elseif($t=='consultation'){
			$datas['datas']['medecin']=$this->session->userdata('user_id');
		}elseif($t=='prescription_examens'){
			//if(!is_numeric($param1) && !is_numeric($value1))
			//	redirect($_SERVER['HTTP_REFERER']);
			//$pvvid = $this->input->get('pvv');
			//$pvv = $this->lg->get_data('pvv',array('id' => $pvvid),true);
			$datas['datas']['pvv'] = $this->input->get('pvv'); //$pvv['code'];
			$expl = explode('_', $this->input->get('cons'));
			$datas['datas']['consultation'] = $expl[1];
			$datas['datas']['medecin']=$this->session->userdata('user_id');
			$datas['datas']['ge']=array('unchecked');
			$datas['datas']['nfs']=array('unckecked');
		}

		//var_dump($datas['datas']); exit;


		/*if( ($t=='ordonnance') && (!$value) ){

			$datas['pvv']=$value;

		}*/

		$datas['referer']=isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false;

		//var_dump($datas['datas']); exit;



		//$this->load->view('view_file');



		$this->load->view('lgedit/add',$datas);

	}



	public function checkDB(){

		return;	

		if (!$this->db->table_exists('lg_datas')){

			//echo "11";	

		}

	}



	public function createDB(){ 	

		return;

		$q = 'CREATE TABLE `lg_datas` (

 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,

 `user` int(11) NOT NULL,

 `table_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

 `datas` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

 `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

 PRIMARY KEY (`id`),

 KEY `user` (`user`),

 KEY `table_name` (`table_name`)

) ENGINE=InnoDB AUTO_INCREMENT=739 DEFAULT CHARSET=utf8';



		$q2 = 'CREATE TABLE `lg_datas_log` (

 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,

 `table_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

 `user` int(11) NOT NULL,

 `operation` char(3) COLLATE utf8_unicode_ci NOT NULL,

 `old_datas` mediumtext COLLATE utf8_unicode_ci NOT NULL,

 `new_datas` mediumtext COLLATE utf8_unicode_ci NOT NULL,

 `date` timestamp NOT NULL DEFAULT \'0000-00-00 00:00:00\' ON UPDATE CURRENT_TIMESTAMP,

 PRIMARY KEY (`id`),

 KEY `table_name` (`table_name`,`date`),

 KEY `date` (`date`)

) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci';



		$this->db->query($q);

		$tables = $this->db->list_tables();

		foreach ($tables as $table){

			if(in_array($table,array('lg_datas'))) continue;

        	//echo $table.PHP_EOL;

			$res=$this->db->get($table)->result_array();

			foreach($res as $r){

				print_r($r);

				$datas = array(

					'table_name' => $table,

					'datas' => json_encode($r)

				);

				$this->db->insert('lg_datas',$datas);

			}

		}

		//sync ID	

	}

	public function syncIDs(){ 

		return;

		$tables = array('tarifs' => 'travaux','travaux' => 'project','projects' => 'client','clients' => false);

		$tables = array_reverse($tables);

		$nids = array(); 

		$ptable = false;

		foreach ($tables as $table => $key){

        	echo $table.PHP_EOL;

			$nids[$table]=array();



			$this->db->where('table_name',$table);

			$res=$this->db->get('lg_datas')->result_array();

			foreach($res as $r){

				$id = $r['id'];

				$datas = json_decode($r['datas'],true);

				echo "ID =>".$id.PHP_EOL;

				$nids[$table][$datas['id']]=$id;

				if($key){

					$datas[$key]=$nids[$ptable][$datas[$key]];

				}

				unset($datas['id']);

				print_r($datas);

				$this->db->where('id',$id);

				$this->db->update('lg_datas',array('datas' => json_encode($datas)));

			}

			$ptable=$table;

			//die();

		}

		//sync ID	

	}

}

