<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.2
 *
 * Copyright (C) 2006-2015  Sylvain FATOME
 * This program is free software; you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program
 * (in the directory docs);
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Contact : galawa@free.fr
 *
 * Web : http://smi.no-ip.org
 ****************************************************************************************/


// Vérification des tentatives de hack
$pos = strpos($_SERVER['PHP_SELF'], "inc.php");
if ($pos === FALSE)
    $ok_inc = TRUE;
else
    $ok_inc = FALSE;
if ($ok_inc == FALSE) header("Location: ../index.php");

/***********************************************************/
/* Fonctions pour les accès aux fichiers multi rendez-vous */
/***********************************************************/

/**
 * Lecture d'un RDV par son code pièce rattachée
 * A utiliser uniquement lors de l'enregistrement initial
 *
 * @param $typrat
 * @param $coderat
 * @param bool $open
 * @return array|null
 */
function lit_enr_rdv_code($typrat, $coderat, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT * FROM `" . TBRDV . "`";
    $rexist .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
    $row2 = $db->get_row($rexist, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Lecture d'un RDV par son ID
 *
 * @param $id
 * @param bool $open
 * @param string $typ
 * @return array|null
 */
function lit_enr_rdv_id($id, $open = TRUE, $typ = "")
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT * FROM `" . TBRDV . "`";
    $rexist .= " WHERE rdv_id=" . $id;
    switch ($typ) {
        case "num" :
            $row2 = $db->get_row($rexist, ARRAY_N);
            break;
        default :
            $row2 = $db->get_row($rexist, ARRAY_A);
            break;
    }
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification du nombre de rendez-vous pour un type et numéro donné
 *
 * @param $typrat
 * @param $coderat
 * @param bool $open
 * @return null
 */
function nb_rdv($typrat, $coderat, $open = TRUE)
{
    global
    $db;


    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBRDV . "`";
    $rexist .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Retourne le détail des RDV pour un rattachement
 * filtrenonhonore = on ne prend que les RDV non honorés
 * idrdv = on filtre sur un ID de RDV en particulier
 *
 * @param $typrat
 * @param $coderat
 * @param $filtrenonhonore
 * @param $idrdv
 * @param bool $open
 * @return array
 */
function detail_rdv_rat($typrat, $coderat, $filtrenonhonore, $idrdv, $open = TRUE)
{
    global
    $db;
    $tab = [];

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBRDV . "`";
    $rech2 .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
    if ($filtrenonhonore == TRUE)
        $rech2 .= " AND rdv_honore=0";
    if (intval($idrdv) > 0)
        $rech2 .= " AND rdv_id=" . intval($idrdv);
    $rech2 .= " ORDER BY rdv_date, rdv_heure";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            $row2 = encode_str($row2);
            extract($row2);
            $txt_rdv = datetolocal($rdv_date) . " (" . _("à partir de") . " " . substr($rdv_heure, 0, 5) . ")";

            $rech3 = "SELECT lieu_desc FROM `" . TBLIEU . "` WHERE lieu_code = '$rdv_codelieu'";
            $row3 = $db->get_row($rech3, ARRAY_A);
            if ($row3) {
                $row3 = encode_str($row3);
                extract($row3);
                $txt_rdv .= " \n" . $lieu_desc;
            }
            $tab[] = $txt_rdv;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $tab;
}

/**
 * Retourne le prochain rendez-vous non honoré pour un type et numéro donné en tenant compte de la date du jour
 *
 * @param $typrat
 * @param $coderat
 * @param bool $open
 * @return array|null
 */
function next_rdv($typrat, $coderat, $open = TRUE)
{
    global
    $db,
    $datea,
    $heurea;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    // On trouve les RDV supérieurs ou égaux à la date du jour
    $rech2 = "SELECT * FROM `" . TBRDV . "`";
    // $rech2 .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
    $rech2 .= " WHERE rdv_typrat=" . $typrat . " AND rdv_coderat='" . $coderat . "'";
    $rech2 .= " AND rdv_honore=0 AND (rdv_date>'" . $datea . "'";
    $rech2 .= " OR (rdv_date='" . $datea . "' AND rdv_heure>'" . $heurea . "'))";
    $rech2 .= " ORDER BY rdv_date, rdv_heure";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Retourne le dernier rendez-pris pour un type et numéro donné en tenant compte de la date du jour
 *
 * @param $typrat
 * @param $coderat
 * @param bool $open
 * @return array|null
 */
function last_rdv($typrat, $coderat, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    // On trouve les RDV supérieurs ou égaux à la date du jour
    $rech2 = "SELECT * FROM `" . TBRDV . "`";
    // $rech2 .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
    $rech2 .= " WHERE rdv_typrat=" . $typrat . " AND rdv_coderat='" . $coderat . "'";
    $rech2 .= " ORDER BY rdv_date DESC, rdv_heure DESC";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Retourne s'il y a des RDV non honoré (date dépassée et pas de travail saisi) en tenant compte de la date du jour
 * ATTENTION : Interventions closes pas concernées
 *
 * @param $typrat
 * @param $coderat
 * @param bool $open
 * @return null
 */
function missed_rdv($typrat, $coderat, $open = TRUE)
{
    global
    $db,
    $datea,
    $heurea;


    $a_verifier = TRUE;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    switch (intval($typrat)) {
        // Interventions
        case 1 :
            $rech2 = "SELECT int_datefin FROM `" . TBINT . "`";
            $rech2 .= " WHERE int_code='" . $db->escape($coderat) . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                extract($row2);
                if ($int_datefin <> "0000-00-00")
                    $a_verifier = FALSE;
            }
            break;
        default :
            break;
    }

    if ($a_verifier == TRUE) {
        $rech2 = "SELECT COUNT(rdv_id) FROM `" . TBRDV . "`";
        $rech2 .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
        $rech2 .= " AND rdv_honore=0 AND (rdv_date<'" . $datea . "'";
        $rech2 .= " OR (rdv_date='" . $datea . "' AND rdv_heure<'" . $heurea . "'))";
        $rech2 .= " ORDER BY rdv_date";
        $nbexist = $db->get_var($rech2);;
    }
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Ajoute un rendez-vous pour un type et numéro donné
 *
 * @param $date
 * @param $heure
 * @param $dureem
 * @param $codelieu
 * @param $typrat
 * @param $coderat
 * @param bool $open
 */
function add_rdv($date, $heure, $dureem, $codelieu, $typrat, $coderat, $open = TRUE)
{
    global
    $db,
    $_SESSION,
    $datea;

    $codeuser = @$_SESSION["code_log"];

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    // On vérifie si le RDV a déjà été pris
    $rech2 = "SELECT rdv_id FROM `" . TBRDV . "`";
    $rech2 .= " WHERE rdv_typrat=" . $db->escape($typrat) . " AND rdv_coderat='" . $db->escape($coderat) . "'";
    $rech2 .= " AND rdv_date='" . $date . "' AND rdv_heure='" . $heure . "' AND rdv_dureem=" . $dureem;
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($row2) // Déjà saisi : on modifie
    {
        extract($row2);
        $rech3 = "UPDATE `" . TBRDV . "` SET `rdv_datemod`='" . $datea . "', `rdv_codemod`='" . $codeuser . "',";
        $rech3 .= " `rdv_date`='" . $date . "',`rdv_codelieu`='" . $db->escape($codelieu) . "', `rdv_heure`='" . $heure . "', `rdv_dureem`='" . $dureem . "'";
        $rech3 .= " WHERE `rdv_id` = '" . $rdv_id . "'";
    } else // Pas saisi : on ajoute
    {
        $rech3 = "INSERT INTO `" . TBRDV . "`";
        $rech3 .= " (rdv_datecrea,rdv_codecrea,rdv_datemod,rdv_codemod,rdv_typrat,rdv_coderat,rdv_date,rdv_codelieu,";
        $rech3 .= "rdv_heure,rdv_dureem)";
        $rech3 .= " VALUES";
        $rech3 .= " ('$datea','$codeuser','$datea','$codeuser','" . $db->escape($typrat) . "','" . $db->escape($coderat) . "','$date','" . $db->escape($codelieu) . "',";
        $rech3 .= "'$heure','$dureem')";
    }
    $db->query($rech3);

    if ($open == TRUE)
        $db->disconnect();
}

/**
 * Vérifie si un RDV est honoré (saisi dans un historique)
 * $full : on vérifie si, dans le cas où le RDV a été planifié, tous les techniciens sont intervenus
 *
 * @param $typrat
 * @param $idrdv
 * @param bool $full
 * @param bool $open
 * @return int
 */
function honore_rdv($typrat, $idrdv, $full = TRUE, $open = TRUE)
{
    global
    $db;

    // 0 : pas honoré du tout
    // 1 : Honoré en partie
    // 2 : Honoré à 100%
    $honore = 0;
    $rech2 = "";

    // On veut juste vérifie si au moins un RDV a été traité
    if ($full == FALSE) {
        switch ($typrat) {
            // Interventions
            case 1 :
                $rech2 = "SELECT COUNT(inth_id) FROM `" . TBINTH . "`";
                $rech2 .= " WHERE inth_idrdv=" . intval($idrdv);
                break;
            default :
                break;
        }

        if ($rech2 <> "") {
            if ($open == TRUE)
                $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

            $nbres2 = $db->get_var($rech2);
            if ($nbres2 > 0)
                $honore = 2;

            if ($open == TRUE)
                $db->disconnect();
        }
    } else // On veut vérifier si tous les RDV planifiés ont été honorés
    {
        $rech2 = "SELECT pevt_dest FROM `" . TBPEVT . "`";
        $rech2 .= " WHERE pevt_idrdv=" . intval($idrdv);

        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        // On construit le tableau des techniciens ayant été planifiés pour ce RDV
        $tab_tec = [];

        $rows2 = $db->get_results($rech2, ARRAY_A);
        if ($rows2) {
            foreach ($rows2 as $row2) {
                extract($row2);
                $tab_tec[] = $pevt_dest;
            }
        }

        // On vérifie si chaque technicien planifié a bien reçu une saisie d'historique pour ce RDV
        if (count($tab_tec) > 0) {
            $found = 0;

            foreach ($tab_tec as $value) {
                $rech2 = "";
                switch ($typrat) {
                    // Interventions
                    case 1 :
                        $rech2 = "SELECT COUNT(inth_id) FROM `" . TBINTH . "`";
                        $rech2 .= " WHERE inth_idrdv=" . intval($idrdv);
                        $rech2 .= " AND inth_codetec='" . $value . "'";
                        break;
                    default :
                        break;
                }

                if ($rech2 <> "") {
                    $nbres2 = $db->get_var($rech2);
                    if ($nbres2 == 1)
                        $found++;
                }
            }

            if ($found == 0)
                $honore = 0;
            else {
                if ($found == count($tab_tec))
                    $honore = 2;
                else
                    $honore = 1;
            }
        } // Rien n'a été planifié pour ce RDV
        // S'il y a au moins un historique de saisi dans les historiques interventions,
        // pour ce RDV, on considère que c'est honoré
        else {
            switch ($typrat) {
                // Interventions
                case 1 :
                    $rech2 = "SELECT COUNT(inth_id) FROM `" . TBINTH . "`";
                    $rech2 .= " WHERE inth_idrdv=" . intval($idrdv);
                    break;
                default :
                    break;
            }

            if ($rech2 <> "") {
                $nbres2 = $db->get_var($rech2);
                if ($nbres2 > 0)
                    $honore = 2;
            }
        }

        if ($open == TRUE)
            $db->disconnect();
    }

    return $honore;
}

/**
 * Création du code Javascript pour affichage des RDV de l'intervention
 *
 * @param $id_html
 * @param $td
 * @param $code
 * @param string $from
 * @param bool $open
 * @internal param $id
 */
function cre_html_trdv($id_html, $td, $code, $from = '', $open = TRUE)
{
    global
    $db,
    $rdv_titre_col,
    $rdvcli_titre_col,
    $mod_planning,
    $_SESSION;

    $rdv_maj = TRUE; // Autorisation de mettre à jour les RDV
    $rdv_detail = TRUE; // Autorisation d'afficher le détail des RDV

    // Création de la chaine HTML

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    // On récupère le code du technicien responsable
    $rech = "SELECT int_codetec FROM `" . TBINT . "`";
    $rech .= " WHERE int_code='" . $db->escape($code) . "'";
    $row = $db->get_row($rech, ARRAY_A);
    if ($row) {
        $row = encode_str($row);
        extract($row);
    }

    switch ($_SESSION["niv_log"]) {
        case 1 :
        case 2 :
            $rdv_maj = FALSE;
            $rdv_detail = FALSE;
            break;
        case 3 :
            if ($_SESSION["code_log"] <> $int_codetec)
                $rdv_maj = FALSE;
            break;
        default :
            break;
    }

    // On construit la table des RDV
    $rech = "SELECT * FROM `" . TBRDV . "`";
    $rech .= " WHERE rdv_typrat=1 AND rdv_coderat='" . $db->escape($code) . "'";
    $rech .= " ORDER BY rdv_date, rdv_heure";
    $rows = $db->get_results($rech, ARRAY_A);
    // *** Affichage de la table
    $str_html = '<table id="trdv" class="Mtable" border="0" width="100%" cellpadding="0" cellspacing="0">';

    // Création entête
    if (@$_SESSION["niv_log"] <> 1) {
        foreach ($rdv_titre_col as $nom_col => $code_champ) {
            $str_html .= '<th>';
            $str_html .= ucfirst($nom_col);
            $str_html .= '</th>';
        }
        if ($td == "edit")
            $str_html .= '<th>' . _("Cliquer") . '</th>';
    } else {
        foreach ($rdvcli_titre_col as $nom_col => $code_champ) {
            $str_html .= '<th>';
            $str_html .= ucfirst($nom_col);
            $str_html .= '</th>';
        }
    }

    $i = 0;
    if ($rows) {
        foreach ($rows as $row) {
            $row = encode_str($row);
            // Couleurs alternées
            if ($i % 2 == 0)
                $str_html .= '<tr onmouseover="this.className=\'TRsel\'" onmouseout="this.className=\'TRalter1\'" class="TRalter1">';
            else
                $str_html .= '<tr onmouseover="this.className=\'TRsel\'" onmouseout="this.className=\'TRalter2\'" class="TRalter2">';

            if ($rdv_detail == TRUE) {
                // Urgence
                $str_html .= '<td align="center" width="30px"';
                $couleur = give_coul_urg($row["rdv_nivurg"], FALSE);
                $detail = give_nom_urg($row["rdv_nivurg"], FALSE);;
                if ($couleur <> "XX")
                    $str_html .= ' style="background:' . $couleur . '"';
                $str_html .= ' >';
                $str_html .= '<a href="#" class="pop"><img src="../img/none.gif" alt="'._("Détail").'" border="0" align="absmiddle"><span>' . formatetxtbr($detail) . '</span></a>';
                $str_html .= '</td>';
                // Fin affichage détail urgence

                // Planifié ?
                $str_html .= '<td align="center">';
                $planifie = est_planifie_rdv($row["rdv_id"], FALSE);
                if ($planifie == FALSE)
                    $str_html .= '<img src="../img/none.gif" border="0" align="absmiddle">';
                else {
                    $detail = detail_planifie_rdv($row["rdv_id"], TRUE, FALSE);
                    if ($detail <> "")
                        $str_html .= '<a href="#" class="pop"><img src="../img/ok.png" border="0" align="absmiddle"><span>' . formatetxtbr($detail) . '</span></a>';
                    else
                        $str_html .= '<img src="../img/ok.png" title="'._("oui").'" border="0" align="absmiddle">';
                }
                $str_html .= '</td>';

                // Honoré ?
                $str_html .= '<td align="center">';
                $honore = honore_rdv(1, $row["rdv_id"], TRUE, FALSE);
                if ($honore > 0) {
                    $detail = detail_honore_rdv($row["rdv_id"], TRUE, FALSE);
                    $img_honore = "../img/ok.png";
                    $alt_img = _("oui");
                    if ($honore == 1) {
                        $img_honore = "../img/warn.png";
                        $detail = '('._("Partiellement honoré").')<br /><br />' . $detail;
                    }
                    if ($detail <> "")
                        $str_html .= '<a href="#" class="pop"><img src="' . $img_honore . '" border="0" align="absmiddle"><span>' . formatetxtbr($detail) . '</span></a>';
                    else
                        $str_html .= '<img src="' . $img_honore . '" title="' . $alt_img . '" border="0" align="absmiddle">';
                } else
                    $str_html .= '<img src="../img/none.gif" border="0" align="absmiddle">';
                $str_html .= '</td>';
            }

            $str_html .= '<td align="center">';
            $str_html .= datetolocal($row["rdv_date"]);
            $str_html .= '</td>';
            $str_html .= '<td align="center">';
            $str_html .= substr($row["rdv_heure"], 0, 5);
            $str_html .= '</td>';
            $str_html .= '<td>';
            $str_html .= '<div align="center">';

            $lieu = $row["rdv_codelieu"];
            $rech2 = "SELECT * FROM `" . TBLIEU . "` WHERE lieu_code = '$lieu'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                $row2 = encode_str($row2);
                extract($row2);
                if ($lieu_img <> "") {
                    $lieuint = $lieu_desc . " (" . $lieu . ")";
                    $str_html .= '<img src="' . $lieu_img . '" title="' . $lieuint . '" border="0" align="absmiddle">';
                } else {
                    $str_html .= '<span class="annot_std_it">';
                    $str_html .= $lieu;
                    $str_html .= "</span>";
                }
            }
            $str_html .= "</div>";
            $str_html .= '</td>';

            if ($rdv_detail == TRUE) {
                // Durée
                $str_html .= '<td align="center">';
                $str_html .= substr(sec_heure($row["rdv_dureem"] * 60), 0, 5);
                $str_html .= '</td>';
            }

            // icônes
            switch ($td) {
                case "edit" :
                    $str_html .= '<td align="center">';
                    if ($honore < 2) {
                        if ($rdv_maj == TRUE) {
                            $url_edit = "rdvi_maj.php?td=edit&ci=" . $code . "&rdv=" . $row["rdv_id"];
                            if (url_ok($url_edit, FALSE) == TRUE)
                                $str_html .= cre_falselnk_img('', 'rdvi_edit_'.$row["rdv_id"], 'span', '', _("Edition"), 'lnkpop', $url_edit, '../img/edit.png', 500 , 300, true,true);
                            $url_del = "rdvi_maj.php?td=del&ci=" . $code . "&rdv=" . $row["rdv_id"];
                            if (url_ok($url_del, FALSE) == TRUE)
                                $str_html .= cre_falselnk_img('', 'rdvi_del_'.$row["rdv_id"], 'span', '', _("Suppression"), 'lnkpop', $url_del, '../img/del.png', 500 , 300, true,true);
                            // On vérifie si le module planning est bien en place
                            if ($mod_planning == TRUE) {
                                $urlplan = 'plan_addedit.php?';
                                if ($planifie == FALSE) {
                                    $urlplan .= 'td=add&typd=-1&coded=&typr=1&coder='.$row["rdv_coderat"];
                                    // MAJ ID RDV
                                    $urlplan .= '&irdv=' . $row["rdv_id"];
                                    // Lieu d'appel
                                    $urlplan .= '&tx=int&from=int';
                                    $str_html .= cre_falselnk_img('', 'plan_add_'.$row["rdv_id"], 'span', '', _("Ajout planification"), 'lnkpop', $urlplan, '../img/plan_add.png', 1020 , 760, true,true);
                                } else {
                                    $urlplan .= 'td=edit&typd=-1&coded=&typr=1&coder='.$row["rdv_coderat"];
                                    // MAJ ID RDV
                                    $urlplan .= '&irdv=' . $row["rdv_id"];
                                    // Lieu d'appel
                                    $urlplan .= '&tx=int&from=int';
                                    $str_html .= cre_falselnk_img('', 'plan_edit_'.$row["rdv_id"], 'span', '', _("Edition planification"), 'lnkpop', $urlplan, '../img/plan_edit.png', 1020 , 760, true,true);
                                }
                            }
                        }
                        $alea = time();
                        $url_imp = "int_pdf.php?token=" . $alea . "&ci=" . $code . "&rdv=" . $row["rdv_id"];
                        $str_html .= cre_falselnk_img('', 'int_pdf_'.$row["rdv_id"], 'span', '', _("Impression intervention"), 'lnkpop', $url_imp, '../img/print.png', 0 , 0, true,true);
                    } else
                        $str_html .= '<img src="../img/none.gif" border="0" align="absmiddle">';
                    $str_html .= '</td>';
                    break;
                default :
                    break;
            }
            $str_html .= '</tr>';
            $i++;
        }
    }
    $str_html .= "</table>";
    if ($open == TRUE)
        $db->disconnect();


    echo 'function updatmrdv() {';
    echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
    echo $from . "$('#" . $id_html . "').html('" . str_replace("'", "\'", $str_html) . "');";
    echo '}';
    echo '}';
}


/**
 * Création du code Javascript pour affichage des prochains RDV de l'intervention
 *
 * @param $id_html
 * @param $td
 * @param $code
 * @param string $from
 * @param bool $open
 * @internal param $id
 */
function cre_html_nextrdv($id_html, $td, $code, $from = '', $open = TRUE)
{
    global
    $db,
    $_SESSION;

    $rdv_add = TRUE; // Autorisation d'ajouter des RDV

    // Création de la chaine HTML
    $str_html = '';

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    // On récupère le code du technicien responsable
    $rech = "SELECT int_codetec FROM `" . TBINT . "`";
    $rech .= " WHERE int_code='" . $code . "'";
    // $rech .= " WHERE int_code='" . $db->escape($code) . "'";
    $row = $db->get_row($rech, ARRAY_A);
    if ($row)
        extract($row);

    switch ($_SESSION["niv_log"]) {
        case 1 :
        case 2 :
            $rdv_add = FALSE;
            break;
        case 3 :
            if ($td == "edit") {
                if ($_SESSION["code_log"] <> $int_codetec)
                    $rdv_add = FALSE;
            }
            break;
        default :
            break;
    }

    if ($rdv_add == TRUE) {
        if (($td == "add") OR ($td == "edit")) {
            $str_html = '<div class="haut_droit">';
            $url_addrdv = "rdvi_maj.php?td=add&ci=" . $code;
            if (url_ok($url_addrdv,FALSE) == TRUE)
            {
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$url_addrdv."','rdvi_addrdv_".$ci."',500,300,'yes')\")>";
                $str_html .= '<img src="../img/intp.png" border="0" align="absmiddle" title="' . _("Ajout RDV") . '"></a>';
            }

                // $str_html .= '<a href="javascript:;" onclick="fensaisie(\'' . $url_addrdv . '\',500,300,\'status=no,scrollbars=yes,menubar=no,statusbar=no,location=no,locationbar=no\');")><img src="../img/intp.png" border="0" align="absmiddle" alt="rdv" title="' . _("Ajouter RDV") . '"></a>';
            $str_html .= '</div>';
        }
    }

    $str_html .= '<div class="titre_gras" style="margin-bottom:2px;">';
    $str_html .= _("Prochain RDV");
    $str_html .= '</div>';

    // On récupère la dernière date de RDV
    $row2 = next_rdv('1', $code, FALSE);
    // Si prochain RDV, on l'affiche
    if ($row2) {
        $row2 = encode_str($row2);
        extract($row2);
        // Date
        $str_html .= datetolocal($rdv_date) . " " . _("à") . " ";
        // Heure
        $str_html .= substr($rdv_heure, 0, 5);
        // On vérifie si planifié
        if ((@$_SESSION["niv_log"] == 3) OR (@$_SESSION["niv_log"] == 4) OR (@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 9)) {
            if (est_planifie_rdv($rdv_id, FALSE) == FALSE)
                $str_html .= ' <img src="../img/warn.png" title ="' . _("Non planifié") . '" border="0" align="top">';
        }
        $str_html .= '<br />';

        // Lieu
        $rech3 = "SELECT lieu_desc FROM `" . TBLIEU . "` WHERE `lieu_code` = '" . $rdv_codelieu . "'";
        $row3 = $db->get_row($rech3, ARRAY_A);
        if ($row3) {
            $row3 = encode_str($row3);
            extract($row3);
        }
        $str_html .= '<div class="annot_petit_it">';
        $str_html .= $lieu_desc;
        $str_html .= '</div>';
    } else {
        $str_html .= '<div class="annot_petit_it">';
        $str_html .= _("Aucun");
        $str_html .= '</div>';
    }
    $str_html .= '</div>';

    if ($open == TRUE)
        $db->disconnect();

    echo 'function updatnextrdv() {';
    echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
    echo $from . "$('#" . $id_html . "').html('" . str_replace("'", "\'", $str_html) . "');";
    echo '}';
    echo '}';
}
