<?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");

include_once("../inc/config.inc.php");
include_once("../inc/func.inc.php");
include_once("../inc/func_date.inc.php");
include_once("../inc/func_log.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_time.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../inc/lst.inc.php");
include_once("../inc/fic_age.inc.php");
include_once("../inc/fic_cli.inc.php");
include_once("../inc/fic_cocl.inc.php");
include_once("../inc/fic_droits.inc.php");
include_once("../inc/fic_hum.inc.php");
include_once("../inc/fic_int.inc.php");
include_once("../inc/fic_rel.inc.php");
include_once("../inc/fic_tec.inc.php");
include_once("../inc/fic_zc.inc.php");
include_once("../classes/ezSQL/shared/ez_sql_core.php");
include_once("../classes/ezSQL/mysqli/ez_sql_mysqli.php");
include_once("../inc/func_sql.inc.php");
Archivelog(@$_SESSION["code_log"]);
$_SESSION["typ_filtres"] = "sitesi";

// Variables Formulaire
fix_magic_quotes();
$_POST = clean_str($_POST);
$_GET = clean_str($_GET);

$pbm_site = FALSE;
$pbm_cli = FALSE;
$pbm_int = FALSE;
$pbm_cocl = FALSE;
$sitep = FALSE;
$form_ok = FALSE; // Formulaire validé ?
$lstsites = "";

$action_to_do = '';
if ((trim(@$_POST["nbutton"]) == 'enr1') OR (trim(@$_POST["nbutton"]) == 'enr2')) // On a cliqué sur valider
    $action_to_do = 'valid';

if ($action_to_do <> 'valid') // On a pas validé
{
    $cc = $_GET['cc']; // Récupération code Client
    $ci = $_GET['ci']; // Récupération code Intervention
    $co = $_GET['co']; // Récupération code Contrat
    $td = $_GET['td']; // Récupération type demande
    $dte = datetomysql($_GET['dte']); // Récupération date de Contrôle
    $si = intval($_GET['si']); // Récupération site Intervention
    $ca = $_GET['ca']; // Récupération code agence gestionnaire
    $cas = $_GET['cas']; // Récupération code agence site
    $tr = $_GET['tr']; // Récupération code technicien responsable

    if (($td <> "edit") AND ($td <> "view") AND ($td <> "add"))
        $pbm_int = TRUE;

    // On Contrôle le code site
    /*
	if (($si==NULL) OR ($si<0))
		$si=0;
    */
    $sitep = ($si == 0);

    if ($si > 0) {
        $row = lit_enr_scli_id($si, TRUE);
        if (!is_array($row))
            $pbm_site = TRUE;
    }

    if ($cc <> "") {
        // Contrôle qu'un client n'essaye pas de "hacker" un contrat
        if ((@$_SESSION["niv_log"] == 1) AND ($cc <> @$_SESSION["code_log"]))
            $pbm_cli = TRUE;

        $row = lit_enr_cli($cc, TRUE);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);

            // Contrôle qu'une agence n'essaye pas de "hacker" un contrat
            switch (@$_SESSION["niv_log"]) {
                case 3 :
                case 4 :
                    if (client_age_ok($cli_code, @$_SESSION["code_age"], TRUE) == FALSE)
                        $detail_ok = TRUE;
                    break;
                default :
                    break;
            }
        } else
            $pbm_cli = TRUE;
    } else
        $pbm_cli = TRUE;

    if ($ci <> "") {
        // Récupération des informations intervention client
        $row = lit_enr_int($ci);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);

            // Si intervention terminée, force le mode "view"
            if (datetolocal($int_datefin) <> "")
                $td = "view";

            if ($td <> "add") {
                // Contrôle qu'un client n'essaye pas de "hacker" une intervention
                if ((@$_SESSION["niv_log"] == 1) AND ($int_codecli <> @$_SESSION["code_log"]))
                    $pbm_int = TRUE;
                // Contrôle qu'une agence n'essaye pas de "hacker" une intervention
                if (($int_codeage <> @$_SESSION["code_age"]) AND ($int_codeages <> @$_SESSION["code_age"])) {
                    // Intervention non gérée ?
                    if (trim($int_codeage) == "") {
                        // On vérifie si client couvert par l'agence
                        if (dep_in_zcc_age_open($cli_dep, $cli_codepays, @$_SESSION["code_age"], TRUE) == FALSE)
                            $pbm_int = TRUE;
                        else {
                            // On affecte l'intervention à cette agence
                            $int_codeage = @$_SESSION["code_age"];
                            // On affecte le client à cette agence
                            $cli_prop = @$_SESSION["code_age"];
                        }
                    }
                }
            }
        } else {
            if ($td <> "add")
                $pbm_int = TRUE;
        }
    } else {
        if ($td <> "add")
            $pbm_int = TRUE;
    }

    if ($co <> "") {
        // Récupération des informations contrat client
        $row = lit_enr_cocl($co);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);

            // Construction de la chaîne des sites autorisés, inclues les annexes
            $lstsites = cree_str_lstsites_cocl($co);

            // Site principal inclus ?
            $sitep = sitep_in_cocl_except($co, '', TRUE);

            // Si contrat terminé, force le mode "view"
            if (datetolocal($cocl_datefin) <> "")
                $td = "view";

            if ($td <> "add") {
                // Contrôle qu'un client n'essaye pas de "hacker" un contrat
                if ((@$_SESSION["niv_log"] == 1) AND ($cocl_codecli <> @$_SESSION["code_log"]))
                    $pbm_cocl = TRUE;
                // Contrôle qu'une agence n'essaye pas de "hacker" un contrat
                if (((@$_SESSION["niv_log"] == 4) OR (@$_SESSION["niv_log"] == 3)) AND ($cocl_codeage <> @$_SESSION["code_age"]))
                    $pbm_cocl = TRUE;
            }
        } else {
            if ($td <> "add")
                $pbm_cocl = TRUE;
        }
    }

    /*
    echo "pbm : ".$pbm_int."<br>";
    if (($tr <> "") AND ($tr <> '-1')) {
        $row = lit_enr_tec($tr, TRUE);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);
        } else
            $pbm_int = TRUE;
    } else {
        if ($_SESSION["niv_log"] <> 2)
            $pbm_int = TRUE;
    }
    */
} else {
    $form_ok = TRUE;
    $td = $_POST['td']; // Récupération type demande
    $cc = $_POST['cc']; // Récupération code Client
    $ci = $_POST['ci']; // Récupération code Intervention
    $si = intval($_POST['si']); // Récupération site Intervention
    $ca = $_POST['ca']; // Récupération code Agence
    $cas = $_POST['cas']; // Récupération code agence site
}
// Création du tableau des sites possibles pour le contrat (si contrat)
$tab_sites = explode("-", $lstsites);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>SMI - <?PHP echo _("ESPACE PRIVE"); ?> : <?PHP echo _("Sites intervention"); ?></title>

    <?PHP include_once("../inc/header.inc.php"); ?>
    <script language="javascript">
        <!--
        var tab_champ = new Array(
            "nom:scli_choisi ; format:radio ; req:Y ; txt:<?PHP echo _("Site d'intervention"); ?> ; stok:saisieok ; stbad:saisiepasok");
        //-->
    </script>

    <script type="text/javascript">
        <!--
        <?PHP
        if ($form_ok == TRUE)
        {
            if ($_SESSION["niv_log"]<> 2)
            {
                cre_sel_agesite($ci,$cc, intval($_POST["scli_choisi"]), 'window.opener.', 'agesite');
                echo "\n";
                cre_sel_tec($ca,$cas,$ci,$cc, intval($_POST["scli_choisi"]), 'window.opener.', 'codetec');
                echo "\n";
                $display="none";
                if (exist_rpbm_actif_site($td,$cc,$ci,intval($_POST["scli_choisi"])) == TRUE)
                    $display="block";
            }
            $tab_maitre = give_tab_maitre_cli($cc,TRUE);
            cre_sel_ddeurs_cli($cc, intval($_POST["scli_choisi"]), $tab_maitre, 'window.opener.', 'ddeur');
                echo "\n";
            cre_sel_codecocl($td,$ci,$cc, intval($_POST["scli_choisi"]), 'window.opener.', 'codecocl');
                echo "\n";
        }
        ?>

        function init_all() {
            init_Body();
            <?PHP
            if ($form_ok == FALSE)
            {
                echo "add_func_click('annul1','sclose','');";
                echo "add_func_click('annul2','sclose','');";
                echo "init_valid_form('enr1','sitesi_lst','".$_SESSION['date_fmtshort']."',tab_champ,'','');";
                echo "init_valid_form('enr2','sitesi_lst','".$_SESSION['date_fmtshort']."',tab_champ,'','');";
                echo "Focus_first();";
            }
            else
            {
                if ($_SESSION["niv_log"]<> 2)
                {
                    echo "update_sel_codeages();";
                    echo "update_sel_tec();";
                    // On remet les valeurs générées à zéro si on repart sur un nouveau site
                    if ($si<>$_POST["scli_choisi"])
                    {
                        echo "update_detail_pbm(true,'detailpbm','','viewpbm','viewpbmfait');";
                        echo "update_fait_pbm(true,'detailpbmfait','','viewpbmfait');";
                        $_SESSION["pbm_choisis"] = '';
                        $_SESSION["pbm_faits"] = '';
                        $nom_scli = nom_scli($_POST["scli_choisi"],TRUE);
                        echo "update_scli_from_fen_sites(true,'nomsite','".str_escape($nom_scli)."','idsite','".$_POST["scli_choisi"]."');";
                    }
                }
                echo "update_sel_ddeurs();";
                echo "update_sel_codecocl();";
                echo "self.close();";
            }
            ?>
        }

        $(document).ready(function () {
            init_all();
        });
        //-->
    </script>

</head>

<body>

<?PHP
if (($pbm_site == FALSE) AND ($pbm_cli == FALSE) AND ($pbm_int == FALSE) AND ($pbm_cocl == FALSE))
{
if ($form_ok == FALSE) // Si le formulaire n'a pas été validé
{
?>
<p align="center"><span class="titrepage"><?PHP echo _("SITES D'INTERVENTION"); ?></span></p>

<div align="center">
    <?PHP
    if (($td == "add") OR ($td == "edit")) {
        echo _("Merci de choisir le site d'intervention");
        if ((@$_SESSION["niv_log"] <> 2) AND (@$_SESSION["niv_log"] <> 6) AND (@$_SESSION["niv_log"] <> 7)) {
            echo '<div class="annot_petit_it" style="width:70%;">';
            echo _("Si vous modifiez votre choix par rapport à l'actuel,");
            echo _("la liste des matériels/problèmes/travaux effectués précédemment générée,");
            echo _("celle des contrats possibles, et celle des techniciens seront remises à zéro.");
            echo "</div>";
        }
        echo '<br />';
        echo '<div class="annot_std_it">';
        if ($co <> "")
            echo _("Liste des sites couverts par le contrat") . " " . $co;
        else
            echo _("Liste de tous les sites actifs");
        echo '</div>';
    }
    ?>
</div>

<form name="sitesi_lst" id="sitesi_lst" method="post" action="sitesi_lst.php">
<input name="ci" type="hidden" id="ci" value="<?PHP echo $ci ?>">
<input name="cc" type="hidden" id="cc" value="<?PHP echo $cc ?>">
<input name="co" type="hidden" id="co" value="<?PHP echo $co ?>">
<input name="td" type="hidden" id="td" value="<?PHP echo $td ?>">
<input name="dte" type="hidden" id="dte" value="<?PHP echo $dte ?>">
<input name="si" type="hidden" id="si" value="<?PHP echo $si ?>">
<input name="ca" type="hidden" id="ca" value="<?PHP echo $ca ?>">
<input name="cas" type="hidden" id="cas" value="<?PHP echo $cas ?>">
<input name="nbutton" type="hidden" id="nbutton" value="">
<?PHP
echo '<p align="center">';
if ($td <> "view") {
    echo '<input name="RAZ" type="reset" class="bton_std" id="RAZ" value="' . _("Remise à Zéro") . '">';
    echo '<input name="enr1" type="button" class="bton_std" id="enr1" value="' . _("Valider") . '">';
    echo '<input name="annul1" type="button" class="bton_std" id="annul1" value="' . _("Annuler") . '">';
} else
    echo '<input name="annul1" type="button" class="bton_std" id="annul1" value="' . _("Fermer") . '">';
echo '</p>';

echo "<table class=\"MtableD\" border=\"0\" width=\"890\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\">\n";

// création de l'entête de la table "sites d'intervention"
echo "<th>";
echo _("Coordonnées");
echo "</th>\n";
echo "<th>";
echo _("Tel/Fax");
echo "</th>\n";
echo "<th>";
echo _("Contact");
echo "</th>\n";
echo "<th>";
echo _("Créé le");
echo "</th>\n";
echo "<th>";
echo _("Choisir");
echo "</th>\n";

$j = 0;
if (($sitep == TRUE) OR ($co == "")) {
    $affsitep = TRUE;
    switch (@$_SESSION["niv_log"]) {
        case 3 :
        case 4 :
            // L'agence n'est pas celle qui gère le compte principal
            if (($cli_prop <> @$_SESSION["code_age"]) AND ($cli_prop <> "") AND ($cli_prop <> NULL))
                $affsitep = FALSE;
            break;
        default :
            break;
    }

    if ($affsitep == TRUE) {
        // création de l'entête de ligne (TR)
        creetrlstdet($j);

        echo "<td>\n";
        echo _("Site principal");
        echo "</td>\n";
        echo "<td align=\"center\">\n";
        echo "&nbsp;";
        echo "</td>\n";
        echo "<td align=\"center\">\n";
        echo "&nbsp;";
        echo "</td>\n";
        echo "<td align=\"center\">\n";
        echo "&nbsp;";
        echo "</td>\n";

        echo "<td align=\"center\">\n";

        $choisi = FALSE;

        if ($si == 0)
            $choisi = TRUE;

        $readonly = "";
        if ($td == "view")
            $readonly = "disabled";

        if ($choisi == TRUE) {
            if ($j % 2 == 0)
                echo "<input type=\"radio\" name=\"scli_choisi\" value=\"0\" class=\"TRalter1D\" checked " . $readonly . ">";
            else
                echo "<input type=\"radio\" name=\"scli_choisi\" value=\"0\" class=\"TRalter2D\" checked " . $readonly . ">";
        } else {
            if ($j % 2 == 0)
                echo "<input type=\"radio\" name=\"scli_choisi\" value=\"0\" class=\"TRalter1D\" " . $readonly . ">";
            else
                echo "<input type=\"radio\" name=\"scli_choisi\" value=\"0\" class=\"TRalter2D\" " . $readonly . ">";
        }
        echo "</td>\n";
        echo "</tr>\n";

        $j++;
    }
}

// Création de la liste des sites secondaires
$tab_scli = give_tab_scli_age($cc, $ca, $cas);

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

if (count($tab_scli) > 0) {
    $rech = "SELECT * FROM `" . TBSCLI . "` WHERE (";
    foreach ($tab_scli as $value) {
        $rech .= " scli_id = " . $value . " OR";
    }

    // Suppression du dernier 'OR'
    $rech = substr($rech, 0, strlen($rech) - 3);
    $rech .= ")";
    $rech .= " ORDER BY `scli_ste`";
    $rows = $db->get_results($rech, ARRAY_A);
    if (($rows) AND (count($rows) > 0)) {
        foreach ($rows as $row) {
            $row = encode_str($row);
            if ((exist_in_array($row["scli_id"], $tab_sites) == TRUE) OR ($co == "")) {
                // création de l'entête de ligne (TR)
                creetrlstdet($j);

                echo "<td>\n";
                echo $row["scli_ste"];
                echo "<br />";
                echo $row["scli_adr1"];
                echo "<br />";
                if ($row["scli_adr2"] <> "") {
                    echo $row["scli_adr2"];
                    echo "<br />";
                }
                echo Retournecp_Id($row["scli_ville"], FALSE) . " " . Retourneville_Id($row["scli_ville"], FALSE) . "<br />";
                // détail propriétaire
                if (((@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 9)) OR (((@$_SESSION["niv_log"] == 4) OR (@$_SESSION["niv_log"] == 3)) AND ($cli_prop = @$_SESSION["code_age"]))) {
                    echo "<div class=\"annot_petit_it\" align=\"right\">";
                    $txt = _("Géré par") . " ";
                    switch ($row["scli_prop"]) {
                        case "-1" :
                            $txt .= _("agences couvrant le département");
                            break;
                        case "0" :
                            if (trim($cli_prop) <> "")
                                $txt .= $cli_prop;
                            else
                                $txt = _("Non affecté");
                            break;
                        default :
                            if (trim($row["scli_prop"]) <> "")
                                $txt .= $row["scli_prop"];
                            else {
                                if (trim($cli_prop) <> "")
                                    $txt .= $cli_prop;
                                else
                                    $txt = _("Non affecté");
                            }
                            break;
                    }
                    echo $txt;
                    echo "</div>";
                }
                echo "</td>\n";
                echo "<td align=\"center\">\n";
                echo _("T.") . $row["scli_telf"];
                if ($row["scli_fax"] <> "") {
                    echo "<br />";
                    echo _("F.") . $row["scli_fax"];
                }
                echo "</td>\n";
                echo "<td align=\"center\">\n";
                echo $row["scli_rcivil"] . " " . $row["scli_rprenom"] . " " . $row["scli_rnom"];
                echo "<br />";
                echo _("T.") . $row["scli_rtelf"];
                if ($row["scli_rfax"] <> "") {
                    echo "<br />";
                    echo _("F.") . $row["scli_rfax"];
                }
                if ($row["scli_rtelp"] <> "") {
                    echo "<br />";
                    echo _("P.") . $row["scli_rtelp"];
                }
                echo "</td>\n";
                echo "<td align=\"center\">\n";
                echo datetolocal($row["scli_datecrea"]);
                echo "</td>\n";

                echo "<td align=\"center\">\n";
                $choisi = FALSE;
                if ($row["scli_id"] == $si)
                    $choisi = TRUE;

                $readonly = "";
                if ($td == "view") {
                    $readonly = "disabled";
                }

                if ($choisi == TRUE) {
                    if ($j % 2 == 0)
                        echo "<input type=\"radio\" name=\"scli_choisi\" value=\"" . $row["scli_id"] . "\" class=\"TRalter1D\" checked " . $readonly . ">";
                    else
                        echo "<input type=\"radio\" name=\"scli_choisi\" value=\"" . $row["scli_id"] . "\" class=\"TRalter2D\" checked " . $readonly . ">";
                } else {
                    if ($j % 2 == 0)
                        echo "<input type=\"radio\" name=\"scli_choisi\" value=\"" . $row["scli_id"] . "\" class=\"TRalter1D\" " . $readonly . ">";
                    else
                        echo "<input type=\"radio\" name=\"scli_choisi\" value=\"" . $row["scli_id"] . "\" class=\"TRalter2D\" " . $readonly . ">";
                }
                echo "</td>\n";
                echo "</tr>\n";

                $j++;
            }
        }
    }
}
echo "</table>\n";
// Fin affichage table liste sites
$db->disconnect();

echo '<p align="center">';

switch ($td) {
    case "view" :
        echo '<input name="annul2" type="button" class="bton_std" id="annul2" value="' . _("Fermer") . '">';
        break;
    default :
        echo '<input name="RAZ" type="reset" class="bton_std" id="RAZ" value="' . _("Remise à Zéro") . '">';
        echo '<input name="enr2" type="button" class="bton_std" id="enr2" value="' . _("Valider") . '">';
        echo '<input name="annul2" type="button" class="bton_std" id="annul2" value="' . _("Annuler") . '">';
        break;
}

echo '</p>';
echo '</form>';
}
}
else
    close_fen_auto('', '');
?>
</body>
</html>
