<?php
// src/ca_rdv.php?conseiller=2&choice=1&civ=&nom=T&prenom=&ENTITY=1&IDA=00100_PBMI0Pc
require '../../inc/PHPMailerAutoload.php';
// require './ses.php';
include ('../../inc/confNetisse.php');

if(isset($_GET['IDA'])) {

//$mail = new PHPMailer();

$start = date('H:i:s');
$IDA = $_GET['IDA'];

$partpro = 0;
$conseiller=$_GET['conseiller'];
$civ = "";
if (isset($_GET['civ'])) $civ = $_GET['civ'];
$nom = "";
if (isset($_GET['nom'])) $nom = $_GET['nom'];
$prenom = "";
if (isset($_GET['prenom'])) $prenom = $_GET['prenom'];
$company = "";
if (isset($_GET['company'])) $company = $_GET['company'];
$myst = ($conseiller == 0) ? 1 : 0;
$matricule = "";
if (isset($_GET['matricule'])) $matricule = $_GET['matricule'];
$NFCPROV = 0;
if (isset($_GET['nfcprov'])) $NFCPROV = $_GET['nfcprov'];

$CLIENT = 0;
if (isset($_GET['client'])) $CLIENT = $_GET['client'];
$PHONE = "";
if (isset($_GET['phone'])) $PHONE = $_GET['phone'];

$IDBORNE = 0;
if (isset($_GET['IDBORNE'])) $IDBORNE = $_GET['IDBORNE'];
$ENTITY = 0;
if ($GLOBALS["BO_CONF"]["ENTITIES"] && isset($_GET['ENTITY'])) $ENTITY = $_GET['ENTITY'];

$q = "SELECT id_agence, eds FROM ca_agences WHERE code_agence=:code_agence and supp=:supp ";
$values = array('code_agence' => $IDA, 'supp' => 0);
$result = excuteQuery($q, $values);
$o = $result['stmt']->fetch(PDO::FETCH_OBJ);
$agence = $o->id_agence;
$eds = $o->eds;

// PCZ : GESTION DU DECALAGE HORAIRE :


$dt = date('Y-m-d H:i:s');
$valuesInsert = array();
if (in_array($IDA, $GLOBALS["changeTimezone"])){
	$dt = changeTimeMG($dt);
}
else{
	$dtf = new DateTime($dto, new DateTimeZone('Europe/Paris'));
	$dtf->setTimezone(new DateTimeZone('Europe/Paris'));
	$dt = $dtf->format('Y-m-d H:i:s');
}

$companyQ = $companyV = "";
if($GLOBALS["BO_CONF"]["CLIENT"]["company"]){
	$companyQ = ", company";
	$companyV = ', :company';
        $valuesInsert['company']=$company;
}
$clientQ = $clientV = "";
if($GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]){
	$clientQ = ", client";
	$clientV = ', :client';
        $valuesInsert['client']=$CLIENT;
}
$ticket = 0;
$accompanyingPersons = array();
if (isset($_GET['accompanyingPersons'])) $accompanyingPersons = json_decode($_GET['accompanyingPersons']);

$phoneQ = $phoneV = "";
if($GLOBALS["BORNE_CONF"]["FIELDS"]["PHONE"] && $GLOBALS["BORNE_CONF"]["FIELDS"]["PHONE"]["ENABLED"]){
	$phoneQ = ", telephone";
	$phoneV = ', :telephone';
        $valuesInsert['telephone']=$PHONE;
}
if($GLOBALS["BO_CONF"]["GUICHETS"]){
	$r = excuteQuery("SELECT MAX(ticket) FROM ca_clients WHERE id_agence=".$agence." AND DATE(date_arrivee) = DATE(now())");
	$ticket = (int)$r['stmt']->fetch()[0];
	$ticket++;
}

$ticketQ = "";
$ticketV = "";
if($GLOBALS["BO_CONF"]["GUICHETS"]){
  $ticketQ = ",ticket" ;
  $ticketV = ", :ticket" ;
  $valuesInsert['ticket']=$ticket;
}

// SEARCH IF SAME CLIENT EXISTS
$qSearch = "SELECT id_client FROM ca_clients WHERE rdv = :rdv AND id_agence = :id_agence AND civ=:civ AND id_conseiller = :id_conseiller AND nom = :nom AND prenom=:prenom AND date_arrivee BETWEEN NOW() - INTERVAL 1 HOUR AND NOW()";
$valuesSearch = array('id_agence'=>$agence, 'rdv'=>"1", 'id_conseiller'=>$conseiller, 'civ'=>$civ, 'nom'=>$nom, 'prenom'=>$prenom);
$rSearch = excuteQuery($qSearch, $valuesSearch);
if (!$rSearch['status']) 
    wts_die (var_dump($rSearch['stmt']->errorInfo()));
$clientCount = $rSearch['stmt']->rowCount();

if($clientCount>0){
	echo json_encode(array("status"=>false));
	exit;
}


$qInsert = 'INSERT INTO ca_clients (id_client, id_agence, date_arrivee, date_priseencharge, date_cloture, rdv, rdv_type, id_conseiller, entite, nbr, civ, nom, prenom, nfcprov, id_borne, matricule'.$companyQ.$clientQ.$ticketQ.$phoneQ.') '
        . 'VALUES (:id_client, :id_agence, :date_arrivee, :date_priseencharge, :date_cloture, :rdv, :rdv_type, :id_conseiller, :entite, :nbr, :civ, :nom, :prenom, :nfcprov, :id_borne, :matricule'.$companyV.$clientV.$ticketV.$phoneV. ')';

$valuesInsert += array('id_client'=>NULL, 'id_agence'=>$agence, 'date_arrivee'=>$dt,'date_priseencharge'=>'0000-00-00 00:00:00', 'date_cloture'=>'0000-00-00 00:00:00', 'rdv'=>"1", 'rdv_type'=>$partpro, 'id_conseiller'=>$conseiller, 'entite'=>$ENTITY, 'nbr'=>'0', 'civ'=>$civ, 'nom'=>$nom, 'prenom'=>$prenom, 'nfcprov'=>$NFCPROV, 'id_borne'=>$IDBORNE, 'matricule' => $matricule);
$rInsert = excuteQuery($qInsert, $valuesInsert);

if (!$rInsert['status']) 
    wts_die (var_dump($rInsert['stmt']->errorInfo()));

$id=$GLOBALS["cnx"]->lastInsertId();

$ADRESSES = array();
if($myst == 0){
	$mailCol = ($GLOBALS["BO_CONF"]["CONSEILLER"]["receive_email"]) ? ", receive_email" : "";
	$q = "SELECT email, nom, prenom, civ".$mailCol." FROM ca_conseillers WHERE id_conseiller=".$conseiller;
        $r=excuteQuery($q);
	if (!$r['status']) 
            wts_die (var_dump($r['stmt']->errorInfo()));
	while($o = $r['stmt']->fetch(PDO::FETCH_OBJ))
    {
		$to=$o->email;
		$ADRESSES[0] = $to;
		$consnom=$o->nom;
		$consprenom=$o->prenom;
		$consciv=$o->civ;
		$receivemail=$o->receive_email;
	}
}
else{
	$q = "SELECT email, nom, prenom, civ FROM ca_conseillers WHERE id_agence=".$agence." AND inactif='0' AND supp=0 AND fonction='4'";
	$r =excuteQuery($q);
        if (!$r['status']) 
            wts_die (var_dump($r['stmt']->errorInfo()));
	$i = 0;
	while($o = $r['stmt']->fetch(PDO::FETCH_OBJ))
	{
		$check = explode(";", $o->email);
		if (count($check) == 1) {
			if (!in_array($o->email, $ADRESSES)) {
				$ADRESSES[$i] = $o->email;
				$i++;
			}
		} else {
			for($j=0;$j<(count($check));$j++) {
				if (!in_array($check[$j], $ADRESSES)) {
					$ADRESSES[$i] = $check[$j];
					$i++;
				}
			}
		}
	}
	$consprenom="Je ne connais pas";
	$consnom="mon conseiller";
}

$q = "SELECT count(*) as total FROM ca_clients WHERE DATEDIFF(date_arrivee,now())=0 AND id_agence='".$agence."' ORDER BY id_client";
$r =excuteQuery($q);
        if (!$r['status']) 
            wts_die (var_dump($r['stmt']->errorInfo()));
while($o = $r['stmt']->fetch(PDO::FETCH_OBJ))
    {
		$total = $o->total;
	}

$q = "UPDATE ca_clients SET nbr=".$total." WHERE id_client =".$id;
$r =excuteQuery($q);
        if (!$r['status']) 
            wts_die (var_dump($r['stmt']->errorInfo()));

$return = array("status"=>true);
$return["ticket"] = $ticket;

if($GLOBALS["BORNE_CONF"]["RDV_CALENDAR"]){
	// INSERT ROW ca_rdv_calendar
	$rdvInfos = json_decode($_REQUEST["rdv"]);
	$matricule = $rdvInfos->matricule;
	$uid = $rdvInfos->uid_client;
	$theme_id = $rdvInfos->theme;
	$theme = $theme_id ? (isset($GLOBALS["BORNE_CONF"]["RDV_CALENDAR_THEMES"][$theme_id]) ? $GLOBALS["BORNE_CONF"]["RDV_CALENDAR_THEMES"][$theme_id] : $theme_id) : '';
	$dd = $rdvInfos->date_debut;
	$df = $rdvInfos->date_fin;
	$q = "INSERT INTO ca_rdv (id_client, id_agence, id_conseiller, matricule, eds, uid_client, civ_client, nom_client, prenom_client, theme_id, theme, date_debut, date_fin) VALUES (
		:id_client, :id_agence, :id_conseiller, :matricule, :eds, :uid_client, :civ_client, :nom_client, :prenom_client, :theme_id, :theme, :date_debut, :date_fin
	)";
	$values = array(
		":id_client" => $id,
		":id_agence" => $agence,
		":id_conseiller" => $conseiller,
		":matricule" => $matricule,
		":eds" => $eds,
		":uid_client" => $uid,
		":civ_client" => $civ,
		":nom_client" => $nom,
		":prenom_client" => $prenom,
		":theme_id" => $theme_id,
		":theme" => $theme,
		":date_debut" => $dd,
		":date_fin" =>  $df
	);
	$r =excuteQuery($q, $values);
    if (!$r['status']) 
        $return["status"] = false;
}

echo json_encode($return);

} else {
	echo json_encode(array("status"=>false));
	//echo "<html><head><style type=\"text/css\">body {font-family:Arial ,sans-serif;font-size:14px;color:#000;}</style></head><body><center><img src=\"images/ca_logo.jpg\" width=\"110\" height=\"90\" alt=\"Credit Agricole\" title=\"Credit Agricole\"/><br/><br/>L'adresse de cette page n'est pas correcte.<br/>Contactez le Service informatique de votre caisse.</center></body></html>";
}
?>