<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.4
 *
 * Copyright (C) 2006-2016  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');
$ok_inc = FALSE;
if ($pos === FALSE) {
    $ok_inc = TRUE;
}
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(valsession('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 = '';
$co = '';
$coa = '';
$sp = 0;
$sitep = 0;
$signe = FALSE;
$lstsites = '';
$str_rlp = '';
$cocla_id = 0;
$exist_rlic_actif = FALSE;
$exist_rpdt_actif = FALSE;
$tab_scli_choisis = [];
$tab_sclia_choisis = [];

// Niveau <=2 ne peut que voir les sites des contrats
if (valsession('niv_log') <= 2) {
    $td = 'view';
}

$action_to_do = '';
if (trim(valpost('val')) <> '') // On a cliqué sur valider
{
    $action_to_do = 'valid';
}

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

    // Site principal coché ?
    if ((int)$_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 = valget('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 (CheckNivLog('1') AND ($cc <> valsession('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 (valsession('niv_log')) {
                    case 3 :
                    case 4 :
                        if (client_age_ok($cli_code, valsession('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 (CheckNivLog('1') AND ($cocl_codecli <> valsession('code_log'))) {
                    $pbm_cocl = TRUE;
                }
                // Contrôle qu'une agence n'essaye pas de "hacker" un contrat
                if (CheckNivLog('3-4') AND ($cocl_codeage <> valsession('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']);
    $tab_sclia_choisis = explode('-', $_SESSION['sclia_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é
    {
        cre_ent_form(_('SITES DU CONTRAT'), '', '', '', FALSE);
        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, 'utf8');
        $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">';

                // création de l'entête de la table "sites secondaires"
                echo '<th>';
                echo _('Coordonnées');
                echo '</th>';
                echo '<th>';
                echo _('Tel/Fax');
                echo '</th>';
                echo '<th>';
                echo _('Contact');
                echo '</th>';
                echo '<th>';
                echo _('Créé le');
                echo '</th>';
                echo '<th>';
                if ($td <> 'view') {
                    echo _('Choisir');
                } else {
                    echo '&nbsp;';
                }
                echo '</th>';

                $lstsites = '';

                foreach ($rows as $row) {
                    $row = encode_str($row);
                    // création de l'entête de ligne (TR)
                    echo '<tr>';

                    echo '<td>';
                    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>';
                    echo '<td align="center">';
                    echo _('T.') . $row['scli_telf'];
                    if ($row['scli_fax'] <> '') {
                        echo '<br />';
                        echo _('F.') . $row['scli_fax'];
                    }
                    echo '<td align="center">';
                    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>';
                    echo '<td align="center">';
                    echo datetolocal($row['scli_datecrea']);
                    echo '</td>';

                    echo '<td align="center">';
                    echo '<input type="checkbox" name="scli_choisi[]" value="' . $row['scli_id'] . '" id="chks' . $row['scli_id'] . '"';


                    if (exist_in_array($row['scli_id'], $tab_scli_choisis)) {
                        echo ' checked';
                    }
                    if (exist_in_array($row['scli_id'], $tab_sclia_choisis)) {
                        echo ' checked';
                    }

                    if (($td == 'view') OR exist_in_array($row['scli_id'], $tab_sclia_choisis)) {
                        echo ' disabled';
                    }
                    echo '>';

                    if (exist_in_array($row['scli_id'], $tab_sclia_choisis)) {
                        echo ' <div class="annot_upetit_it">' . _('Annexe') . '</div>';
                    }

                    echo '</td>';
                    echo '</tr>';
                }

                echo '</table>';
                // Fin affichage table liste sites
            }
        }
        close_database();

        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>
