<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.0
 *
 * Copyright (C) 2006-2014  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 interventions */
/* et fichiers rattachés                      */
/**********************************************/

// Indices

/**
 * Vérification du nombre d'indices contrats
 *
 * @param bool $open
 * @return null
 */
function nb_ind($open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBIND . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Lecture d'un enregistrement indice contrat
 *
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_ind($code, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBIND . "` WHERE ind_code = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}


/**
 * Vérifie si un indice est modifiable
 * (Non, si déjà utilisé dans une intervention)
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function ind_modifiable($code, $open = TRUE)
{
    global
    $db;
    $used = FALSE;

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

    // Dans une intervention ?
    $rech2 = "SELECT COUNT(*) FROM `" . TBINTH . "` WHERE inth_codeind = '" . $db->escape($code) . "'";
    $nbres = $db->get_var($rech2);
    if ($nbres > 0)
        $used = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return !$used;
}


// Interventions

/**
 * Lecture d'un enregistrement intervention
 *
 * @param $code
 * @param bool $open
 * @param string $typ
 * @return array|null
 */
function lit_enr_int($code, $open = TRUE, $typ = "")
{
    global
    $db;

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

    $rech2 = "SELECT * FROM `" . TBINT . "` WHERE `int_code` = '" . $db->escape($code) . "'";
    switch ($typ) {
        case "num" :
            $row2 = $db->get_row($rech2, ARRAY_N);
            break;
        default :
            $row2 = $db->get_row($rech2, ARRAY_A);
            break;
    }
    if ($open == TRUE)
        $db->disconnect();
    return $row2;
}

/**
 * Vérification si intervention close ou pas
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function int_closed($code, $open = TRUE)
{
    global
    $db;
    $closed = FALSE;

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

    $rexist2 = "SELECT int_datefin FROM `" . TBINT . "` WHERE `int_code` = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rexist2, ARRAY_A);
    if ($row2) {
        extract($row2);
        if ($int_datefin <> "0000-00-00")
            $closed = TRUE;
    }
    if ($open == TRUE)
        $db->disconnect();

    return $closed;
}

/**
 * Vérification de la présence d'une agence/opérateur/technicien en tant
 * que code de création d'une fiche intervention
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_in_int_codecrea($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBINT . "` WHERE `int_codecrea` = '" . $db->escape($code) . "'";
    $nbres = $db->get_var($rexist);
    if ($nbres > 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Crée une chaîne qui contient la liste des problèmes rattachés à une intervention
 *
 * @param $ci
 * @param bool $open
 * @return string
 */
function cree_str_lstpbm_int($ci, $open = TRUE)
{
    global
    $db;
    $lstpbm = "";

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

    $rech2 = "SELECT rpbm_id FROM `" . TBRPBM . "` WHERE `rpbm_codeint`= '" . $db->escape($ci) . "' ORDER BY `rpbm_datecrea`";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if (($rows2) AND (count($rows2) > 0)) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $lstpbm .= $rpbm_id . "-";
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    if ($lstpbm != "")
        $lstpbm = substr($lstpbm, 0, strlen($lstpbm) - 1);

    return $lstpbm;
}

/**
 * Création du texte avec le détail des problèmes pour popup intervention
 *
 * @param $lstpbm
 * @param bool $open
 *
 * @return string
 */
function cre_str_pbm_int($lstpbm, $open = TRUE)
{
    global
    $db;

    $str_pbm = '';

    if (trim($lstpbm) <> '') {
        $tab_lstpbm = explode("-", $lstpbm);

        $saut = "%%";
        $npbm = 1;

        if (count($tab_lstpbm) > 0) {
            if ($open == TRUE)
                $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

            foreach ($tab_lstpbm as $value) {
                $rech = "SELECT rpbm_id,rpbm_coderlp,rpbm_typrel,rpbm_pbm FROM `" . TBRPBM . "` WHERE `rpbm_id`= '" . intval($value) . "'";
                $row = $db->get_row($rech, ARRAY_A);
                if ($row) {
                    // Si ce n'est pas le premier problème, on rajoute un saut de ligne
                    if ($npbm > 1)
                        $str_pbm .= '%%%%';

                    $row = encode_str($row);
                    extract($row);
                    $rech2 = "";
                    switch ($rpbm_typrel) {
                        // C'est une licence
                        case 1 :
                            $rech2 = "SELECT * FROM `" . TBRLIC . "` WHERE `rlic_code`= '" . $rpbm_coderlp . "'";
                            break;

                        // C'est du matériel
                        case 2 :
                            $rech2 = "SELECT * FROM `" . TBRPDT . "` WHERE `rpdt_code`= '" . $rpbm_coderlp . "'";
                            break;

                        default :
                            break;
                    }
                    if ($rech2 <> "") {
                        $row2 = $db->get_row($rech2, ARRAY_A);
                        if ($row2) {
                            $row2 = encode_str($row2);
                            extract($row2);

                            $str_pbm_titre = "---- " . _("PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                            switch ($rpbm_typrel) {
                                // C'est une licence
                                case 1 :
                                    $rech3 = "SELECT * FROM `" . TBMQUE . "` WHERE `mque_code` = '" . $rlic_codema . "'";
                                    $row3 = $db->get_row($rech3, ARRAY_A);
                                    if ($row3) {
                                        $row3 = encode_str($row3);
                                        extract($row3);
                                    }
                                    $str_pbm_corps1 .= _("Licence") . " : " . $mque_ste . " " . $rlic_modele . " " . _("ver.") . " " . $rlic_version . " (" . _("Relevé") . " " . $rlic_code . ")";
                                    break;

                                // C'est du matériel
                                case 2 :
                                    $rech3 = "SELECT * FROM `" . TBRPCAT . "` WHERE `rpcat_code` = '" . $rpdt_codecat . "'";
                                    $row3 = $db->get_row($rech3, ARRAY_A);
                                    if ($row3) {
                                        $row3 = encode_str($row3);
                                        extract($row3);
                                    }
                                    $rech3 = "SELECT * FROM `" . TBMQUE . "` WHERE `mque_code` = '" . $rpdt_codema . "'";
                                    $row3 = $db->get_row($rech3, ARRAY_A);
                                    if ($row3) {
                                        $row3 = encode_str($row3);
                                        extract($row3);
                                    }
                                    $str_pbm_corps1 = _("Matériel") . " : " . $rpcat_desc;
                                    if (trim($rpdt_ns) <> "")
                                        $str_pbm_corps1 .= " (" . _("NS") . " : " . $rpdt_ns . ")";
                                    $str_pbm_corps1 .= " / " . $mque_ste . " " . $rpdt_modele . " - " . $rpdt_codep . " (" . _("Relevé") . " " . $rpdt_code . ")";
                                    break;

                                default :
                                    break;
                            }
                            $str_pbm_corps2 = _("A faire") . " : ".str_replace(chr(13) . chr(10), $saut, $rpbm_pbm);
                            $str_pbm_pied = "---- " . _("FIN PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";

                            $str_pbm .= $str_pbm_titre . $saut . $str_pbm_corps1 . $saut . $str_pbm_corps2 . $saut . $str_pbm_pied;
                        }
                    }
                    $npbm ++;
                }
            }
            if ($open == TRUE)
                $db->disconnect();
        }
    }

    return $str_pbm;
}

/**
 * Crée un tableau des problèmes traités
 *
 * @param $lstpbm
 * @param bool $open
 * @return array
 */
function cre_tab_pbmfait_int($lstpbm, $open = TRUE)
{
    global
    $db;

    $tab_pbmfait = [];

    if (trim($lstpbm) <> '') {
        $tab_lstpbm = explode("-", $lstpbm);

        if (count($tab_lstpbm) > 0) {
            if ($open == TRUE)
                $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

            foreach ($tab_lstpbm as $value) {
                $rech = "SELECT rpbm_id,rpbm_fait FROM `" . TBRPBM . "` WHERE `rpbm_id`= '" . intval($value) . "'";
                $row = $db->get_row($rech, ARRAY_A);
                if ($row) {
                    // $row = encode_str($row);
                    extract($row);
                    $tab_pbmfait[intval($rpbm_id)] = str_replace(chr(13) . chr(10), "%%", $rpbm_fait);
                }
            }
            if ($open == TRUE)
                $db->disconnect();
        }
    }
    return $tab_pbmfait;
}

/**
 * Crée un texte des problèmes traités à partir d'un tableau
 *
 * @param $tab_pbmfait
 * @param bool $open
 * @return string
 */
function cre_str_pbmfait_int($tab_pbmfait, $open = TRUE)
{
    global
    $db;

    $str_pbm = '';

    if (count($tab_pbmfait) > 0) {
        $saut = "%%";
        $npbm = 1;

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

        foreach ($tab_pbmfait as $key => $value) {
            $rech = "SELECT rpbm_id,rpbm_coderlp,rpbm_typrel FROM `" . TBRPBM . "` WHERE `rpbm_id`= '" . intval($key) . "'";
            $row = $db->get_row($rech, ARRAY_A);
            if ($row) {
                // Si ce n'est pas le premier problème, on rajoute un saut de ligne
                if ($npbm > 1)
                    $str_pbm .= '%%%%';

                $row = encode_str($row);
                extract($row);
                $rech2 = "";
                switch ($rpbm_typrel) {
                    // C'est une licence
                    case 1 :
                        $rech2 = "SELECT * FROM `" . TBRLIC . "` WHERE `rlic_code`= '" . $rpbm_coderlp . "'";
                        break;

                    // C'est du matériel
                    case 2 :
                        $rech2 = "SELECT * FROM `" . TBRPDT . "` WHERE `rpdt_code`= '" . $rpbm_coderlp . "'";
                        break;

                    default :
                        break;
                }
                if ($rech2 <> "") {
                    $row2 = $db->get_row($rech2, ARRAY_A);
                    if ($row2) {
                        $row2 = encode_str($row2);
                        extract($row2);

                        $str_pbm_titre = "---- " . _("PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                        switch ($rpbm_typrel) {
                            // C'est une licence
                            case 1 :
                                $rech3 = "SELECT * FROM `" . TBMQUE . "` WHERE `mque_code` = '" . $rlic_codema . "'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3) {
                                    $row3 = encode_str($row3);
                                    extract($row3);
                                }
                                $str_pbm_corps1 .= _("Licence") . " : " . $mque_ste . " " . $rlic_modele . " " . _("ver.") . " " . $rlic_version . " (" . _("Relevé") . " " . $rlic_code . ")";
                                break;

                            // C'est du matériel
                            case 2 :
                                $rech3 = "SELECT * FROM `" . TBRPCAT . "` WHERE `rpcat_code` = '" . $rpdt_codecat . "'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3) {
                                    $row3 = encode_str($row3);
                                    extract($row3);
                                }
                                $rech3 = "SELECT * FROM `" . TBMQUE . "` WHERE `mque_code` = '" . $rpdt_codema . "'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3) {
                                    $row3 = encode_str($row3);
                                    extract($row3);
                                }
                                $str_pbm_corps1 = _("Matériel") . " : " . $rpcat_desc;
                                if (trim($rpdt_ns) <> "")
                                    $str_pbm_corps1 .= " (" . _("NS") . " : " . $rpdt_ns . ")";
                                $str_pbm_corps1 .= " / " . $mque_ste . " " . $rpdt_modele . " - " . $rpdt_codep . " (" . _("Relevé") . " " . $rpdt_code . ")";
                                break;

                            default :
                                break;
                        }
                        $str_pbm_corps2 = utf8_encode($value);
                        $str_pbm_pied = "---- " . _("FIN PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";

                        // $str_pbm .= $str_pbm_titre . $saut . $str_pbm_corps1 . $saut . $saut . $str_pbm_corps2 . $saut . $str_pbm_pied . $saut;
                        $str_pbm .= $str_pbm_titre . $saut . $str_pbm_corps2 . $saut . $str_pbm_pied;
                    }

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

    return $str_pbm;
}

/**
 * Crée le texte des matériels (intervention) sur la base de la string des problèmes choisis
 *
 * @param $lstpbm
 * @param bool $open
 * @return string
 */
function cree_txt_matos_int($lstpbm, $open = TRUE)
{
    global
    $db;

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

    $txtmatos = "";
    $tab_lstpbm = explode("-", $lstpbm);

    if (count($tab_lstpbm) > 0) {
        for ($i = 0; $i < count($tab_lstpbm); $i++) {
            $rech = "SELECT * FROM `" . TBRPBM . "` WHERE `rpbm_id`= '" . $tab_lstpbm[$i] . "'";
            $row = $db->get_row($rech, ARRAY_A);
            if ($row) {
                $row = encode_str($row);
                extract($row);
                $rech2 = '';
                switch ($rpbm_typrel) {
                    // C'est une licence
                    case 1 :
                        $rech2 = "SELECT * FROM `" . TBRLIC . "` WHERE `rlic_code`= '" . $rpbm_coderlp . "'";
                        break;

                    // C'est du matériel
                    case 2 :
                        $rech2 = "SELECT * FROM `" . TBRPDT . "` WHERE `rpdt_code`= '" . $rpbm_coderlp . "'";
                        break;

                    default :
                        break;
                }
                if ($rech2 <> "") {
                    $txtmatos_titre = "";
                    $txtmatos_corps1 = "";
                    $txtmatos_pied = "";
                    $row2 = $db->get_row($rech2, ARRAY_A);
                    if ($row2) {
                        $row2 = encode_str($row2);
                        extract($row2);

                        switch ($rpbm_typrel) {
                            // C'est une licence
                            case 1 :
                                $txtmatos_titre .= "---- " . _("DETAIL LICENCE CONCERNEE PAR LE PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                                $rech3 = "SELECT * FROM `" . TBMQUE . "` WHERE `mque_code` = '" . $rlic_codema . "'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3) {
                                    $row3 = encode_str($row3);
                                    extract($row3);
                                }
                                $txtmatos_corps1 .= _("Relevé") . " " . $rlic_code . " : " . $mque_ste . " " . $rlic_modele . " " . _("ver.") . " " . $rlic_version;
                                break;

                            // C'est du matériel
                            case 2 :
                                $txtmatos_titre .= "---- " . _("DETAIL MATERIEL CONCERNE PAR LE PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                                $rech3 = "SELECT * FROM `" . TBRPCAT . "` WHERE `rpcat_code` = '" . $rpdt_codecat . "'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3)
                                    extract($row3);
                                $rech3 = "SELECT * FROM `" . TBMQUE . "` WHERE `mque_code` = '" . $rpdt_codema . "'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3)
                                    extract($row3);
                                $txtmatos_corps1 = _("Relevé") . " " . $rpdt_code . " : " . $rpcat_desc;
                                if (trim($rpdt_ns) <> "")
                                    $txtmatos_corps1 .= " (" . _("NS") . " : " . $rpdt_ns . ")";
                                $txtmatos_corps1 .= " / " . $mque_ste . " " . $rpdt_modele . " (" . $rpdt_codep . ")";
                                break;

                            default :
                                break;
                        }

                        switch ($rpbm_typrel) {
                            // C'est une licence
                            case 1 :
                                $txtmatos_pied = "---- " . _("FIN LICENCE CONCERNEE PAR LE PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                                break;

                            // C'est du matériel
                            case 2 :
                                $txtmatos_pied = "---- " . _("FIN MATERIEL CONCERNEE PAR LE PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                                break;

                            default :
                                break;
                        }
                        $txtmatos .= $txtmatos_titre . "%%" . $txtmatos_corps1 . "%%" . $txtmatos_pied . "%%%%";
                    }
                }
            }
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    if ($txtmatos != "")
        $txtmatos = substr($txtmatos, 0, strlen($txtmatos) - 4);
    return $txtmatos;
}

/**
 * Crée le texte des problèmes (intervention) sur la base de la string des problèmes choisis
 *
 * @param $lstpbm
 * @param bool $open
 * @return string
 */
function cree_txt_pbm_int($lstpbm, $open = TRUE)
{
    global
    $db;

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

    $txtpbm = "";
    $tab_lstpbm = explode("-", $lstpbm);

    if (count($tab_lstpbm) > 0) {
        for ($i = 0; $i < count($tab_lstpbm); $i++) {
            $rech = "SELECT * FROM `" . TBRPBM . "` WHERE `rpbm_id`= '" . $tab_lstpbm[$i] . "'";
            $row = $db->get_row($rech, ARRAY_A);
            if ($row) {
                $row = encode_str($row);
                extract($row);
                $rech2 = "";
                switch ($rpbm_typrel) {
                    // C'est une licence
                    case 1 :
                        $rech2 = "SELECT * FROM `" . TBRLIC . "` WHERE `rlic_code`= '" . $rpbm_coderlp . "'";
                        break;

                    // C'est du matériel
                    case 2 :
                        $rech2 = "SELECT * FROM `" . TBRPDT . "` WHERE `rpdt_code`= '" . $rpbm_coderlp . "'";
                        break;

                    default :
                        break;
                }
                if ($rech2 <> "") {
                    $row2 = $db->get_row($rech2, ARRAY_A);
                    if ($row2) {
                        $row2 = encode_str($row2);
                        extract($row2);

                        $txtpbm_titre = "---- " . _("DETAIL PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";
                        $saut = chr(13) . chr(10);
                        $txtpbm_corps1 = str_replace($saut, "%%", $rpbm_pbm);
                        $txtpbm_corps2 = _("Signalé par") . " " . $rpbm_signale . ", " . ("le") . " " . datetolocal($rpbm_datecrea);
                        $txtpbm_pied = "---- " . _("FIN PROBLEME N°") . sprintf("%'010s", $rpbm_id) . " ----";

                        $txtpbm .= $txtpbm_titre . "%%" . $txtpbm_corps1 . "%%" . $txtpbm_corps2 . "%%" . $txtpbm_pied . "%%%%";
                    }
                }
            }
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    if ($txtpbm != "")
        $txtpbm = substr($txtpbm, 0, strlen($txtpbm) - 4);
    return $txtpbm;
}

// Détails Horaires

/**
 * Vérification de la présence d'une intervention dans un historique contrat client
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_int_in_coclh($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBCOCLH . "` WHERE `coclh_codeint` = '" . $db->escape($code) . "'";
    $nbres = $db->get_var($rexist);
    if ($nbres > 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Nombre de détails horaires pour une intervention
 *
 * @param $code
 * @param bool $open
 * @return null
 */
function nb_inth($code, $open = TRUE)
{
    global
    $db;

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

    $rech2 = "SELECT COUNT(*) FROM `" . TBINTH . "` WHERE `inth_codeint` = '" . $db->escape($code) . "'";
    $nbexist = $db->get_var($rech2);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Lecture d'un enregistrement détail horaire intervention
 *
 * @param $id
 * @param bool $open
 * @return array|null
 */
function lit_enr_inth($id, $open = true)
{
    global
    $db;

    if ($id > 0) {
        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        $rech2 = "SELECT * FROM `" . TBINTH . "` WHERE `inth_id` = '$id'";
        $row2 = $db->get_row($rech2, ARRAY_A);
        if ($open == TRUE)
            $db->disconnect();
    }

    return $row2;
}

/**
 * Donne le temps complet (secondes) travaillé sur une intervention
 *
 * @param $codeint
 * @param bool $open
 * @return int
 */
function tps_travaille_int($codeint, $open = TRUE)
{
    global
    $db;
    $tps = 0;

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

    // Récupération total travaillé
    $rech = "SELECT * FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $db->escape($codeint) . "'";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $ind_coeff = 1;
            if ($row["inth_codeind"] <> "-1") {
                $row2 = lit_enr_ind($row["inth_codeind"], FALSE);
                if (is_array($row2))
                    extract($row2);
            }
            $tps = $tps + (diff_time_sec($row["inth_heurea"], $row["inth_heured"]) * $ind_coeff);
        }
    }

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

    return $tps;
}

/**
 * Donne le temps réellement compté (secondes) au client sur une intervention
 *
 * @param $codeint
 * @param bool $open
 * @return int
 */
function tps_retenu_int_sec($codeint, $open = TRUE)
{
    global
    $db;

    $tps = 0;

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

    // Récupération total travaillé
    // $rech = "SELECT inth_codeind, inth_heurea, inth_heured FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $codeint . "' AND `inth_offert`= 0";
    $rech = "SELECT inth_codeind, inth_heurea, inth_heured FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $db->escape($codeint) . "' AND `inth_offert`= 0";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            extract($row);
            $ind_coeff = 1;
            if ($inth_codeind <> "-1") {
                $row2 = lit_enr_ind($inth_codeind, FALSE);
                if (is_array($row2))
                    extract($row2);
            }
            $tps = $tps + (diff_time_sec($inth_heurea, $inth_heured) * $ind_coeff);
        }
    }

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

    return $tps;
}

/**
 * Donne le temps offert (secondes) sur une intervention
 *
 * @param $codeint
 * @param bool $open
 * @return int
 */
function tps_offert_int($codeint, $open = TRUE)
{
    global
    $db;
    $tps = 0;

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

    // Récupération total travaillé
    $rech = "SELECT * FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $db->escape($codeint) . "' AND `inth_offert`= 1";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $ind_coeff = 1;
            if ($row["inth_codeind"] <> "-1") {
                $row2 = lit_enr_ind($row["inth_codeind"], FALSE);
                if (is_array($row2))
                    extract($row2);
            }
            $tps = $tps + (diff_time_sec($row["inth_heurea"], $row["inth_heured"]) * $ind_coeff);
        }
    }

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

    return $tps;
}

/**
 * Calcule le prix de revient d'une intervention
 *
 * @param $codeint
 * @param bool $open
 * @return int
 */
function px_revient_int($codeint, $open = TRUE)
{
    global
    $db;
    $pr = 0;

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

    // Récupération prix de revient pour le travail effectué (inclus offert)
    $rech = "SELECT * FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $db->escape($codeint) . "'";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            extract($row);
            $tps = diff_time_sec($inth_heurea, $inth_heured); // Temps passé sur site
            $cout_aller = 0;
            $tpsa = diff_time_sec($inth_aheured, $inth_aheuref); // Temps pour aller
            $cout_retour = 0;
            $tpsr = diff_time_sec($inth_rheured, $inth_rheuref); // Temps pour retour
            // Calcul du coût de déplacement
            // On récupère le prix de revient du technicien en fonction de la date
            $rech2 = "SELECT tecpr_couth FROM `" . TBTECPR . "` WHERE `tecpr_date` <= '$inth_date' AND `tecpr_codetec` = '" . $inth_codetec . "' ORDER BY tecpr_date DESC";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                extract($row2);
                // ... Aller
                $rech3 = "SELECT * FROM `" . TBMT . "` WHERE `mt_code` = '$inth_acodemt'";
                $row3 = $db->get_row($rech3, ARRAY_A);
                if ($row3) {
                    extract($row3);
                    if ($mt_coutk > 0) // C'est un coût interne
                        $cout_aller = $inth_akm * $mt_coutk; // Montant "kilométrique" aller
                    else // C'est sous-traité
                    {
                        // Coût forfaitaire
                        if ($mt_coutas == 0) // A saisir ?
                            $cout_aller = $mt_coutf; // Oui : Montant forfaitaire pour l'aller
                        else
                            $cout_aller = $inth_acd; // Non : Montant saisi pour l'aller
                        // Coût kilométrique
                        if ($mt_kmill == 0) // Pas illimité : on calcule (sinon on ne fait rien)
                        {
                            $diff_km = $inth_akm - $mt_kmi;
                            if ($diff_km > 0)
                                $cout_aller = $cout_aller + ($mt_kms * $diff_km);
                        }
                    }
                    $cout_aller = $cout_aller + $mt_coutc + $inth_afrais; // Rajout des frais supplémentaires

                    if ($mt_tpsdi == 0) // Le temps de déplacement n'est pas inclus : on calcule (sinon on ne fait rien)
                        $cout_aller = $cout_aller + round((($tecpr_couth / 3600) * $tpsa) * 100) / 100;
                }
                // ...Sur site
                $cout_site = round((($tecpr_couth / 3600) * $tps) * 100) / 100;
                // ... Retour
                $rech3 = "SELECT * FROM `" . TBMT . "` WHERE `mt_code` = '$inth_rcodemt'";
                $row3 = $db->get_row($rech3, ARRAY_A);
                if ($row3) {
                    extract($row3);
                    if ($mt_coutk > 0) // C'est un coût interne
                        $cout_retour = $inth_rkm * $mt_coutk; // Montant "kilométrique" retour
                    else // C'est sous-traité
                    {
                        // Coût forfaitaire
                        if ($mt_coutas == 0) // A saisir ?
                            $cout_retour = $mt_coutf; // Oui : Montant forfaitaire pour le retour
                        else
                            $cout_retour = $inth_rcd; // Non : Montant saisi pour le retour
                        // Coût kilométrique
                        if ($mt_kmill == 0) // Pas illimité : on calcule (sinon on ne fait rien)
                        {
                            $diff_km = $inth_rkm - $mt_kmi;
                            if ($diff_km > 0)
                                $cout_retour = $cout_retour + ($mt_kms * $diff_km);
                        }
                    }
                    $cout_retour = $cout_retour + $mt_coutc + $inth_rfrais; // Rajout des frais supplémentaires

                    if ($mt_tpsdi == 0) // Le temps de déplacement n'est pas inclus : on calcul (sinon on ne fait rien)
                        $cout_retour = $cout_retour + round((($tecpr_couth / 3600) * $tpsr) * 100) / 100;
                }
                $pr = $pr + $cout_site + $cout_aller + $cout_retour;
            }
        }
    }

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

    return $pr;
}

/**
 * Donne la chaîne des techniciens traitants sur une intervention
 * Les clients ne voient pas le détail des agences
 *
 * @param $codeint
 * @param bool $open
 * @return string
 */
function str_tec_traitants_int($codeint, $open = TRUE)
{
    global
    $db,
    $_SESSION;
    $str = "";

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

    $rech = "SELECT DISTINCT inth_codetec FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $db->escape($codeint) . "'";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $row = encode_str($row);
            $rech2 = "SELECT tec_nom, tec_prenom,tec_codeage FROM `" . TBTEC . "` WHERE `tec_code`= '" . $row["inth_codetec"] . "' ORDER BY tec_nom";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                $row2 = encode_str($row2);
                $str .= $row2["tec_nom"] . " " . $row2["tec_prenom"];
                if ($_SESSION["niv_log"] <> 1)
                    $str .= " (" . substr($row2["tec_codeage"], 1, strlen($row2["tec_codeage"])) . ")";
                $str .= ", ";
            }
        }
    }
    if ($str != "")
        $str = substr($str, 0, strlen($str) - 2) . ".";
    if ($open == TRUE)
        $db->disconnect();

    return $str;
}


/**
 * Retourne le détail historique saisi en fonction ID RDV
 * $full = avec prénom et nom (sinon, que code)
 *
 * @param $idrdv
 * @param bool $full
 * @param bool $open
 * @return array|string
 */
function detail_honore_rdv($idrdv, $full = TRUE, $open = TRUE)
{
    global
    $db;
    $detail = "";
    $tab = [];
    $dateact = "";

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

    // On recherche le RDV
    $rech2 = "SELECT inth_date, inth_codetec, inth_heurea, inth_heured FROM `" . TBINTH . "` WHERE inth_idrdv = " . $idrdv;
    $rech2 .= " ORDER BY inth_date, inth_heurea";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if (($rows2) AND (count($rows2) > 0)) {
        foreach ($rows2 as $row2) {
            extract($row2);
            // Rupture par date
            if ($tab == FALSE) {
                if ($inth_date <> $dateact) {
                    if (trim($detail) <> "")
                        $detail .= "<br />";
                    $detail .= "-- " . datetolocal($inth_date);
                }
            }
            $rech3 = "SELECT tec_prenom, tec_nom, tec_codeage FROM `" . TBTEC . "` WHERE `tec_code` = '$inth_codetec'";
            $rech3 .= "ORDER BY tec_nom";
            $row3 = $db->get_row($rech3, ARRAY_A);
            if ($row3) {
                $row3 = encode_str($row3);
                extract($row3);

                $txt_detail = $inth_codetec;
                // En mode mod "full", détail complet, sinon, que code
                if ($full == TRUE)
                    $txt_detail = substr($inth_heurea, 0, 5) . " - " . substr($inth_heured, 0, 5) . " : " . $tec_nom . " " . $tec_prenom . " (" . $tec_codeage . ")";

                // En mode "tab", on crée un tableau, sinon, une string
                if ($tab == TRUE)
                    $tab[$inth_codetec] = $txt_detail;
                else {
                    if (trim($detail) <> "")
                        $detail .= "<br />";
                    $detail .= $txt_detail;
                }
            }
            $dateact = $inth_date;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    if ($tab == TRUE)
        return $tab;
    else
        return $detail;
}

/********************************************************************/
/* Produits & Taxes dans interventions et historiques interventions */
/********************************************************************/

/**
 * Vérification du nombre d'articles dans une fiche intervention
 *
 * @param $code
 * @param bool $open
 * @return null
 */
function nb_art_in_int($code, $open = TRUE)
{
    global
    $db;

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

    $rech = "SELECT COUNT(*) FROM `" . TBPDTI . "` WHERE `pdti_codeint` = '" . $db->escape($code) . "'";
    $nbexist = $db->get_var($rech);
    $rech2 = "SELECT COUNT(*) FROM `" . TBPDTIH . "` WHERE `pdtih_codeint` = '" . $db->escape($code) . "'";
    $nbexist2 = $db->get_var($rech2);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist + $nbexist2;
}

/**
 * Vérification du nombre d'articles dans une fiche historique intervention
 *
 * @param $code
 * @param int $idinth
 * @param bool $open
 * @return null
 */
function nb_art_in_inth($code, $idinth = 0, $open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBPDTIH . "` WHERE `pdtih_codeint` = '" . $db->escape($code) . "'";
    if ($idinth > 0)
        $rexist .= " AND `pdtih_idhisto` = '$idinth'";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Vérification du nombre de taxes dans une fiche intervention
 *
 * @param $code
 * @param bool $open
 * @return null
 */
function nb_tpf_in_int($code, $open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBTPFI . "` WHERE `tpfi_codeint` = '" . $db->escape($code) . "'";
    $nbexist = $db->get_var($rexist);
    $rexist2 = "SELECT * FROM `" . TBTPFIH . "` WHERE `tpfih_codeint` = '" . $db->escape($code) . "'";
    $nbexist2 = $db->get_var($rexist2);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist + $nbexist2;
}

/**
 * Vérification du nombre de taxes dans une fiche historique intervention
 *
 * @param $code
 * @param $idinth
 * @param bool $open
 * @return null
 */
function nb_tpf_in_inth($code, $idinth, $open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBTPFIH . "` WHERE `tpfih_codeint` = '" . $db->escape($code) . "' AND `tpfih_idhisto` = '$idinth'";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Création du code javascript du tableau des produits de l'intervention
 *
 * @param $id_html
 * @param $td
 * @param $code
 * @param int $acpte
 * @param string $from
 * @param bool $open
 */

function cre_html_pdti($id_html, $td, $code, $acpte = 0, $from = '', $open = TRUE)
{
    global
    $db,
    $_SESSION;

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

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

    if ((nb_art_in_int($code, FALSE) > 0) OR (nb_tpf_in_int($code, FALSE) > 0)) {
        // Variables de calcul
        $totalintHT = 0; // Total HT de l'intervention
        $totalintTTC = 0; // Total TTC de l'intervention
        $totalintTVA = 0; // Total TVA de l'intervention
        $totalTTCpdt = 0; // Total TTC des produits (sans les taxes) de l'intervention
        $totalgenHT = 0; // Total général (avec les taxes globales) HT de l'intervention
        $totalgenTTC = 0; // Total général (avec les taxes globales) TTC de l'intervention
        $totalgenTVA = 0; // Total général (avec les taxes globales) TVA de l'intervention

        // Type de facturation
        $factTTC = TRUE;

        $rech = "SELECT int_codecli FROM `" . TBINT . "` WHERE int_code='" . $db->escape($code) . "'";
        $row = $db->get_row($rech, ARRAY_A);

        if ($row) {
            $row = encode_str($row);
            extract($row);
            $rech2 = "SELECT cli_modfact FROM `" . TBCLI . "` WHERE cli_code='" . $int_codecli . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);

            if ($row2) {
                $row2 = encode_str($row2);
                extract($row2);
                if (($cli_modfact == "0") OR ($cli_modfact == "2"))
                    $factTTC = FALSE;
            }
        }

        // *** Affichage de la table
        $str_html = '<table class="Ltable" border="0" width="100%" cellpadding="0" cellspacing="0">';

        // Création entête
        $str_html .= '<th>';
        $str_html .= _("Code");
        $str_html .= '</th>';

        $str_html .= '<th>';
        $str_html .= _("Désignation");
        $str_html .= '</th>';

        $str_html .= "<th>";
        if ($factTTC == TRUE)
            $txt = _("PU TTC");
        else
            $txt = _("PU HT");
        $str_html .= $txt;
        $str_html .= '</th>';

        $str_html .= '<th>';
        $str_html .= _("Qté");
        $str_html .= '</th>';

        $str_html .= '<th>';
        if ($factTTC == TRUE)
            $txt = _("Total TTC");
        else
            $txt = _("Total HT");
        $str_html .= $txt;
        $str_html .= '</th>';

        $str_html .= '<th>';
        $str_html .= _("TVA");
        $str_html .= '</th>';

        if ($td == "edit") {
            $str_html .= '<th>';
            $str_html .= _("Cliquer");
            $str_html .= '</th>';
        }

        // Lignes des articles sur historiques
        $rech = "SELECT * FROM `" . TBPDTIH . "` WHERE pdtih_codeint='" . $db->escape($code) . "' ORDER BY pdtih_codeint,pdtih_id";
        $rows = $db->get_results($rech, ARRAY_A);

        $i = 0;
        $idinth = 0;
        $entete_inth = FALSE;

        if (($rows) AND (count($rows) > 0)) {
            foreach ($rows as $row) {
                $row = encode_str($row);
                extract($row);

                if ($idinth <> $pdtih_idhisto) {
                    // On vérifie d'abord s'il n'y a pas de taxes saisie sur cet historique
                    $rech2 = "SELECT * FROM `" . TBTPFIH . "` WHERE tpfih_codeint='" . $db->escape($code) . "' AND tpfih_idhisto = '" . $pdtih_idhisto . "' ORDER BY tpfih_id";
                    $rows2 = $db->get_results($rech2, ARRAY_A);
                    if (($rows2) AND (count($rows2) > 0)) {
                        foreach ($rows2 as $row2) {
                            $row2 = encode_str($row2);
                            extract($row2);

                            // 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">';

                            // Code taxe
                            $str_html .= '<td class="tdlst" valign="top">';
                            $str_html .= $tpfih_codetpf;
                            $str_html .= '</td>';

                            $rech3 = "SELECT tpf_desc,tpf_typmt,tpf_pour,tpf_basepour FROM `" . TBTPF . "` WHERE tpf_code='" . $db->escape($tpfih_codetpf) . "'";
                            $row3 = $db->get_row($rech3, ARRAY_A);
                            if ($row3) {
                                $row3 = encode_str($row3);
                                extract($row3);
                            }

                            // Désignation
                            $str_html .= '<td class="tdlst" valign="top">';
                            $str_html .= $tpf_desc;

                            // Commentaire en cas de taxe globale par pourcentage
                            if ($tpf_pour == TRUE) {
                                $str_html .= '<div class="annot_moy_it">';
                                $txt = ' ' . _("Sur") . ' ';
                                $txt .= full_num_format($tpfih_valeur, '', '', FALSE, '', FALSE);
                                $txt .= _("% du total des articles");
                                if ($tpf_basepour == TRUE)
                                    $txt .= ' ' . _("avec les taxes.");
                                else
                                    $txt .= ' ' . _("sans les taxes.");
                                $str_html .= $txt;
                                $str_html .= '</div>';
                            }

                            // Affichage ligne(s) du commentaire
                            if (trim($tpfih_texte) <> "") {
                                $ligne_cesure = cesuretxt_tab($tpfih_texte, 100);
                                foreach ($ligne_cesure as $ligne) {
                                    $ligne = str_replace('"', '\"', $ligne);
                                    $str_html .= '<div class="annot_moy_it">';
                                    $str_html .= $ligne;
                                    $str_html .= '</div>';
                                }
                            }
                            $str_html .= "</td>";

                            // Prix
                            // On récupère la TVA de la taxe
                            $rech3 = "SELECT tva_tx FROM `" . TBTVA . "` WHERE tva_code='" . $db->escape($tpfih_codetva) . "'";
                            $row3 = $db->get_row($rech3, ARRAY_A);
                            if ($row3) {
                                $row3 = encode_str($row3);
                                extract($row3);
                            }

                            $txtva = $tva_tx / 100;
                            $puttc = 0;
                            switch ($tpf_pour) {
                                // Calcul normal
                                case "0" :
                                    $puttc = $tpfih_valeur;
                                    break;
                                // Pourcentage du total articles
                                case "1" :
                                    if ($tpf_basepour == TRUE)
                                        $puttc = round($totalintTTC * ($tpfih_valeur / 100), 2);
                                    else
                                        $puttc = round($totalTTCpdt * ($tpfih_valeur / 100), 2);
                                    break;
                            }
                            $puht = round($puttc / (1 + $txtva), 2);

                            if ($factTTC == TRUE)
                                $txt = full_num_format($puttc, '', '', TRUE, '', FALSE);
                            else
                                $txt = full_num_format($puht, '', '', TRUE, '', FALSE);
                            $str_html .= '<td class="tdlst" valign="top" align="right">';
                            $str_html .= $txt;
                            $str_html .= '</td>';

                            // Quantité
                            $str_html .= '<td class="tdlst" valign="top" align="right">';
                            $str_html .= full_num_format($tpfih_qte, '', '', FALSE, '', FALSE);
                            $str_html .= '</td>';


                            // Total ligne
                            if ($factTTC == TRUE) {
                                $totalligneTTC = round($puttc * $tpfih_qte, 2);
                                $totalligneHT = round($totalligneTTC / (1 + $txtva), 2);
                                $totalligneTVA = $totalligneTTC - $totalligneHT;
                                $txt .= full_num_format($totalligneTTC, '', '', TRUE, '', FALSE);
                            } else {
                                $totalligneHT = round($puht * $tpfih_qte, 2);
                                $totalligneTVA = round($totalligneHT * $txtva, 2);
                                $totalligneTTC = $totalligneHT + $totalligneTVA;
                                $txt .= full_num_format($totalligneHT, '', '', TRUE, '', FALSE);
                            }
                            $str_html .= '<td class="tdlst" valign="top" align="right">';
                            $str_html .= $txt;
                            $str_html .= '</td>';

                            // Taux TVA
                            $str_html .= '<td class="tdlst" valign="top" align="center">';
                            $str_html .= full_num_format($tva_tx, '', '', FALSE, '', FALSE) . '%';
                            $str_html .= '</td>';

                            if ($td == "edit") {
                                $str_html .= '<td class="tdlst" valign="top" align="center">';
                                $str_html .= '&nbsp;';
                                $str_html .= '</td>';
                            }

                            $totalintHT = $totalintHT + $totalligneHT;
                            $totalintTTC = $totalintTTC + $totalligneTTC;
                            $totalintTVA = $totalintTVA + $totalligneTVA;

                            $str_html .= '</tr>';

                            $i++;
                        }
                    }

                    // Titre
                    $str_html .= '<tr style="color:white; font-style: italic; font-weight: bold;font-size: 9px; background-color: brown;">';

                    $str_html .= '<td class="tdlst" valign="top"';
                    if ($td == "edit")
                        $str_html .= ' colspan="7"';
                    else
                        $str_html .= ' colspan="6"';
                    $str_html .= '>';

                    // On récupère les éléments pour fabriquer le titre
                    $titre_detail = _("Détail par intervention");
                    $row2 = lit_enr_inth($pdtih_idhisto, FALSE);
                    if (is_array($row2)) {
                        $row2 = encode_str($row2);
                        extract($row2);
                        // récupération lieu
                        $lieu_desc = $inth_codelieu;
                        $rech3 = "SELECT lieu_desc FROM `" . TBLIEU . "` WHERE `lieu_code` = '" . $db->escape($inth_codelieu) . "'";
                        $row3 = $db->get_row($rech3, ARRAY_A);
                        if ($row3) {
                            $row3 = encode_str($row3);
                            extract($row3);
                        }
                        $titre_detail = _("Intervention du") . ' ' . datetolocal($inth_date) . ' ' . _("de") . ' ' . substr($inth_heurea, 0, 5) . ' ' . _("à") . ' ' . substr($inth_heured, 0, 5) . ' (' . $lieu_desc . ')';
                    }
                    $str_html .= $titre_detail;
                    $str_html .= '</td>';
                    $str_html .= '</tr>';

                    $entete_inth = TRUE;
                }

                // 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">';

                // Code produit
                $str_html .= '<td class="tdlst" valign="top">';
                $str_html .= $pdtih_codepdt;
                $str_html .= '</td>';

                if ($pdtih_frompdt <> "") // C'est une taxe rattachée à un produit
                    $rech2 = "SELECT tpf_desc,tpf_typmt FROM `" . TBTPF . "` WHERE tpf_code='" . $db->escape($pdtih_codepdt) . "'";
                else // C'est un produit
                    $rech2 = "SELECT pdt_des,pdt_codepdtu FROM `" . TBPDT . "` WHERE pdt_code='" . $db->escape($pdtih_codepdt) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                // Désignation
                if ($pdtih_frompdt <> "")
                    $txt = $tpf_desc;
                else {
                    $txt = $pdt_des;
                    $desart = $pdt_des;
                }
                $str_html .= '<td class="tdlst" valign="top">';
                $str_html .= $txt;
                // Commentaire en cas de taxe parafiscale
                if ($pdtih_frompdt <> "") {
                    $str_html .= '<div class="annot_moy_it">';
                    $txt = " " . _("Sur") . ' ' . $desart;
                    $str_html .= $txt;
                    $str_html .= '</div>';
                }

                // Affichage ligne(s) du numéro de série
                if (trim($pdtih_ns) <> "") {
                    $ligne_cesure = cesuretxt_tab($pdtih_ns, 100);
                    foreach ($ligne_cesure as $index_ligne => $ligne) {
                        $ligne = str_replace('"', '\"', $ligne);
                        $str_html .= '<div class="annot_moy_it">';
                        if ($index_ligne == 0)
                            $txt = _("N/S") . ' : ';
                        else
                            $txt = '';
                        $str_html .= $txt . $ligne;
                        $str_html .= '</div>';
                    }
                }
                // Affichage ligne(s) du commentaire
                if (trim($pdtih_texte) <> "") {
                    $ligne_cesure = cesuretxt_tab($pdtih_texte, 100);
                    foreach ($ligne_cesure as $ligne) {
                        $str_html .= '<div class="annot_moy_it">';
                        $str_html .= $ligne;
                        $str_html .= '</div>';
                    }
                }
                $str_html .= '</td>';

                // Prix
                // On récupère la TVA du produit
                $rech2 = "SELECT tva_tx FROM `" . TBTVA . "` WHERE tva_code='" . $db->escape($pdtih_codetva) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                $txtva = $tva_tx / 100;

                if ($pdtih_facture == 0)
                    $pdtih_puttc = 0;

                $puht = round($pdtih_puttc / (1 + $txtva), 2);

                if ($factTTC == TRUE)
                    $txt = full_num_format($pdti_puttc, '', '', TRUE, '', FALSE);
                else
                    $txt = full_num_format($puht, '', '', TRUE, '', FALSE);

                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Quantité
                $rech2 = "SELECT pdtu_abr FROM `" . TBPDTU . "` WHERE pdtu_code='" . $db->escape($pdt_codepdtu) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                $txt = $pdtih_qte;
                if ($pdtih_frompdt == "")
                    $txt .= " " . $pdtu_abr;

                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Total ligne
                if ($factTTC == TRUE) {
                    $totalligneTTC = $pdtih_puttc * $pdti_qte;
                    $totalligneHT = round($totalligneTTC / (1 + $txtva), 2);
                    $totalligneTVA = $totalligneTTC - $totalligneHT;
                    $txt = full_num_format($totalligneTTC, '', '', TRUE, '', FALSE);
                } else {
                    $totalligneHT = round($puht * $pdtih_qte, 2);
                    $totalligneTVA = round($totalligneHT * $txtva, 2);
                    $totalligneTTC = $totalligneHT + $totalligneTVA;
                    $txt = full_num_format($totalligneHT, '', '', TRUE, '', FALSE);
                }
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
                $str_html .= $txt;
                $str_html .= "</td>";

                // Taux TVA
                $txt = full_num_format($tva_tx, '', '', FALSE, '', FALSE) . '' % '';
                $str_html .= '<td class="tdlst" valign="top" align="center">';
                $str_html .= $txt;
                $str_html .= '</td>';

                if ($td == "edit") {
                    $str_html .= '<td class="tdlst" valign="top" align="center">';
                    $str_html .= "&nbsp;";
                    $str_html .= '</td>';
                }

                $totalintHT = $totalintHT + $totalligneHT;
                $totalintTTC = $totalintTTC + $totalligneTTC;
                $totalintTVA = $totalintTVA + $totalligneTVA;

                if ($pdti_frompdt == "")
                    $totalTTCpdt = $totalTTCpdt + $totalligneTTC;

                $idinth = $pdtih_idhisto;

                $i++;
            }
        }

        // Lignes des articles
        $rech = "SELECT * FROM `" . TBPDTI . "` WHERE pdti_codeint='" . $db->escape($code) . "' ORDER BY pdti_id";
        $rows = $db->get_results($rech, ARRAY_A);

        $i = 0;

        if (($rows) AND (count($rows) > 0)) {
            // On a déjà affiché des articles sur historique interventions : on crée un séparateur
            if ($entete_inth == TRUE) {
                // Titre
                $str_html .= '<tr style="color:white; font-style: italic; font-weight: bold;font-size: 9px; background-color: brown;">';

                $str_html .= '<td class="tdlst" valign="top"';
                if ($td == "edit")
                    $str_html .= ' colspan="7"';
                else
                    $str_html .= ' colspan="6"';
                $str_html .= '>';

                // On récupère les éléments pour fabriquer le titre
                $titre_detail = _("Articles complémentaires");
                $str_html .= $titre_detail;
                $str_html .= '</td>';
                $str_html .= '</tr>';
            }

            foreach ($rows as $row) {
                $row = encode_str($row);
                extract($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">';

                // Code produit
                $str_html .= '<td class="tdlst" valign="top">';
                $str_html .= $pdti_codepdt;
                $str_html .= '</td>';

                if ($pdti_frompdt <> "") // C'est une taxe rattachée à un produit
                    $rech2 = "SELECT tpf_desc,tpf_typmt FROM `" . TBTPF . "` WHERE tpf_code='" . $db->escape($pdti_codepdt) . "'";
                else // C'est un produit
                    $rech2 = "SELECT pdt_des,pdt_codepdtu FROM `" . TBPDT . "` WHERE pdt_code='" . $db->escape($pdti_codepdt) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                // Désignation
                if ($pdti_frompdt <> "")
                    $txt = $tpf_desc;
                else {
                    $txt = $pdt_des;
                    $desart = $pdt_des;
                }
                $str_html .= '<td class="tdlst" valign="top">';
                $str_html .= $txt;

                // Commentaire en cas de taxe parafiscale
                if ($pdti_frompdt <> "") {
                    $str_html .= '<div class="annot_moy_it">';
                    $txt = ' ' . _("Sur") . ' ' . $desart;
                    $str_html .= $txt;
                    $str_html .= '</div>';
                }

                // Affichage ligne(s) du numéro de série
                if (trim($pdti_ns) <> "") {
                    $ligne_cesure = cesuretxt_tab($pdti_ns, 100);
                    foreach ($ligne_cesure as $index_ligne => $ligne) {
                        $ligne = str_replace('"', '\"', $ligne);
                        $str_html .= '<div class="annot_moy_it">';
                        if ($index_ligne == 0)
                            $txt = _("N/S") . ' : ';
                        else
                            $txt = '';
                        $str_html .= $txt . $ligne;
                        $str_html .= '</div>';
                    }
                }
                // Affichage ligne(s) du commentaire
                if (trim($pdti_texte) <> "") {
                    $ligne_cesure = cesuretxt_tab($pdti_texte, 100);
                    foreach ($ligne_cesure as $ligne) {
                        $str_html .= '<div class="annot_moy_it">';
                        $str_html .= $ligne;
                        $str_html .= '</div>';
                    }
                }
                $str_html .= '</td>';

                // Prix
                // On récupère la TVA du produit
                $rech2 = "SELECT tva_tx FROM `" . TBTVA . "` WHERE tva_code='" . $db->escape($pdti_codetva) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                $txtva = $tva_tx / 100;

                if ($pdti_facture == 0)
                    $pdti_puttc = 0;

                $puht = round($pdti_puttc / (1 + $txtva), 2);

                if ($factTTC == TRUE)
                    $txt = full_num_format($pdti_puttc, '', '', TRUE, '', FALSE);
                else
                    $txt = full_num_format($puht, '', '', TRUE, '', FALSE);

                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Quantité
                $rech2 = "SELECT pdtu_abr FROM `" . TBPDTU . "` WHERE pdtu_code='" . $db->escape($pdt_codepdtu) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                $txt = $pdti_qte;
                if ($pdti_frompdt == "")
                    $txt .= " " . $pdtu_abr;

                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Total ligne
                if ($factTTC == TRUE) {
                    $totalligneTTC = $pdti_puttc * $pdti_qte;
                    $totalligneHT = round($totalligneTTC / (1 + $txtva), 2);
                    $totalligneTVA = $totalligneTTC - $totalligneHT;
                    $txt = full_num_format($totalligneTTC, '', '', TRUE, '', FALSE);
                } else {
                    $totalligneHT = round($puht * $pdti_qte, 2);
                    $totalligneTVA = round($totalligneHT * $txtva, 2);
                    $totalligneTTC = $totalligneHT + $totalligneTVA;
                    $txt = full_num_format($totalligneHT, '', '', TRUE, '', FALSE);
                }
                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Taux TVA
                $txt = $txt = full_num_format($tva_tx, '', '', FALSE, '', FALSE) . '%';
                $str_html .= '<td class="tdlst" valign="top" align="center">';
                $str_html .= $txt;
                $str_html .= '</td>';

                if ($td == "edit") {
                    $str_html .= '<td class="tdlst" valign="top" align="center">';
                    if ($pdti_frompdt == "") {
                        $urleditart = "pdti_maj.php?td=edit&ci=" . $pdti_codeint . "&ca=" . $pdti_codepdt;
                        /*
                        $str_html .= cre_falselnk_img('', 'pdti_edit_'.$pdti_id, 'span', '', _("Edition"), 'lnkpop', $urleditart, '../img/edit.png', 700 , 500, true);
                        */
                        $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('" . $urleditart . "','pdti_edit_" . $pdti_id . "',700,500,'yes')\")>";
                        $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                        $str_html .= ' ';
                        $urldelart = "pdti_maj.php?td=del&ci=" . $pdti_codeint . "&ca=" . $pdti_codepdt;
                        /*
                        $str_html .= cre_falselnk_img('', 'pdti_del_'.$pdti_id, 'span', '', _("Suppression"), 'lnkpop', $urldelart, '../img/del.png', 700 , 500, true);
                        */
                        $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('" . $urldelart . "','pdti_maj_" . $pdti_id . "',700,500,'yes')\")>";
                        $str_html .= '<img src="../img/del.png" border="0" align="absmiddle" title="' . _("Suppression") . '"></a>';
                    } else
                        $str_html .= ' ';
                    $str_html .= '</td>';
                }

                $totalintHT = $totalintHT + $totalligneHT;
                $totalintTTC = $totalintTTC + $totalligneTTC;
                $totalintTVA = $totalintTVA + $totalligneTVA;

                if ($pdti_frompdt == "")
                    $totalTTCpdt = $totalTTCpdt + $totalligneTTC;

                $str_html .= '</tr>';
                $i++;
            }
        }

        $totalgenHT = $totalintHT;
        $totalgenTTC = $totalintTTC;
        $totalgenTVA = $totalintTVA;

        // Lignes des taxes globales
        $rech = "SELECT * FROM `" . TBTPFI . "` WHERE tpfi_codeint='" . $db->escape($code) . "' ORDER BY tpfi_id";
        $rows = $db->get_results($rech, ARRAY_A);

        if (($rows) AND (count($rows) > 0)) {
            foreach ($rows as $row) {
                $row = encode_str($row);
                extract($row);

                // Couleurs alternées
                if ($i % 2 == 0)
                    $str_html .= '<tr onmouseover="this.className=\'TRsel\'" onmouseout="this.className=\'TRalter4\'" class="TRalter4">';
                else
                    $str_html .= '<tr onmouseover="this.className=\'TRsel\'" onmouseout="this.className=\'TRalter5\'" class="TRalter5">';

                // Code taxe
                $str_html .= '<td class="tdlst" valign="top">';
                $str_html .= $tpfi_codetpf;
                $str_html .= '</td>';

                $rech2 = "SELECT tpf_desc,tpf_typmt,tpf_pour,tpf_basepour FROM `" . TBTPF . "` WHERE tpf_code='" . $db->escape($tpfi_codetpf) . "'";
                $row2 = $db->get_row($rech2, ARRAy_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                // Désignation
                $str_html .= '<td class="tdlst" valign="top">';
                $str_html .= $tpf_desc;

                // Commentaire en cas de taxe globale par pourcentage
                if ($tpf_pour == TRUE) {
                    $str_html .= "<div class=\"annot_moy_it\">";
                    $txt = " " . _("Sur") . " " . full_num_format($tpfi_valeur, '', '', FALSE, '', FALSE) . _("% du total des articles");
                    if ($tpf_basepour == TRUE)
                        $txt .= _(" avec les taxes.");
                    else
                        $txt .= _(" sans les taxes.");
                    $str_html .= $txt;
                    $str_html .= '</div>';
                }

                // Affichage ligne(s) du commentaire
                if (trim($tpfi_texte) <> "") {
                    $ligne_cesure = cesuretxt_tab($tpfi_texte, 100);
                    foreach ($ligne_cesure as $ligne) {
                        $ligne = str_replace('"', '\"', $ligne);
                        $str_html .= '<div class="annot_moy_it">';
                        $str_html .= $ligne;
                        $str_html .= '</div>';
                    }
                }
                $str_html .= '</td>';

                // Prix
                // On récupère la TVA de la taxe
                $rech2 = "SELECT tva_tx FROM `" . TBTVA . "` WHERE tva_code='" . $db->escape($tpfi_codetva) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                }

                $txtva = $tva_tx / 100;
                $puttc = 0;
                switch ($tpf_pour) {
                    // Calcul normal
                    case "0" :
                        $puttc = $tpfi_valeur;
                        break;
                    // Pourcentage du total articles
                    case "1" :
                        if ($tpf_basepour == TRUE)
                            $puttc = round($totalintTTC * ($tpfi_valeur / 100), 2);
                        else
                            $puttc = round($totalTTCpdt * ($tpfi_valeur / 100), 2);
                        break;
                }
                $puht = round($puttc / (1 + $txtva), 2);

                if ($factTTC == TRUE)
                    $txt = full_num_format($puttc, '', '', TRUE, '', FALSE);
                else
                    $txt = full_num_format($puht, '', '', TRUE, '', FALSE);
                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Quantité
                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $tpfi_qte;
                $str_html .= '</td>';


                // Total ligne
                if ($factTTC == TRUE) {
                    $totalligneTTC = round($puttc * $tpfi_qte, 2);
                    $totalligneHT = round($totalligneTTC / (1 + $txtva), 2);
                    $totalligneTVA = $totalligneTTC - $totalligneHT;
                    $txt = full_num_format($totalligneTTC, '', '', TRUE, '', FALSE);
                } else {
                    $totalligneHT = round($puht * $tpfi_qte, 2);
                    $totalligneTVA = round($totalligneHT * $txtva, 2);
                    $totalligneTTC = $totalligneHT + $totalligneTVA;
                    $txt = full_num_format($totalligneHT, '', '', TRUE, '', FALSE);
                }
                $str_html .= '<td class="tdlst" valign="top" align="right">';
                $str_html .= $txt;
                $str_html .= '</td>';

                // Taux TVA
                $str_html .= '<td class="tdlst" valign="top" align="center">';
                $str_html .= full_num_format($tva_tx, '', '', FALSE, '', FALSE) . '%';
                $str_html .= '</td>';

                if ($td == "edit") {
                    $str_html .= '<td class="tdlst" valign="top" align="center">';
                    $urledittpf = "tpfi_maj.php?td=edit&ci=" . $tpfi_codeint . "&tpf=" . $tpfi_codetpf;
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('" . $urledittpf . "','tpfi_edit_" . $tpfi_id . "',700,500,'yes')\")>";
                    $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                    $str_html .= ' ';

                    $urldeltpf = "tpfi_maj.php?td=del&ci=" . $tpfi_codeint . "&tpf=" . $tpfi_codetpf;
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('" . $urldeltpf . "','tpfi_del_" . $tpfi_id . "',700,500,'yes')\")>";
                    $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Suppression") . '"></a>';
                    $str_html .= '</td>';
                }

                $totalgenHT = $totalgenHT + $totalligneHT;
                $totalgenTTC = $totalgenTTC + $totalligneTTC;
                $totalgenTVA = $totalgenTVA + $totalligneTVA;

                $str_html .= '</tr>';

                $i++;
            }
        }

        // Pied de liste

        // Total HT
        // Couleurs alternées
        $str_html .= '<tr class="TRalter3">';

        for ($j = 0; $j < 3; $j++) {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= _("Total HT") . ' : ';
        $str_html .= '</td>';

        $txt = full_num_format($totalgenHT, '', '', TRUE, '',FALSE);
        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= $txt;
        $str_html .= '</td>';

        $str_html .= '<td class="tdlst">';
        $str_html .= "&nbsp;";
        $str_html .= '</td>';

        if ($td == "edit") {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '</tr>';
        $i++;

        // Total TVA
        $str_html .= '<tr class="TRalter3">';

        for ($j = 0; $j < 3; $j++) {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= _("TVA") . " :";
        $str_html .= '</td>';

        $txt = full_num_format($totalgenTVA, '', '', TRUE,'',FALSE);
        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= $txt;
        $str_html .= '</td>';

        $str_html .= '<td class="tdlst">';
        $str_html .= "&nbsp;";
        $str_html .= '</td>';

        if ($td == "edit") {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '</tr>';

        // Total TTC
        $str_html .= '<tr class="TRalter3">';

        for ($j = 0; $j < 3; $j++) {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= _("Total TTC") . ' : ';
        $str_html .= '</td>';

        $txt = full_num_format($totalgenTTC, '', '', TRUE,'',FALSE);
        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= $txt;
        $str_html .= '</td>';

        $str_html .= '<td class="tdlst">';
        $str_html .= "&nbsp;";
        $str_html .= '</td>';

        if ($td == "edit") {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= "</tr>";

        // Acompte
        $str_html .= '<tr class="TRalter3">';

        for ($j = 0; $j < 3; $j++) {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= _("Acompte") . ' : ';
        $str_html .= '</td>';

        if ($acpte <> 0)
            $txt = '-' . full_num_format($acpte, '', '', TRUE,'',FALSE);
        else
            $txt = "&nbsp;";
        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= $txt;
        $str_html .= '</td>';

        if ($acpte <> 0)
            $txt = _("TTC");
        else
            $txt = "&nbsp;";
        $str_html .= '<td class="tdlst">';
        $str_html .= $txt;
        $str_html .= '</td>';

        if ($td == "edit") {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '"</tr>';

        // Net à payer
        $str_html .= "<tr class=\"TRalter3\">";
        for ($j = 0; $j < 3; $j++) {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= _("Net à payer") . " :";
        $str_html .= '</td>';

        $txt = full_num_format($totalgenTTC - $acpte, '', '', TRUE,'',FALSE);
        $str_html .= '<td class="tdlst" align="right">';
        $str_html .= $txt;
        $str_html .= '</td>';

        $str_html .= '<td class=\"tdlst\">';
        $str_html .= _("TTC");
        $str_html .= '</td>';

        if ($td == "edit") {
            $str_html .= '<td class="tdlst">';
            $str_html .= "&nbsp;";
            $str_html .= '</td>';
        }

        $str_html .= '</tr>';

        // Fermeture de la table
        $str_html .= '</table>';
    }

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

    echo 'function updatpdti() {';
    echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
    echo $from . "$('#".$id_html."').html('" . str_replace("'", "\'", $str_html) . "');";
    echo '}';
    // MAJ champ du total intervention
    $totalgen = $totalintTTC - $acpte;
    echo $from . '$("#totalint").val(\'' . $totalgen . '\');';
    echo '}';
}

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

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

    if ((count($_SESSION["pdtih"]) > 0) OR (count($_SESSION["tpfih"]) > 0))
    {
        // Variables de calcul
        $totalintHT = 0; // Total HT de l'intervention
        $totalintTTC = 0; // Total TTC de l'intervention
        $totalintTVA = 0; // Total TVA de l'intervention
        $totalTTCpdt = 0; // Total TTC des produits (sans les taxes) de l'intervention
        $totalgenHT = 0; // Total général (avec les taxes globales) HT de l'intervention
        $totalgenTTC = 0; // Total général (avec les taxes globales) TTC de l'intervention
        $totalgenTVA = 0; // Total général (avec les taxes globales) TVA de l'intervention

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

        // Type de facturation
        $factTTC = TRUE;

        $rech = "SELECT int_codecli FROM `" . TBINT . "` WHERE int_code='" . $db->escape($code) . "'";
        $row = $db->get_row($rech, ARRAY_A);
        if ($row) {
            extract($row);
            $rech2 = "SELECT cli_modfact FROM `" . TBCLI . "` WHERE cli_code='" . $int_codecli . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                extract($row2);
                if (($cli_modfact == "0") OR ($cli_modfact == "2"))
                    $factTTC = FALSE;
            }
        }

        // *** Affichage de la table
        $str_html = "<table class=\"Ltable\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";

        // Création entête
        $str_html .= "<th>";
        $str_html .= _("Code");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Désignation");
        $str_html .= "</th>";

        $str_html .= "<th>";
        if ($factTTC == TRUE)
            $txt = _("PU TTC");
        else
            $txt = _("PU HT");
        $str_html .= $txt;
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Qté");
        $str_html .= "</th>";

        $str_html .= "<th>";
        if ($factTTC == TRUE)
            $txt = _("Total TTC");
        else
            $txt = _("Total HT");
        $str_html .= $txt;
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("TVA");
        $str_html .= "</th>";

        if ($td == "edit") {
            $str_html .= "<th>";
            $str_html .= _("Cliquer");
            $str_html .= "</th>";
        }

        // Lignes des articles
        $i = 0;
        foreach ($_SESSION["pdtih"] as $row) {
            extract($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\">";

            // Code produit
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $pdtih_codepdt;
            $str_html .= "</td>";

            if ($pdtih_frompdt <> "") // C'est une taxe rattachée à un produit
                $rech2 = "SELECT tpf_desc,tpf_typmt FROM `" . TBTPF . "` WHERE tpf_code='" . $db->escape($pdtih_codepdt) . "'";
            else // C'est un produit
                $rech2 = "SELECT pdt_des,pdt_codepdtu FROM `" . TBPDT . "` WHERE pdt_code='" . $db->escape($pdtih_codepdt) . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);

            // Désignation
            if ($pdtih_frompdt <> "")
                $txt = $tpf_desc;
            else {
                $txt = $pdt_des;
                $desart = $pdt_des;
            }
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $txt;
            // Commentaire en cas de taxe parafiscale
            if ($pdtih_frompdt <> "") {
                $str_html .= "<div class=\"annot_moy_it\">";
                $txt = ' ' . _("Sur") . ' ' . $desart;
                $str_html .= $txt;
                $str_html .= "</div>";
            }

            // Affichage ligne(s) du numéro de série
            if (trim($pdtih_ns) <> "") {
                $ligne_cesure = cesuretxt_tab($pdtih_ns, 100);
                foreach ($ligne_cesure as $index_ligne => $ligne) {
                    $ligne = str_replace('"', '\"', $ligne);
                    $str_html .= "<div class=\"annot_moy_it\">";
                    if ($index_ligne == 0)
                        $txt = _("N/S")." : ";
                    else
                        $txt = "";
                    $str_html .= $txt . $ligne;
                    $str_html .= "</div>";
                }
            }
            // Affichage ligne(s) du commentaire
            if (trim($pdtih_texte) <> "") {
                $ligne_cesure = cesuretxt_tab($pdtih_texte, 100);
                foreach ($ligne_cesure as $ligne) {
                    $str_html .= "<div class=\"annot_moy_it\">";
                    $str_html .= $ligne;
                    $str_html .= "</div>";
                }
            }
            $str_html .= "</td>";

            // Prix
            // On récupère la TVA du produit
            $tva_tx = 0;
            $rech2 = "SELECT tva_tx FROM `" . TBTVA . "` WHERE tva_code='" . $pdtih_codetva . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);

            $txtva = $tva_tx / 100;

            if (intval($pdtih_facture) == 0)
                $pdtih_puttc = 0;

            $puht = round($pdtih_puttc / (1 + $txtva), 2);

            if ($factTTC == TRUE)
                $txt = full_num_format($pdtih_puttc, '', '', TRUE, '', FALSE);
            else
                $txt = full_num_format($puht, '', '', TRUE, '', FALSE);

            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Quantité
            $rech2 = "SELECT pdtu_abr FROM `" . TBPDTU . "` WHERE pdtu_code='" . $pdt_codepdtu . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);

            $txt = $pdtih_qte;
            if ($pdtih_frompdt == "")
                $txt .= " " . $pdtu_abr;

            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Total ligne
            if ($factTTC == TRUE) {
                $totalligneTTC = $pdtih_puttc * $pdtih_qte;
                $totalligneHT = round($totalligneTTC / (1 + $txtva), 2);
                $totalligneTVA = $totalligneTTC - $totalligneHT;
                $txt = full_num_format($totalligneTTC, '', '', TRUE, '', FALSE);
            } else {
                $totalligneHT = round($puht * $pdtih_qte, 2);
                $totalligneTVA = round($totalligneHT * $txtva, 2);
                $totalligneTTC = $totalligneHT + $totalligneTVA;
                $txt = full_num_format($totalligneHT, '', '', TRUE, '', FALSE);
            }
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Taux TVA
            $txt = full_num_format($tva_tx) . "%";
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            if ($td == "edit") {
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                if ($pdtih_frompdt == "") {
                    $urleditart = "pdtih_maj.php?td=edit&ci=" . $pdtih_codeint . "&cih=" . $idinth . "&ca=" . $pdtih_codepdt;
                    // $str_html .= cre_falselnk_img('', 'pdtih_edit_'.$pdtih_id, 'span', '', _("Edition"), 'lnkpop', $urleditart, '../img/edit.png', 700 , 500, true);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urleditart."','pdtih_edit_".$pdtih_id."',700,500,'yes')\")>";
                    $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                    $str_html .= " ";

                    $urldelart = "pdtih_maj.php?td=del&ci=" . $pdtih_codeint . "&cih=" . $idinth . "&ca=" . $pdtih_codepdt;
                    // $str_html .= cre_falselnk_img('', 'pdtih_del_'.$pdtih_id, 'span', '', _("Suppression"), 'lnkpop', $urldelart, '../img/del.png', 700 , 500, true);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldelart."','pdtih_del_".$pdtih_id."',700,500,'yes')\")>";
                    $str_html .= '<img src="../img/del.png" border="0" align="absmiddle" title="' . _("Suppression") . '"></a>';
                } else
                    $str_html .= " ";
                $str_html .= "</td>";
            }

            $totalintHT = $totalintHT + $totalligneHT;
            $totalintTTC = $totalintTTC + $totalligneTTC;
            $totalintTVA = $totalintTVA + $totalligneTVA;

            if ($pdtih_frompdt == "")
                $totalTTCpdt = $totalTTCpdt + $totalligneTTC;

            $str_html .= "</tr>";
            $i++;
        }

        $totalgenHT = $totalintHT;
        $totalgenTTC = $totalintTTC;
        $totalgenTVA = $totalintTVA;

        // Lignes des taxes globales
        $i = 0;
        foreach ($_SESSION["tpfih"] as $row) {
            extract($row);

            // Couleurs alternées
            if ($i % 2 == 0)
                $str_html .= "<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter4'\" class=\"TRalter4\">";
            else
                $str_html .= "<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter5'\" class=\"TRalter5\">";

            // Code taxe
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $tpfih_codetpf;
            $str_html .= "</td>";

            $rech2 = "SELECT tpf_desc,tpf_typmt,tpf_pour,tpf_basepour FROM `" . TBTPF . "` WHERE tpf_code='" . $tpfih_codetpf . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);

            // Désignation
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $tpf_desc;

            // Commentaire en cas de taxe globale par pourcentage
            if ($tpf_pour == TRUE) {
                $str_html .= "<div class=\"annot_moy_it\">";
                $txt = ' ' . _("Sur") . ' ' . full_num_format($tpfih_valeur) . _("% du total des articles");
                if ($tpf_basepour == TRUE)
                    $txt .= ' ' . _("avec les taxes");
                else
                    $txt .= ' ' . _("sans les taxes");
                $str_html .= $txt;
                $str_html .= "</div>";
            }

            // Affichage ligne(s) du commentaire
            if (trim($tpfih_texte) <> "") {
                $ligne_cesure = cesuretxt_tab($tpfih_texte, 100);
                foreach ($ligne_cesure as $ligne) {
                    $ligne = str_replace('"', '\"', $ligne);
                    $str_html .= "<div class=\"annot_moy_it\">";
                    $str_html .= $ligne;
                    $str_html .= "</div>";
                }
            }
            $str_html .= "</td>";

            // Prix
            // On récupère la TVA de la taxe
            $rech2 = "SELECT tva_tx FROM `" . TBTVA . "` WHERE tva_code='" . $tpfih_codetva . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);

            $txtva = $tva_tx / 100;
            $puttc = 0;
            switch ($tpf_pour) {
                // Calcul normal
                case "0" :
                    $puttc = $tpfih_valeur;
                    break;
                // Pourcentage du total articles
                case "1" :
                    if ($tpf_basepour == TRUE)
                        $puttc = round($totalintTTC * ($tpfih_valeur / 100), 2);
                    else
                        $puttc = round($totalTTCpdt * ($tpfih_valeur / 100), 2);
                    break;
            }
            $puht = round($puttc / (1 + $txtva), 2);

            if ($factTTC == TRUE)
                $txt = full_num_format($puttc, '', '', TRUE, '', FALSE);
            else
                $txt = full_num_format($puht, '', '', TRUE, '', FALSE);
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Quantité
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $tpfih_qte;
            $str_html .= "</td>";


            // Total ligne
            if ($factTTC == TRUE) {
                $totalligneTTC = round($puttc * $tpfih_qte, 2);
                $totalligneHT = round($totalligneTTC / (1 + $txtva), 2);
                $totalligneTVA = $totalligneTTC - $totalligneHT;
                $txt = full_num_format($totalligneTTC, '', '', TRUE, '', FALSE);
            } else {
                $totalligneHT = round($puht * $tpfih_qte, 2);
                $totalligneTVA = round($totalligneHT * $txtva, 2);
                $totalligneTTC = $totalligneHT + $totalligneTVA;
                $txt = full_num_format($totalligneHT, '', '', TRUE, '', FALSE);
            }
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Taux TVA
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            $str_html .= full_num_format($tva_tx) . "%";
            $str_html .= "</td>";

            if ($td == "edit") {
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                $urledittpf = "tpfih_maj.php?td=edit&ci=" . $tpfih_codeint . "&tpf=" . $tpfih_codetpf . "&cih=" . $idinth;
                // $str_html .= cre_falselnk_img('', 'tpfih_edit_'.$tpfih_id, 'span', '', _("Edition"), 'lnkpop', $urledittpf, '../img/edit.png', 700 , 500, true);
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urledittpf."','tpfih_edit_".$tpfih_id."',700,500,'yes')\")>";
                $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                $str_html .= " ";

                $urldeltpf = "tpfih_maj.php?td=del&ci=" . $tpfih_codeint . "&tpf=" . $tpfih_codetpf . "&cih=" . $idinth;
                // $str_html .= cre_falselnk_img('', 'tpfih_edit_'.$tpfih_id, 'span', '', _("Suppression"), 'lnkpop', $urldeltpf, '../img/del.png', 700 , 500, true);
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldeltpf."','tpfih_edit_".$tpfih_id."',700,500,'yes')\")>";
                $str_html .= '<img src="../img/del.png" border="0" align="absmiddle" title="' . _("Suppression") . '"></a>';
                $str_html .= "</td>";
            }

            $totalgenHT = $totalgenHT + $totalligneHT;
            $totalgenTTC = $totalgenTTC + $totalligneTTC;
            $totalgenTVA = $totalgenTVA + $totalligneTVA;

            $str_html .= "</tr>";

            $i++;
        }

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

        // Pied de liste

        // Total HT
        // Couleurs alternées
        $str_html .= "<tr class=\"TRalter3\">";

        for ($j = 0; $j < 3; $j++) {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= ("Total HT")." :";
        $str_html .= "</td>";

        $txt = full_num_format($totalgenHT, '', '', TRUE, '', FALSE);
        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        $str_html .= "<td class=\"tdlst\">";
        $str_html .= "&nbsp;";
        $str_html .= "</td>";

        if ($td == "edit") {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "</tr>";
        $i++;

        // Total TVA
        $str_html .= "<tr class=\"TRalter3\">";

        for ($j = 0; $j < 3; $j++) {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= _("TVA")." :";
        $str_html .= "</td>";

        $txt = full_num_format($totalgenTVA, '', '', TRUE, '', FALSE);
        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        $str_html .= "<td class=\"tdlst\">";
        $str_html .= "&nbsp;";
        $str_html .= "</td>";

        if ($td == "edit") {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "</tr>";

        // Total TTC
        $str_html .= "<tr class=\"TRalter3\">";

        for ($j = 0; $j < 3; $j++) {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= _("Total TTC")." :";
        $str_html .= "</td>";

        $txt = full_num_format($totalgenTTC, '', '', TRUE, '', FALSE);
        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        $str_html .= "<td class=\"tdlst\">";
        $str_html .= "&nbsp;";
        $str_html .= "</td>";

        if ($td == "edit") {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "</tr>";

        // Acompte
        $str_html .= "<tr class=\"TRalter3\">";

        for ($j = 0; $j < 3; $j++) {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= _("Acompte")." :";
        $str_html .= "</td>";

        if ($acpte <> 0)
            $txt = full_num_format($acpte, '', '', TRUE, '', FALSE);
        else
            $txt = "&nbsp;";
        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        if ($acpte <> 0)
            $txt = _("TTC");
        else
            $txt = "&nbsp;";
        $str_html .= "<td class=\"tdlst\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        if ($td == "edit") {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "</tr>";

        // Net à payer
        $str_html .= "<tr class=\"TRalter3\">";
        for ($j = 0; $j < 3; $j++) {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= _("Net à payer")." :";
        $str_html .= "</td>";

        $txt = full_num_format(($totalgenTTC - $acpte), '', '', TRUE, '', FALSE);
        $str_html .= "<td class=\"tdlst\" align=\"right\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        $str_html .= "<td class=\"tdlst\">";
        $str_html .= _("TTC");
        $str_html .= "</td>";

        if ($td == "edit") {
            $str_html .= "<td class=\"tdlst\">";
            $str_html .= "&nbsp;";
            $str_html .= "</td>";
        }

        $str_html .= "</tr>";

        // Fermeture de la table
        $str_html .= "</table>";
    }

    echo 'function updatpdtih() {';
    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 de la liste des déductions sur un contrat dans une intervention
 *
 * @param      $id
 * @param      $codecocl
 * @param      $codeint
 * @param      $codecli
 * @param      $idsite
 * @param      $from
 * @param bool $open
 */
function cre_sel_deduc_cocl_int($id, $codecocl, $codeint, $codecli,$idsite, $from, $open = TRUE)
{
    $tab_deduc = cre_tab_cocl_deduc($codecocl, $codeint, $codecli, $idsite, $open, TRUE);

    echo 'function updatcoded() {';
    echo 'if ((' . $from . '$("#' . $id . '").length) > 0) {';
    echo 'var $lsttded = '.$from.'$("#lsttded").val();';
    echo $from . '$("#' . $id . '").empty();';
    foreach ($tab_deduc as $key => $value) {
        echo $from . '$("#' . $id . '").append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
    }
    echo $from.'$("#' . $id . '").val($lsttded);';
    echo '}';
    echo '}';
}

/**
 * Mise à jour de la liste des demandeurs (client)
 *
 * @param $code : code client
 * @param int $id_site : id site
 * @param array $tab_maitre : pour les regroupements de clients
 * @param string $from : local ou window.opener.
 * @param string $id_sel : id de la liste
 * @param bool $open : on ouvre ou pas la base
 */
function cre_sel_ddeurs_cli($code, $id_site = 0, $tab_maitre = [], $from = '', $id_sel = '', $open = TRUE)
{
    $tab_ddeur = give_tab_ccli($code, $id_site, $tab_maitre, $open);

    echo 'function update_sel_ddeurs() {';
    echo 'var id_sel = ' . $from . '$(\'#' . $id_sel . '\');';
    echo 'var val_act = id_sel.val();';
    echo 'id_sel.empty();';
    echo 'id_sel.append(\'<option value="">' . _("-- Faites votre choix --") . '</option>\');';
    if (count($tab_ddeur) > 0) {
        foreach ($tab_ddeur as $key => $value) {
            echo 'id_sel.append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
        }
    }
    echo 'id_sel.val(val_act);';
    echo '}';
}

/**
 *
 * Mise à jour de la liste des demandeurs (agences)
 *
 * @param string $code
 * @param string $from
 * @param string $id_sel
 * @param bool $open
 */
function cre_sel_ddeurs_age($code = '', $from = '', $id_sel = '', $open = TRUE)
{
    $tab_ddeur = give_tab_cage($code, $open);

    echo 'function update_sel_ddeurs() {';
    echo 'var id_sel = ' . $from . '$(\'#' . $id_sel . '\');';
    echo 'var val_act = id_sel.val();';
    echo 'id_sel.empty();';
    echo 'id_sel.append(\'<option value="">' . _("-- Faites votre choix --") . '</option>\');';
    if (count($tab_ddeur) > 0) {
        foreach ($tab_ddeur as $key => $value) {
            echo 'id_sel.append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
        }
    }
    echo 'id_sel.val(val_act);';
    echo '}';
}


/**
 *
 * Mise à jour de la liste des demandeurs (sous-traitants)
 *
 * @param $code : code sous-traitant
 * @param string $from : local ou window.opener.
 * @param string $id_sel : id de la liste
 * @param bool $open : on ouvre ou pas la base
 */
function cre_sel_ddeurs_st($code, $from = '', $id_sel = '', $open = TRUE)
{
    $tab_ddeur = give_tab_cst($code, $open);

    echo 'function update_sel_ddeurs() {';
    echo 'var id_sel = ' . $from . '$(\'#' . $id_sel . '\');';
    echo 'var val_act = id_sel.val();';
    echo 'id_sel.empty();';
    echo 'id_sel.append(\'<option value="">' . _("-- Faites votre choix --") . '</option>\');';
    if (count($tab_ddeur) > 0) {
        foreach ($tab_ddeur as $key => $value) {
            echo 'id_sel.append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
        }
    }
    echo 'id_sel.val(val_act);';
    echo '}';
}

/**
 *
 * Mise à jour de la liste des agences gestionnaires de site
 *
 * @param $codeint
 * @param $codecli
 * @param int $id_site
 * @param string $from
 * @param string $id_sel
 * @param bool $open
 */
function cre_sel_agesite($codeint, $codecli, $id_site = 0, $from = '', $id_sel = '', $open = TRUE)
{
    $tab_age = give_tab_age_scli($codeint, $codecli, $id_site, $open);

    echo 'function update_sel_codeages() {';
    echo 'var id_sel = ' . $from . '$(\'#' . $id_sel . '\');';
    echo 'var val_act = id_sel.val();';
    echo 'id_sel.empty();';
    echo 'id_sel.append(\'<option value="">' . _("-- Faites votre choix --") . '</option>\');';
    if (count($tab_age) > 0) {
        foreach ($tab_age as $key => $value) {
            echo 'id_sel.append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
        }
    }
    echo 'id_sel.val(val_act);';
    echo '}';
}

/**
 * Mise à jour de la liste des contrats possibles pour intervention
 *
 * @param $td
 * @param $codeint
 * @param $codecli
 * @param int $id_site
 * @param string $from
 * @param string $id_sel
 * @param bool $open
 */
function cre_sel_codecocl($td, $codeint, $codecli, $id_site = 0, $from = '', $id_sel = '', $open = TRUE)
{
    $tab_cocl = cre_tab_cocl_int($td, $codeint, $codecli, $open, $id_site);

    echo 'function update_sel_codecocl() {';
    echo 'var id_sel = ' . $from . '$(\'#' . $id_sel . '\');';
    echo 'var val_act = id_sel.val();';
    echo 'id_sel.empty();';
    echo "id_sel.append('<option value=\"\">" . _("-- Faites votre choix --") . "</option>');";
    if (count($tab_cocl) > 0) {
        foreach ($tab_cocl as $key => $value) {
            echo 'id_sel.append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
        }
    }
    echo 'id_sel.val(val_act);';
    echo '}';
}

/**
 * Mise à jour de la liste des techniciens responsabels pour une intervention
 *
 * @param $codeage
 * @param $codeages
 * @param $codeint
 * @param $codecli
 * @param int $id_site
 * @param string $from
 * @param string $id_sel
 * @param bool $open
 */
function cre_sel_tec($codeage, $codeages, $codeint, $codecli, $id_site = 0, $from = '', $id_sel = '', $open = TRUE)
{
    $tab_age = give_tab_age_scli($codeint, $codecli, $id_site, $open);

    $tab_tec = give_tab_rows_tec($codeage, $codeages, $tab_age);

    $tab_tec_sel = [];

    if (count($tab_tec) > 0) {
        foreach ($tab_tec as $row) {
            $row = encode_str($row);
            extract($row);
            $tab_tec_sel[$tec_code] = $tec_nom . ' (' . $tec_prenom . ' - ' . $tec_codeage . ')';
        }
    }

    echo 'function update_sel_tec() {';
    echo 'var id_sel = ' . $from . '$(\'#' . $id_sel . '\');';
    echo 'var val_act = id_sel.val();';
    echo 'id_sel.empty();';
    echo 'id_sel.append(\'<option value="">' . _("-- Faites votre choix --") . '</option>\');';
    echo 'id_sel.append(\'<option value="-1">' . _("-- Dossier non affecté --") . '</option>\');';
    if (count($tab_tec_sel) > 0) {
        foreach ($tab_tec_sel as $key => $value) {
            echo 'id_sel.append(\'<option value="' . $key . '">' . str_escape($value) . '</option>\');';
        }
    }
    echo 'id_sel.val(val_act);';
    echo '}';
}

/**
 * Mise à jour du texte du nombre de factures d'une intervention
 *
 * @param $id_detail
 * @param $codeint
 * @param string $from
 * @param bool $open
 */
function cre_detail_factint($id_detail, $codeint, $from = '', $open = TRUE)
{
    $nb_intf = nb_intf_int($codeint, $open);

    echo 'function update_detail_factint() {';
    echo 'var id_detail = ' . $from . '$(\'#' . $id_detail . '\');';
    echo 'if (id_detail.length>0) {';
    echo 'id_detail.empty();';
    if ($nb_intf > 0)
        echo 'var txt_detail = \'(' . _("Facturé x") . $nb_intf . ')\';';
    else
        echo 'var txt_detail = \'(' . _("Non facturé") . ')\';';
    echo 'id_detail.html(txt_detail);';
    echo '}';
    echo '}';
}

/************************/
/* Suivi de facturation */
/************************/

/**
 * Lecture d'un enregistrement suivi de facturation intervention
 *
 * @param $codei
 * @param $codef
 * @param bool $open
 * @return array|null
 */
function lit_enr_intf($codei, $codef, $open = TRUE)
{
    global
    $db;

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

    $rech2 = "SELECT * FROM `" . TBINTF . "` WHERE `intf_codeint` = '" . $db->escape($codei) . "' AND `intf_numf` = '" . $db->escape($codef) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification de la présence d'un suivi facturation pour une intervention
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_intf_int($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBINTF . "` WHERE `intf_codeint` = '" . $db->escape($code) . "'";
    $nbres = $db->get_var($rexist);
    if ($nbres > 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Nombre de factures pour une intervention
 *
 * @param $code
 * @param bool $open
 * @return null
 */
function nb_intf_int($code, $open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBINTF . "` WHERE `intf_codeint` = '" . $db->escape($code) . "'";
    $nb = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nb;
}


/**********************************/
/* Techniciens traitants affectés */
/**********************************/

/**
 * Nombre de techniciens affectés pour une intervention
 *
 * @param $code
 * @param bool $open
 * @return null
 */
function nb_tect_int($code, $open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBINTT . "` WHERE `intt_codeint` = '" . $db->escape($code) . "'";
    $nb = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nb;
}

/**
 * Vérifie si technicien affecté à une intervention
 *
 * @param $codetec
 * @param $codeint
 * @param bool $open
 * @return bool
 */
function tect_int_ok($codetec, $codeint, $open = TRUE)
{
    global
    $db;
    $ok = FALSE;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBINTT . "` WHERE `intt_codetec` = '" . $db->escape($codetec) . "' AND `intt_codeint` = '" . $db->escape($codeint) . "'";
    $nbres = $db->get_var($rexist);
    if ($nbres > 0)
        $ok = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $ok;
}

/**
 * Retourne un tableau avec la liste des numéros d'intervention lisibles par un technicien en particulier
 *
 * @param $codetec
 * @param $codeage
 * @param bool $open
 * @return array
 */
function give_tab_int_ok_tec($codetec, $codeage, $open = TRUE)
{
    global
    $db;
    $tab_int = [];

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

    // On génère déjà la liste des interventions affectées au technicien
    // $rech = "SELECT intt_codeint FROM `" .TBINTT. "` WHERE `intt_codetec` = '".$db->escape($codetec)."'";
    $rech = "SELECT intt_codeint FROM `" . TBINTT . "` WHERE `intt_codetec` = '" . $codetec . "'";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $row = encode_str($row);
            extract($row);
            $tab_int[] = $intt_codeint;
        }
    }

    // Ensuite, on récupère la liste des interventions non affectées au technicien mais rendues publiques
    // ou dont ce technicien est responsable
    $rech = "SELECT int_code FROM `" . TBINT . "` WHERE (`int_codeage` = '" . $db->escape($codeage) . "' OR `int_codeages` = '" . $db->escape($codeage) . "') AND (`int_codetec` = '" . $db->escape($codetec) . "' OR `int_publique` = 1)";
    if (count($tab_int) > 0) {
        $rech .= " AND";
        if (count($tab_int) > 1)
            $rech .= " (";
        foreach ($tab_int as $value) {
            $rech .= "`int_code` <> '$value' AND";
        }
        // Suppression du dernier ' AND'
        $rech = substr($rech, 0, strlen($rech) - 4);

        if (count($tab_int) > 1)
            $rech .= ")";
    }
    $rows = $db->get_results($rech, ARRAY_A);

    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $row = encode_str($row);
            extract($row);
            $tab_int[] = $int_code;
        }
    }
    // Enfin, on récupère les interventions qui ont été planifiées pour ce technicien
    $rech = "SELECT pevt_coderat FROM `" . TBPEVT . "` WHERE `pevt_dest` = '" . $db->escape($codetec) . "' AND `pevt_typrat` = 1 AND `pevt_coderat` <> ''";
    if (count($tab_int) > 0) {
        $rech .= " AND";
        if (count($tab_int) > 1)
            $rech .= " (";
        foreach ($tab_int as $value) {
            $rech .= "`pevt_coderat` <> '$value' AND";
        }
        // Suppression du dernier ' AND'
        $rech = substr($rech, 0, strlen($rech) - 4);

        if (count($tab_int) > 1)
            $rech .= ")";
    }
    $rows = $db->get_results($rech, ARRAY_A);

    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $row = encode_str($row);
            extract($row);
            $tab_int[] = $pevt_coderat;
        }
    }

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

    return $tab_int;
}

/**
 * Affecte des techniciens à une intervention
 *
 * @param $td
 * @param $tab_tec
 * @param $codeint
 * @param $codetecr
 * @param bool $open
 */
function affecte_tec_int($td, $tab_tec, $codeint, $codetecr, $open = TRUE)
{
    global
    $db,
    $_SESSION;

    if (is_array($tab_tec)) {
        if (count($tab_tec) > 0) {
            $a_affecter = TRUE;

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

            switch (@$_SESSION["niv_log"]) {
                // Technicien
                case 3 :
                    // Uniquement si technicien responsable connecté
                    if ($codetecr <> @$_SESSION["code_log"])
                        $a_affecter = FALSE;
                    break;
                case 4 :
                case 5 :
                case 9 :
                    break;
                default :
                    $a_affecter = FALSE;
                    break;
            }

            if ($a_affecter == TRUE) {
                if ($td == "edit") {
                    // On supprime ceux qui avaient déjà été affectés
                    $rech2 = "DELETE FROM `" . TBINTT . "` WHERE `intt_codeint` = '" . $db->escape($codeint) . "'";
                    $db->query($rech2);
                }

                // On n'a pas choisi "n'importe quel technicien"
                // => On balaye le tableau des techniciens affectés et on enregistre
                if ($tab_tec[0] <> '-1') {
                    foreach ($tab_tec as $value) {
                        $rech2 = "INSERT INTO `" . TBINTT . "`";
                        $rech2 .= " (intt_codeint,intt_codetec)";
                        $rech2 .= " VALUES";
                        $rech2 .= " ('" . $db->escape($codeint) . "','$value')";
                        $db->query($rech2);
                    }
                }
            }

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


/**
 * Retourne un tableau avec la liste des techniciens affectables sur une intervention
 * actif : uniquement les techniciens actifs
 *
 * @param $codeint
 * @param $actif
 * @param bool $open
 * @return array
 */
function give_tab_rows_tec_toaff_int($codeint, $actif, $open = TRUE)
{
    global
    $db,
    $_SESSION;

    $tab_tec = [];

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

        // On vérifie si l'intervention est publique
        $rech = "SELECT int_codetec, int_codeage, int_codeages, int_publique FROM `" . TBINT . "` WHERE `int_code` = '" . $db->escape($codeint) . "'";
        $row = $db->get_row($rech, ARRAY_A);
        if ($row) {
            extract($row);
            // L'intervention est publique (on prend tous les techniciens)
            if (intval($int_publique) == 1) {
                switch (intval($_SESSION["niv_log"])) {
                    case 3 :
                        // Si c'est le technicien responsable qui est connecté
                        // Il peut travailler sur la liste des techniciens de l'agence ou de l'agence site
                        // sinon, non
                        if ($int_codetec == $_SESSION["code_log"]) {
                            $rech2 = "SELECT tec_code FROM `" . TBTEC . "` WHERE";
                            if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                $rech2 .= "(";
                            $rech2 .= " `tec_codeage` = '$int_codeage'";
                            if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                $rech2 .= " OR `tec_codeage` = '" . $int_codeages . "')";
                        } else
                            $rech2 = "SELECT tec_code FROM `" . TBTEC . "` WHERE `tec_code` = '" . $_SESSION["code_log"] . "'";
                        break;
                    case 4 :
                        // L'agence ne peut travailler que sur ses techniciens
                        $rech2 = "SELECT tec_code FROM `" . TBTEC . "` WHERE `tec_codeage` = '" . $_SESSION["code_age"] . "'";
                        break;
                    default :
                        $rech2 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                        if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                            $rech2 .= "(";
                        $rech2 .= "`tec_codeage` = '" . $int_codeage . "'";
                        if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                            $rech2 .= " OR `tec_codeage` = '" . $int_codeages . "')";
                        break;
                }
                if ($actif == TRUE)
                    $rech2 .= " AND `tec_out` = 0";
                $rows2 = $db->get_results($rech2, ARRAY_A);
                foreach ($rows2 as $row2) {
                    extract($row2);
                    $tab_tec[] = $tec_code;
                }
            } else // L'intervention n'est pas publique
            {
                switch (intval($_SESSION["niv_log"])) {
                    case 3 :
                        // Si c'est le technicien responsable qui est connecté
                        // Il peut travailler sur la liste des techniciens affectés
                        // sinon, non
                        if ($int_codetec == $_SESSION["code_log"]) {
                            // On récupère les techniciens affectés
                            $rech2 = "SELECT intt_codetec FROM `" . TBINTT . "` WHERE `intt_codeint` = '" . $db->escape($codeint) . "'";
                            $rows2 = $db->get_results($rech2, ARRAY_A);
                            if (($rows2) AND (count($rows2) > 0)) // Il y en a : on les récupère
                            {
                                foreach ($rows2 as $row2) {
                                    extract($row2);
                                    // On vérifie que le technicien est actif
                                    if ($actif == TRUE) {
                                        $rech3 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                                        $rech3 .= "`tec_code` = '" . $intt_codetec . "'";
                                        $rech3 .= " AND `tec_out` = 0";
                                        $rows3 = $db->get_results($rech3, ARRAY_A);
                                        if (($rows3) AND (count($rows3) > 0)) {
                                            foreach ($rows3 as $row3) {
                                                extract($row3);
                                                $tab_tec[] = $tec_code;
                                            }
                                        }
                                    } else
                                        $tab_tec[] = $intt_codetec;
                                }
                            } else // Il n'y a pas de technicien affectés : on récupère les techniciens agence et agence site
                                // (On est en mode technicien responsable)
                            {
                                $rech2 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                                if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                    $rech2 .= "(";
                                $rech2 .= "`tec_codeage` = '" . $int_codeage . "'";
                                if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                    $rech2 .= " OR `tec_codeage` = '" . $int_codeages . "')";
                                if ($actif == TRUE)
                                    $rech2 .= " AND `tec_out` = 0";
                                $rows2 = $db->get_results($rech2, ARRAY_A);
                                if (($rows2) AND (count($rows2) > 0)) {
                                    foreach ($rows2 as $row2) {
                                        extract($row2);
                                        $tab_tec[] = $tec_code;
                                    }
                                }
                            }
                        } else // On est en mode technicien non responsable
                            // On ne prend le code connecté que s'il peut accéder à cette intervention
                            // (Contrôle sur l'agence)
                        {
                            $rech2 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                            if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                $rech2 .= "(";
                            $rech2 .= "`tec_codeage` = '" . $int_codeage . "'";
                            if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                $rech2 .= " OR `tec_codeage` = '" . $int_codeages . "')";
                            $rech2 .= " AND `tec_code` =  '" . $_SESSION["code_log"] . "'";
                            if ($actif == TRUE)
                                $rech2 .= " AND `tec_out` = 0";
                            $row2 = $db->get_row($rech2, ARRAY_A);
                            if ($row2) {
                                extract($row2);
                                $tab_tec[] = $tec_code;
                            }
                        }
                        break;
                    case 4 :
                        // On récupère les techniciens affectés appartenant à cette agence
                        $rech2 = "SELECT intt_codetec FROM `" . TBINTT . "` WHERE `intt_codeint` = '" . $db->escape($codeint) . "'";
                        $rows2 = $db->get_results($rech2, ARRAy_A);
                        if (($rows2) AND (count($rows2) > 0)) // Il y en a : on les récupère
                        {
                            foreach ($rows2 as $row2) {
                                extract($row2);
                                $rech3 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                                $rech3 .= "`tec_code` = '" . $intt_codetec . "'";
                                $rech3 .= " AND `tec_codeage` = '" . $_SESSION["code_age"] . "'";
                                if ($actif == TRUE)
                                    $rech3 .= " AND `tec_out` = 0";
                                $rows3 = $db->get_results($rech3, ARRAY_A);
                                if (($rows3) AND (count($rows3) > 0)) {
                                    foreach ($rows3 as $row3) {
                                        extract($row3);
                                        $tab_tec[] = $tec_code;
                                    }
                                }
                            }
                        } else // Il n'y en n'a pas (donc "technicien quelconque") : on prend les techniciens de l'agence
                        {
                            // L'agence ne peut travailler que sur ses techniciens
                            $rech3 = "SELECT tec_code FROM `" . TBTEC . "` WHERE `tec_codeage` = '" . $_SESSION["code_age"] . "'";
                            if ($actif == TRUE)
                                $rech3 .= " AND `tec_out` = 0";
                            $rows3 = $db->get_results($rech3, ARRAY_A);
                            if (($rows3) AND (count($rows3) > 0)) // Il y en a : on les récupère
                            {
                                foreach ($rows3 as $row3) {
                                    extract($row3);
                                    $tab_tec[] = $tec_code;
                                }
                            }
                        }
                        break;
                    default :
                        // On récupère les techniciens affectés
                        $rech2 = "SELECT intt_codetec FROM `" . TBINTT . "` WHERE `intt_codeint` = '" . $db->escape($codeint) . "'";
                        $rows2 = $db->get_results($rech2, ARRAY_A);
                        if (($rows2) AND (count($rows2) > 0)) // Il y en a : on les récupère
                        {
                            foreach ($rows2 as $row2) {
                                extract($row2);
                                // On vérifie que le technicien est actif
                                if ($actif == TRUE) {
                                    $rech3 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                                    $rech3 .= "`tec_code` = '" . $intt_codetec . "'";
                                    $rech3 .= " AND `tec_out` = 0";
                                    $rows3 = $db->get_results($rech3, ARRAY_A);
                                    if (($rows3) AND (count($rows3) > 0)) {
                                        foreach ($rows3 as $row3) {
                                            extract($row3);
                                            $tab_tec[] = $tec_code;
                                        }
                                    }
                                } else
                                    $tab_tec[] = $intt_codetec;
                            }
                        } else // Il n'y en n'a pas (donc "technicien quelconque") : on prend les technicien de l'agence et de l'agence site
                        {
                            $rech3 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                            if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                $rech3 .= "(";
                            $rech3 .= "`tec_codeage` = '" . $int_codeage . "'";
                            if (($int_codeages <> "-1") AND ($int_codeages <> $int_codeage))
                                $rech3 .= " OR `tec_codeage` = '" . $int_codeages . "')";
                            if ($actif == TRUE)
                                $rech3 .= " AND `tec_out` = 0";
                            $rows3 = $db->get_results($rech3, ARRAY_A);
                            if (($rows3) AND (count($rows3) > 0)) {
                                foreach ($rows3 as $row3) {
                                    extract($row3);
                                    $tab_tec[] = $tec_code;
                                }
                            }
                        }
                        break;
                }
            }
        }

        // on construit la liste des résultats
        $rows2 = [];
        if (count($tab_tec) > 0) {
            $rech = "SELECT * FROM `" . TBTEC . "`";
            $rech .= " WHERE (";
            foreach ($tab_tec as $value) {
                $rech .= "`tec_code` = '" . $value . "' OR";
            }
            // Suppression du dernier 'OR'
            $rech = substr($rech, 0, strlen($rech) - 3);
            $rech .= ")";
            $rows2 = $db->get_results($rech, ARRAY_A);
        }

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

    return $rows2;
}


/**
 * Retourne un tableau avec la liste des techniciens affectés à une intervention
 * actif : uniquement les techniciens actifs
 *
 * @param $codeint
 * @param $actif
 * @param bool $open
 * @return array
 */
function give_tab_rows_tec_aff_int($codeint, $actif, $open = TRUE)
{
    global
    $db,
    $_SESSION;

    $tab_tec = [];

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

        $rech2 = "SELECT intt_codetec FROM `" . TBINTT . "` WHERE `intt_codeint` = '" . $db->escape($codeint) . "'";
        $rows2 = $db->get_results($rech2, ARRAY_A);
        if (($rows2) AND (count($rows2) > 0)) {
            foreach ($rows2 as $row2) {
                extract($row2);
                // On vérifie que le technicien est actif
                if ($actif == TRUE) {
                    $rech3 = "SELECT tec_code FROM `" . TBTEC . "` WHERE ";
                    $rech3 .= "`tec_code` = '" . $intt_codetec . "'";
                    $rech3 .= " AND `tec_out` = 0";
                    $rows3 = $db->get_results($rech3, ARRAY_A);

                    if (($rows3) AND (count($rows3) > 0)) {
                        foreach ($rows3 as $row3) {
                            extract($row3);
                            $tab_tec[] = $tec_code;
                        }
                    }
                } else
                    $tab_tec[] = $intt_codetec;
            }
        }
        if ($open == TRUE)
            $db->disconnect();
    }
    return $tab_tec;
}

/**
 * Vérifie si un technicien est affecté à une intervention sur le planning
 *
 * @param $codetec
 * @param $codeint
 * @param $idrdv
 * @param bool $open
 * @return bool
 */
function tec_affecte_int_plan($codetec, $codeint, $idrdv, $open = TRUE)
{
    global
    $db;
    $affecte = TRUE;

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

    $rech2 = "SELECT COUNT(*) FROM `" . TBPEVT . "` WHERE pevt_coderat = '" . $db->escape($codeint) . "' AND pevt_idrdv='$idrdv' AND pevt_dest = '" . $db->escape($codetec) . "'";
    $nbres = $db->get_var($rech2);
    if ($nbres == 0)
        $affecte = FALSE;
    if ($open == TRUE)
        $db->disconnect();

    return $affecte;
}


/****************************/
/* Catégories Interventions */
/****************************/

/**
 * Lecture d'un enregistrement catégorie intervention
 *
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_intcat($code, $open = TRUE)
{
    global
    $db;

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

    $rech2 = "SELECT * FROM `" . TBINTC . "` WHERE `intc_code` = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/*****************************/
/* Historiques interventions */
/*****************************/


/**
 * Création du texte des interventions à partir de l'historique interventions
 * retours : si oui, on les nettoie
 *
 * @param $code
 * @param $retours
 * @param $html
 * @param bool $open
 * @param bool $inc_cl
 * @return string
 */
function cree_txt_fait_int($code, $retours, $html, $open = TRUE, $inc_cl = TRUE)
{
    global
    $db,
    $non_oui3;

    $txt_fait = '';

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

    // Récupération code catégorie
    $rech = "SELECT int_codecat FROM `" . TBINT . "` WHERE `int_code` = '" . $db->escape($code) . "'";
    $row = $db->get_row($rech, ARRAY_A);
    if ($row) {
        $row = encode_str($row);
        extract($row);

        /** Tableau des groupements de Check-Lists **/
        $tab_clcgintc = give_tab_clcg_full_intc($int_codecat, FALSE);

        $rech2 = "SELECT * FROM `" . TBINTH . "` WHERE `inth_codeint` = '" . $db->escape($code) . "'";
        $rech2 .= " ORDER BY `inth_date`";
        $rows2 = $db->get_results($rech2, ARRAY_A);
        if (($rows2) AND (count($rows2) > 0)) {
            foreach ($rows2 as $row2) {
                $row2 = encode_str($row2);
                extract($row2);
                if (trim($txt_fait) <> '') {
                    if ($retours == TRUE)
                        $txt_fait .= '<br />';
                    else
                        $txt_fait .= chr(13) . chr(10);
                }

                /**  Entête **/
                if ($html == TRUE)
                    $txt_fait .= '<span class="annot_gras_it">';
                else
                    $txt_fait .= '>>> ';
                $txt_fait .= datetolocal($inth_date) . ', ' . _("de") . ' ' . substr($inth_heurea, 0, 5) . ' ' . _("à") . ' ' . substr($inth_heured, 0, 5);

                // récupération lieu
                $lieu_desc = '';
                $rech3 = "SELECT lieu_desc FROM `" . TBLIEU . "` WHERE `lieu_code` = '$inth_codelieu'";
                $row3 = $db->get_row($rech3, ARRAY_A);
                if ($row3) {
                    $row3 = encode_str($row3);
                    extract($row3);
                }
                if (trim($lieu_desc) <> '')
                    $txt_fait .= ' (' . $lieu_desc . ')';
                else
                    $txt_fait .= ' (' . $inth_codelieu . ')';

                if ($html == TRUE)
                    $txt_fait .= '</span>';
                else
                    $txt_fait .= ' <<<';

                /*
                if ($retours == TRUE)
                    $txt_fait .= '<br />';
                else
                    $txt_fait .= chr(13) . chr(10);

                // Texte des problèmes traités
				$rech3 = "SELECT * FROM `" .TBRPBM. "` WHERE `rpbm_idinth`= ".$inth_id;
				$rech3.= " AND `rpbm_fait` IS NOT NULL";
				$rows3 = $db->get_results($rech3,ARRAY_A);
				if (($rows3) AND (count($rows3)>0))
				{
					foreach ($rows3 as $row3)
					{
                        $row3 = encode_str($row3);
						extract ($row3);
						if (trim($txt_fait)<>'')
						{
							if ($retours==TRUE)
								$txt_fait.= '<br />';
							else
								$txt_fait.=chr(13).chr(10);
						}
						$txt_fait.="*** "._("Travail effectué sur problème n°").sprintf("%'010s",$rpbm_id);
						if ($retours==TRUE)
						{
							$txt_fait.='<br />';
							$txt_fait.= formatetxtbr($rpbm_fait);
							$txt_fait.='<br />';
						}
						else
						{
							$txt_fait.=chr(13).chr(10);
							$txt_fait.= $rpbm_fait;
							$txt_fait.=chr(13).chr(10);
						}
						$txt_fait.= "----";
						if ($retours==TRUE)
							$txt_fait.='<br />';
						else
							$txt_fait.=chr(13).chr(10);
					}
				}
				*/

                /** Texte complémentaire **/
                if ($retours == TRUE) {
                    $txt_fait .= '<br />';
                    $txt_fait .= formatetxtbr($inth_fait);
                } else {
                    $txt_fait .= chr(13) . chr(10);
                    $txt_fait .= $inth_fait;
                }

                if ($retours == TRUE)
                    $txt_fait .= '<br />';
                else
                    $txt_fait .= chr(13) . chr(10);

                /** Check-Lists **/
                if ($inc_cl == TRUE) {
                    if (count($tab_clcgintc) > 0) {
                        // On vérifie d'abord si des check-list ont été saisies dans l'historique intervention
                        $rech3 = "SELECT COUNT(clcginth_id) FROM `" . TBCLCGINTH . "` WHERE clcginth_idinth = '$inth_id'";
                        $nbres = $db->get_var($rech3);
                        if ($nbres > 0) {
                            if (trim($txt_fait) <> '') {
                                if ($retours == TRUE)
                                    $txt_fait .= '<br />';
                                else
                                    $txt_fait .= chr(13) . chr(10);
                            }
                            $txt_fait .= "*** " . _("Points de contrôle");
                            if ($retours == TRUE)
                                $txt_fait .= '<br />';
                            else
                                $txt_fait .= chr(13) . chr(10);

                            $code_clcg_courant = '';
                            $nclcg = 1;

                            foreach ($tab_clcgintc as $key => $value) {
                                $code_clcg = $key;

                                if ($code_clcg <> $code_clcg_courant) {
                                    $row4 = lit_enr_clcg($code_clcg, FALSE);
                                    if (is_array($row4)) {
                                        $row4 = encode_str($row4);
                                        extract($row4);
                                        if ($nclg > 1)
                                        {
                                            if ($retours == TRUE)
                                                $txt_fait .= '<br />';
                                            else
                                                $txt_fait .= chr(13) . chr(10);
                                        }
                                        $txt_fait .= "--- " . $clcg_desc . " ---";
                                        if ($retours == TRUE)
                                            $txt_fait .= '<br />';
                                        else
                                            $txt_fait .= chr(13) . chr(10);
                                        $nclcg++;
                                    }
                                }
                                $code_clcg_courant = $code_clcg;

                                $tab_tmp = $value;
                                foreach ($tab_tmp as $key2 => $value2) {
                                    $row5 = lit_enr_clc($key2, FALSE);
                                    if (is_array($row5)) {
                                        $row5 = encode_str($row5);
                                        extract($row5);
                                        $txt_fait .= formatetxtbr($clc_desc);
                                    }

                                    $rech6 = "SELECT clcginth_choix FROM `" . TBCLCGINTH . "` WHERE clcginth_codeclcg = '$code_clcg_courant' AND clcginth_codeclc = '$key2' AND clcginth_idinth = '$inth_id'";
                                    $row6 = $db->get_row($rech6, ARRAY_A);
                                    if ($row6) {
                                        $row6 = encode_str($row6);
                                        extract($row6);
                                        $txt_fait .= ' : ' . $non_oui3[intval($clcginth_choix)];

                                        if ($retours == TRUE)
                                            $txt_fait .= '<br />';
                                        else
                                            $txt_fait .= chr(13) . chr(10);
                                    }

                                }
                                unset($tab_tmp);
                            }
                        }
                    }
                }
                /*
                if ($retours == TRUE)
                    $txt_fait .= '<br />';
                else
                    $txt_fait .= chr(13) . chr(10);
                */
            }
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $txt_fait;
}

// Check-List

/**
 * Vérification du nombre de champs check-list
 *
 * @param bool $open
 * @return null
 */
function nb_clc($open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBCLC . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Lecture d'un enregistrement champs check-list
 *
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_clc($code, $open = TRUE)
{
    global
    $db;

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

    $rech2 = "SELECT * FROM `" . TBCLC . "` WHERE clc_code = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Retourne un tableau avec la liste des groupements champs checks list affectés à une catégorie
 *
 * @param $codeintc
 * @param bool $open
 * @return array
 */
function give_tab_clcg_intc($codeintc, $open = TRUE)
{
    global
    $db;
    $tab_clcg = [];

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

    $rech2 = "SELECT clcgintc_codeclcg FROM `" . TBCLCGINTC . "` WHERE clcgintc_codeintc = '" . $db->escape($codeintc) . "'";
    $rech2 .= " ORDER BY clcgintc_codeclcg";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $tab_clcg[] = $clcgintc_codeclcg;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $tab_clcg;
}

/**
 * Retourne un tableau avec la liste des groupements champs checks list affectés à une catégorie
 * La liste est complète (libellé + code 3 chiffres donnant les champs à afficher dans le select) et dans un tableau avec les codes groupements
 *
 * @param $codeintc
 * @param bool $open
 * @return array
 */
function give_tab_clcg_full_intc($codeintc, $open = TRUE)
{
    global
    $db;
    $tab_clcg = give_tab_clcg_intc($codeintc, $open);
    $tab_clcg_full = [];
    $tab_tmp = [];

    if (count($tab_clcg) > 0) {
        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        foreach ($tab_clcg as $value) {
            // On récupère les champs check-list rattachés à ce groupement
            $rech2 = "SELECT clcclcg_codeclc FROM `" . TBCLCCLCG . "` WHERE clcclcg_codeclcg = '$value'";
            $rech2 .= " ORDER BY clcclcg_codeclc";
            $rows2 = $db->get_results($rech2, ARRAY_A);
            if (($rows2) AND (count($rows2) > 0)) {
                foreach ($rows2 as $row2) {
                    $row2 = encode_str($row2);
                    extract($row2);
                    $rech3 = "SELECT * FROM `" . TBCLC . "` WHERE clc_code = '$clcclcg_codeclc'";
                    $rows3 = $db->get_results($rech3, ARRAY_A);
                    if (($rows3) AND (count($rows3) > 0)) {
                        foreach ($rows3 as $row3) {
                            $row3 = encode_str($row3);
                            extract($row3);
                            $str_select = "$clc_so" . "$clc_oui" . "$clc_non";
                            $tab_tmp[$clc_code] = $clc_desc . "%%" . $str_select;
                        }
                    }
                }
                $tab_clcg_full[$value] = $tab_tmp;
                unset($tab_tmp);
            }
        }
        if ($open == TRUE)
            $db->disconnect();
    }

    return $tab_clcg_full;
}

// Groupements Check-List

/**
 * Vérification du nombre de champs check-list
 *
 * @param bool $open
 * @return null
 */
function nb_clcg($open = TRUE)
{
    global
    $db;

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

    $rexist = "SELECT COUNT(*) FROM `" . TBCLCG . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Lecture d'un enregistrement groupement champs check-list
 *
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_clcg($code, $open = TRUE)
{
    global
    $db;

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

    $rech2 = "SELECT * FROM `" . TBCLCG . "` WHERE clcg_code = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Retourne un tableau avec la liste des champs checks list affectés à un groupement
 *
 * @param $codeclcg
 * @param bool $open
 * @return array
 */
function give_tab_clc_clcg($codeclcg, $open = TRUE)
{
    global
    $db;
    $tab_clc = [];

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

    $rech2 = "SELECT clcclcg_codeclc FROM `" . TBCLCCLCG . "` WHERE clcclcg_codeclcg = '" . $db->escape($codeclcg) . "'";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if (($rows2) AND (count($rows2) > 0)) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $tab_clc[] = $clcclcg_codeclc;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $tab_clc;
}

/**
 * Lecture d'un enregistrement groupement champs check-list et d'un code champ check-list dans un historique intervention
 *
 * @param $codeclcg
 * @param $codeclc
 * @param $idinth
 * @param bool $open
 * @return array|null
 */
function lit_enr_clc_clcg_inth($codeclcg, $codeclc, $idinth, $open = TRUE)
{
    global
    $db;

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

    $rech2 = "SELECT * FROM `" . TBCLCGINTH . "` WHERE clcginth_codeclcg = '" . $db->escape($codeclcg) . "' AND clcginth_codeclc = '" . $db->escape($codeclc) . "' AND clcginth_idinth = '$idinth'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}
?>