<?php

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

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

//$mail = new PHPMailer();

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

$afa  = (isset($GLOBALS["BO_CONF"]["AFA"]) && $GLOBALS["BO_CONF"]["AFA"]) ? true : false;
$guichets  = (isset($GLOBALS["BO_CONF"]["GUICHETS"]) && $GLOBALS["BO_CONF"]["GUICHETS"]) ? true : false;

$rdv = isset($_GET['choice']) ? $_GET['choice'] : 0;

$civ = "";
if (isset($_GET['civ'])) $civ = $_GET['civ'];
$nom = "";
$prenom = "";
if (isset($_GET['nom'])) $nom = $_GET['nom'];
if (isset($_GET['prenom'])) $prenom = $_GET['prenom'];
$company = "";
if (isset($_GET['company'])) $company = $_GET['company'];
$NFCPROV = 0;
if (isset($_GET['nfcprov'])) $NFCPROV = $_GET['nfcprov'];
$meeting = ($choice == 2) ? 1 : 0;
$matricule = "";
if (isset($_GET['matricule'])) $matricule = $_GET['matricule'];

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

$action = "";
if (isset($_GET['action'])) $action = $_GET['action'];

$action = $action ? json_decode($action) : false;

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

$IDMOTIF = 0;
if (isset($_GET['motif'])) $IDMOTIF = $_GET['motif'];
$PHONE = "";
if (isset($_GET['phone'])) $PHONE = $_GET['phone'];

$MOTIFS = ($GLOBALS["BORNE_CONF"]["MULTIPLEMOTIFS"])?explode(",", $IDMOTIF):array($IDMOTIF);

$afaQ = $afa ? ", is_afa" : "";
$q = "SELECT id_agence, type_agence".$afaQ." FROM ca_agences WHERE code_agence=:code_agence and supp=:supp ";
$values = array(':code_agence' => $IDA, ':supp' => 0);
$result = excuteQuery($q, $values);
$r = $result['stmt'];
$o = $r->fetchObject();
$agence = $o->id_agence;
$type = $o->type_agence;
$is_afa = $afa ? $o->is_afa : 0;

$objetVenue = "";

$companyQ = $companyV = "";
$valuesInsert = array();
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;
}
$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;
}
$ticket = 0;
// PCZ : GESTION DU DECALAGE HORAIRE :
$dt = date('Y-m-d H:i:s');
if (in_array($IDA, $GLOBALS["changeTimezone"])){
    $dt = changeTimeMG($dt);
}
else{
	$dtf = new DateTime($dt, new DateTimeZone('Europe/Paris'));
	$dtf->setTimezone(new DateTimeZone('Europe/Paris'));
	$dt = $dtf->format('Y-m-d H:i:s');
}



// SEARCH IF SAME CLIENT EXISTS
$qSearch = "SELECT id_client FROM ca_clients WHERE rdv = :rdv AND id_agence = :id_agence AND civ=:civ AND nom = :nom AND prenom=:prenom AND date_arrivee BETWEEN NOW() - INTERVAL 1 HOUR AND NOW()";
$valuesSearch = array('id_agence'=>$agence, 'rdv'=>"0", '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;
}


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++;

    $guichet = false;
    if($type == 3){ // CE
        $r = excuteQuery("SELECT numero, gm.id_guichet as id FROM ca_guichet_motifs gm LEFT JOIN ca_guichets g ON g.id_guichet = gm.id_guichet WHERE gm.id_agence=".$agence." AND gm.id_motif = ".$MOTIFS[0]." ORDER BY gm.id_guichet ASC LIMIT 1");
        if ($r['status'])
            $guichet = $r['stmt']->fetchObject();
    }
}

if($choice == 0 && $is_afa && $action && $action->is_motif == "0"){
    $message = $action->message ? $action->message : "";
    $phone_number = $action->phone_number ? $action->phone_number : "";
    $q = 'INSERT INTO ca_pile_cc (`id_client_cc`, `id_agence`, `date_arrivee`, `date_priseencharge`, `id_action`, `id_cc`, `entite`, `civ`, `nom`, `prenom`, `nfcprov`, `message`, `phone`, `id_motif`) VALUES 
    (:id_client_cc, :id_agence, :date_arrivee, :date_priseencharge, :id_action, :id_cc, :entite, :civ, :nom, :prenom, :nfcprov, :message, :phone, :id_motif) '; 
        $valuesQ = array(':id_client_cc'=>NULL, ':id_agence'=>$agence, ':date_arrivee'=>$dt, ':date_priseencharge'=>"0000-00-00 00:00:00", ':id_action'=>$action->id, ':id_cc'=>"0", ':entite'=>$ENTITY, ':civ'=>$civ, ':nom'=>$nom, ':prenom'=>$prenom, ':nfcprov'=>$NFCPROV, ':message'=>$message, ':phone'=>$phone_number, ':id_motif'=>$IDMOTIF);
        $r = excuteQuery($q, $valuesQ);
        if (!$r['status']) 
           wts_die (show_error($r['stmt']->errorInfo()));
}
else{   
    $rdv_type = ($is_afa && $action && $action->is_motif == "1") ? $action->id : "0"; // ACTION ID
    $ticketQ = $GLOBALS["BO_CONF"]["GUICHETS"] ? ",ticket" : "";
        
    $ticketQ .= $guichet ? ",guichet" : "";
    $ticketV = $GLOBALS["BO_CONF"]["GUICHETS"] ? ", :ticket" : "";
    $ticketV .= $guichet ? ", :guichet" : "";
        
        $ticketQ = "";
        $ticketV = "";
        if($GLOBALS["BO_CONF"]["GUICHETS"]){
          $ticketQ = ",ticket" ;
          $ticketV = ", :ticket" ;
          $valuesInsert[':ticket']=$ticket;
        }
        if($guichet){
          $ticketQ .= ",guichet" ;
          $ticketV .= ", :guichet" ;
          $valuesInsert[':guichet']=$guichet->id;
        }
    
        $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_merge($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'=>$rdv, ':rdv_type'=>intval($partpro), ':id_conseiller'=>intval($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 (show_error($rInsert['stmt']->errorInfo()));

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

$afa_motifs = (isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) ? true : false;

if($choice == 0 && (!$action || $afa_motifs)){ // sans RDV
    foreach($MOTIFS as $IDMOTIF){
        $q = 'INSERT INTO ca_client_motifs (id_client,id_motif) values ('.$id.','.$IDMOTIF.')';
        $r = excuteQuery($q);
        if (!$r['status']) 
                    wts_die (show_error($r['stmt']->errorInfo()));
    }
}
if($accompanyingPersons){
    foreach($accompanyingPersons as $accompanyingPerson){
            $valuesInsert = array();
                if($GLOBALS["BO_CONF"]["CLIENT"]["company"]){
                    $companyQ = ", company";
                    $companyA = ', :company';
                    $valuesInsert['company']=(',"'.$accompanyingPerson->company).'"';
                }
        $q = 'INSERT INTO ca_accompanying_persons (id_client, civ, nom, prenom'.$companyQ.') VALUES '
                . '(:id_client, :civ, :nom, :prenom'.$companyA.')'; 
                
                $valuesInsert += array(':id_client'=>$id, ':civ'=>$accompanyingPerson->civilite, ':nom'=>$accompanyingPerson->firstname, ':prenom'=>$accompanyingPerson->lastname);
                $r = excuteQuery($q, $valuesInsert);
                if (!$r['status']) 
                    wts_die (show_error($r['stmt']->errorInfo()));
                
                
        }
}


if(!$action){
    $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 (show_error($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 (show_error($r['stmt']->errorInfo()));
}

$return = array("status"=>true);
$return["ticket"] = $ticket;
$return["guichet"] = $guichet->numero;
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>";
}
?>