<?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_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_rel.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"] = "sites";

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

$pbm_cli = FALSE;
$pbm_cocl = FALSE;
$pbm_cocla = FALSE;
$td = '';
$tx = '';
$cc = '';
$sp = 0;
$sitep = 0;
$signe = FALSE;
$lstsites = '';
$str_rlp = '';
$cocla_id = 0;
$exist_rlic_actif = FALSE;
$exist_rpdt_actif = FALSE;

// Niveau <=2 ne peut que voir les sites des contrats
if (@$_SESSION["niv_log"] <= 2)
    $td = "view";

$action_to_do = '';
if (trim(@$_POST["val"]) <> '') // On a cliqué sur valider
    $action_to_do = 'valid';

// On a validé ?
if ($action_to_do == 'valid') {

    // Site principal coché ?
    if (intval($_POST["sp"]) == 1)
        $sitep = 1;

    if ($_POST["td"])
        $td = $_POST["td"];
    if ($_POST["sp"])
        $sp = $_POST["sp"];
    if ($_POST["co"])
        $co = $_POST["co"];
    if ($_POST["sp"])
        $coa = $_POST["coa"];
    if (isset($_POST['tx']))
        $tx = $_POST["tx"];
    if (isset($_POST['cc']))
        $cc = $_POST['cc']; // Récupération code Client

    // Sites secondaires
    if (count($_POST["scli_choisi"]) <> 0)
        $lstsites = implode("-", $_POST["scli_choisi"]);
    // On vérifie si on changé le choix des sites (auquel cas, RAZ de la zone de choix des matériels et licences
    if (($_SESSION["scli_choisis"] <> $lstsites) OR ($sp <> $sitep))
        $_SESSION["rlp_choisis"] = '';
    $_SESSION["scli_choisis"] = $lstsites;
    $str_rlp = cree_txt_matos_cocl($_SESSION["rlp_choisis"]);
    $str_rlp = str_replace("'", "\'", $str_rlp);
} else // On n'a pas validé
{
    if (isset($_GET['td'])) {
        $td = $_GET['td']; // Récupération type demande
        if (($td <> "edit") AND ($td <> "view") AND ($td <> "add"))
            $pbm_cocl = TRUE;
    } else
        $pbm_cocl = TRUE;

    if (isset($_GET['tx'])) {
        $tx = $_GET['tx']; // Récupération source appel
        if (($tx <> "co") AND ($tx <> "coa"))
            $pbm_cocl = TRUE;
    } else
        $pbm_cocl = TRUE;

    if (isset($_GET['cc']))
        $cc = $_GET['cc']; // Récupération code Client
    else
        $pbm_cocl = TRUE;

    if (isset($_GET['co']))
        $co = $_GET['co']; // Récupération code Contrat
    else
        $pbm_cocl = TRUE;

    if (isset($_GET['coa']))
        $coa = $_GET['coa']; // Récupération code annexe Contrat
    else {
        if (($tx == "coa") AND ($td <> "add"))
            $pbm_cocl = TRUE;
    }

    if ($pbm_cocl == FALSE) {
        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 ($pbm_cocl == FALSE) {
    if ($co <> "") {
        // Récupération des informations contrat client
        $row = lit_enr_cocl($co);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);

            if ($cocl_signe <> "")
                $signe = TRUE;

            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 {
            switch ($tx) {
                case "co" :
                    if (($td == "edit") OR ($td == "view"))
                        $pbm_cocl = TRUE;
                    break;
                case "coa" :
                    $pbm_cocl = TRUE;
            }
        }
    } else
        $pbm_cocl = TRUE;
}

if ($pbm_cocl == FALSE) {
    if ($coa <> "") {
        // Récupération des informations annexe contrat client
        $row = lit_enr_cocla($coa, $co);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);

            if ($cocla_codecocl <> $co)
                $pbm_cocl = TRUE;

        } else {
            if (($td == "edit") OR ($td == "view"))
                $pbm_cocla = TRUE;
        }
    } else {
        if (($tx == "coa") and ($td <> "add"))
            $pbm_cocla = TRUE;
    }
}

if ($pbm_cocl == FALSE) {
    $tab_scli_choisis = explode('-', $_SESSION["scli_choisis"]);
    $exist_rlic_actif = exist_rlic_actif($cc, $_SESSION["scli_choisis"], $sitep);
    $exist_rpdt_actif = exist_rpdt_actif($cc, $_SESSION["scli_choisis"], $sitep);
    switch ($tx) {
        case "co" :
            // Si contrat terminé, force le mode "view"
            if (datetolocal($cocl_datefin) <> "")
                $td = "view";
            // Si contrat signé et en mode contrat, on force le mode "view"
            if ((datetolocal($cocl_datesig) <> "") AND ($tx == "co"))
                $td = "view";

            break;
        case "coa" :
            // Si annexe contrat signée, force le mode "view"
            if (datetolocal($cocla_datesig) <> "")
                $td = "view";
            break;
    }
}
?>
<!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 secondaires"); ?></title>

    <?PHP include_once("../inc/header.inc.php"); ?>

    <script type="text/javascript">
        <!--

        function init_all() {
            init_Body();
            <?PHP
            if ($action_to_do == 'valid')
            {
                echo "update_detail_rlp(true,'detailmat','".$str_rlp."','viewmat');";
                echo "update_detail_rlp_sites(true,'sitep','".$sitep."','sitesec','".$_SESSION["scli_choisis"]."');";
                echo "chk_disp_addmat(true,'addmat','".(int)$exist_rlic_actif."','".(int)$exist_rpdt_actif."');";
                echo "self.close();";
            }
            else
            {
                echo 'var val_sitep = window.opener.$("#sitep").val();';
                echo '$("#sp").val(val_sitep);';
                echo '$("#sitep").attr(\'checked\', (val_sitep === \'1\'));';
                echo "chk_valbut('chx','tab_lst_sites','"._("Tous")."','"._("Aucun")."');";
                echo "init_chk_valbut('chx','tab_lst_sites','"._("Tous")."','"._("Aucun")."');";
                echo "init_check_all('chx','tab_lst_sites','Tous','Aucun');";
            }
            ?>
            add_func_click('annul', 'sclose', '');
            Focus_first();
        }

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

<body>
<?PHP
if (($pbm_cli == FALSE) AND ($pbm_cocl == FALSE)) {
    if ($action_to_do == '') // Si le formulaire n'a pas été validé
    {
        echo '<p align="center"><span class="titrepage">' . _("SITES DU CONTRAT") . '</span></p>';

        echo '<p align="center">';
        if ($td == "add")
            echo _("Merci de choisir les sites");
        else
            echo _("Sites");
        echo ' ';
        if ($tx == 'coa')
            echo _("de l'annexe");
        echo ' ';
        echo _("du contrat");
        echo ' ';
        echo '<span class="annot_std_gras">' . $cocl_code . '</span>';
        echo ' ';
        echo _("pour les sites sélectionnés");
        echo '<div align="center" class="annot_petit_it">' . _("Si vous modifiez votre choix par rapport à celui en place, la liste des matériels/licences précédemment générée sera réinitialisée") . '</div>';
        echo '</p>';

        if ($td <> "view") {
            echo '<p align="center">';
            echo '<br />';
            echo '<input type="button" name="chx" id="chx" value="Tous" class="bton_fgris_petit">';
            echo '</p>';
        }

        echo '<div align="center" id="tab_lst_sites">';

        echo '<form name="sites_lst" id="sites_lst" method="post" action="sites_lst.php">';
        echo '<input name="cc" type="hidden" id="cc" value="' . $cc . '">';
        echo '<input name="co" type="hidden" id="co" value="' . $co . '">';
        echo '<input name="coa" type="hidden" id="coa" value="' . $coa . '">';
        echo '<input name="td" type="hidden" id="td" value="' . $td . '">';
        echo '<input name="tx" type="hidden" id="tx" value="' . $tx . '">';
        echo '<input name="sp" type="hidden" id="sp" value="">';

        echo '<input type="checkbox" name="sitep" id="sitep" value="sitep"';
        switch ($tx) {
            case "co" :
                // Si le contrat est signé, on ne peut pas modifier quoi que ce soit
                if (($signe == TRUE) OR ($td == "view")) echo 'disabled=" disabled"';
                break;
            case "coa" :
                // Si l'annexe au contrat est signée, on ne peut pas modifier quoi que ce soit
                if ($td == "view")
                    echo 'disabled=" disabled"';
                // Sinon, on vérifie si le site principal est "disponible"
                else {
                    if (sitep_in_cocl_except($cocl_code, $cocla_code) == TRUE)
                        echo 'disabled=" disabled"';
                }
                break;
        }

        echo '>';
        echo ' <span class="annot_std_gras">' . _("Site principal inclus dans le contrat") . '</span>';

        // création de la liste des sites secondaires
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
        $rech = "";
        switch ($tx) {
            case "co":
                $rech = "SELECT * FROM `" . TBSCLI . "` WHERE `scli_codecli`= '" . $cc . "' AND `scli_actif`=1 ORDER BY `scli_ste`";
                break;
            case "coa" :
                $tab_scli_free = give_tab_scli_non_affectes($cc, $co, $coa, FALSE);
                if (count($tab_scli_free) > 0) {
                    $rech = "SELECT * FROM `" . TBSCLI . "` WHERE (";
                    foreach ($tab_scli_free as $key => $value) {
                        $rech .= "`scli_id`= '" . $value . "' OR";
                    }
                    $rech = substr($rech, 0, strlen($rexist) - 3);
                    $rech .= ")";
                }
                break;
        }

        if ($rech <> "") {
            $rows = $db->get_results($rech, ARRAY_A);

            if ($rows) {
                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 secondaires"
                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>";
                if ($td <> "view")
                    echo _("Choisir");
                else
                    echo "&nbsp;";
                echo "</th>\n";

                $j = 0;
                $lstsites = "";

                foreach ($rows as $row) {
                    $row = encode_str($row);
                    // 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 />";
                    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 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";
                    echo '<input type="checkbox" name="scli_choisi[]" value="' . $row["scli_id"] . '" id="chks' . $row["scli_id"] . '"';
                    if ($j % 2 == 0)
                        echo " class=\"TRalter1D\"";
                    else
                        echo " class=\"TRalter2D\"";


                    if (exist_in_array($row["scli_id"], $tab_scli_choisis))
                        echo " checked";

                    if ($td == "view")
                        echo " disabled";
                    echo ">";
                    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="annul" type="button" class="bton_std" id="annul" value="' . _("Fermer") . '">';
                break;
            default :
                echo '<input name="RAZ" type="button" class="bton_std" id="RAZ"  value="' . _("Réinitialiser") . '">';
                echo '<input name="val" type="submit" class="bton_std" id="val" value="' . _("Valider") . '">';
                echo '<input name="annul" type="button" class="bton_std" id="annul" value="' . _("Annuler") . '">';
                break;
        }
        echo '</p>';
        echo '</form>';

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