<?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/fic_age.inc.php");
include_once("../inc/fic_cli.inc.php");
include_once("../inc/fic_co.inc.php");
include_once("../inc/fic_cocl.inc.php");
include_once("../inc/fic_do.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_prm.inc.php");
include_once("../inc/fic_txt.inc.php");
include_once("../inc/func.inc.php");
include_once("../inc/func_date.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_mail.inc.php");
include_once("../inc/func_time.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../inc/func_txtcm.inc.php");
include_once("../classes/phpmailer/class.phpmailer.php");
include_once("../classes/phpmailer/class.smtp.php");
include_once("mail.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"]);
// Variables Formulaire
fix_magic_quotes();
$_POST = clean_str($_POST);
$_GET = clean_str($_GET);

$codecocl = $_GET['co']; // Récupération code Contrat
$codeuser = @$_SESSION["code_log"];
$okval = FALSE;
$pbm_cocl = FALSE;

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

if ($action_to_do == 'valid') {
    $okval = TRUE;
    $codecocl = $_POST['co']; // Récupération code Contrat
}

if ($codecocl <> "") {
    $row = lit_enr_cocl($codecocl);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);

        $codeadev = give_dev_codea_defaut_cocl($codecocl, $_SESSION["lng"]);

        // 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
        $pbm_cocl = TRUE;

    if ($pbm_cocl == FALSE) {
        if ($okval == TRUE) {
            // création d'un nouveau contrat sur la base de l'ancien
            $codeco = crecode("CO", TRUE);

            $datedf = $_POST["datedf"];
            if ($datedf <> "")
                $dated = datetomysql($datedf);
            else
                $dated = $datedf;
            $dateff = $_POST["dateff"];
            if ($dateff <> "")
                $datef = datetomysql($dateff);
            else
                $datef = $dateff;
            $nval = $_POST["nval"];
            $inc_annexes = intval($_POST["incannexes"]);
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

            // Réinjection des sites secondaires dans le nouveau contrat
            // et vérification si site principal choisi
            $sitep = 0;
            $tab_sites = $_POST["scli"];
            foreach ($tab_sites as $id_site) {
                if (trim($id_site) <> "") {
                    if (intval($id_site) <> 0) {
                        $rech = "INSERT INTO `" . TBSCLIC . "`";
                        $rech .= " (sclic_datecrea,sclic_datemod,sclic_idscli,sclic_codecocl)";
                        $rech .= " VALUES";
                        $rech .= " ('$datea','$datea','$id_site','" . $db->escape($codeco) . "')";
                        $db->query($rech);
                    } else
                        $sitep = 1;
                }
            }

            //  Création des produits et licences couverts

            // On construit la chaine de caractères des codes licences/produits
            // et la chaine de caractères du matériel couvert
            $str_rlp = $cocl_coderlp;
            $str_matos = $cocl_matos;

            // Balayage des annexes signées du contrat (et couvrant les sites choisis)
            if ($inc_annexes == 1) {
                $tab_sites = $_POST["scli"];
                foreach ($tab_sites as $id_site) {
                    if (trim($id_site) <> "") {
                        // Site principal ?
                        if (intval($id_site) <> 0) {
                            // Non : On récupère l'ID de l'annexe au contrat qui couvre l'ID du site
                            $rech2 = "SELECT sclia_idcocla FROM `" . TBSCLIA . "` WHERE sclia_idscli = '" . $id_site . "' AND sclia_codecocl = '" . $db->escape($codecocl) . "'";
                            $row2 = $db->get_row($rech2, ARRAY_A);
                            // Il y a une annexe qui couvre ce contrat : on récupère la chaine des licences/produits couverts
                            if ($row2) {
                                extract($row2);
                                $rech3 = "SELECT cocla_coderlp FROM `" . TBCOCLA . "` WHERE cocla_id = '" . $sclia_idcocla . "' AND cocla_datesig <> '0000-00-00'";
                                $row3 = $db->get_row($rech3, ARRAY_A);
                                if ($row3) {
                                    extract($row3);
                                    if (trim($str_rlp) <> "")
                                        $str_rlp .= "-";
                                    $str_rlp .= $cocla_coderlp;
                                }
                            }
                        } else {
                            // Oui : on récupère la chaine licences/produits de l'annexe
                            $rech2 = "SELECT cocla_coderlp, cocla_matos FROM `" . TBCOCLA . "` WHERE";
                            if ($sitep == 0)
                                $rech2 .= " cocla_sitep = '1'";
                            else
                                $rech2 .= " (cocla_sitep = '1' OR cocla_sitep = '0')";
                            $rech2 .= " AND cocla_codecocl = '" . $db->escape($codecocl) . "'";
                            $rech2 .= " AND cocla_datesig <> '0000-00-00'";
                            $row2 = $db->get_row($rech2, ARRAY_A);
                            if ($row2) {
                                $row2 = encode_str($row2);
                                extract($row2);
                                if (trim($str_rlp) <> "")
                                    $str_rlp .= "-";
                                $str_rlp .= $cocla_coderlp;
                                if (trim($str_matos) <> "")
                                    $str_matos .= chr(13) . chr(10);
                                $str_matos .= $cocla_matos;
                            }
                        }
                    }
                }
            }

            // Création du nouveau contrat
            $rech = "INSERT INTO `" . TBCOCL . "`";
            $rech .= " (cocl_datecrea,cocl_codecrea,cocl_datemod,cocl_codemod,cocl_dateenv,cocl_daterec,cocl_code,cocl_codeco,cocl_codeper,";
            $rech .= "cocl_codeage,cocl_codecli,cocl_delai,cocl_nbs,cocl_typh,cocl_dated,cocl_datef,cocl_preavis,cocl_daterel,cocl_nivrel,";
            $rech .= "cocl_renouv,cocl_rnum,cocl_datefin,cocl_signe,cocl_matos,cocl_pvht,cocl_coderlp,cocl_sitep,cocl_codetva,";
            $rech .= "cocl_renauto)";
            $rech .= " VALUES";
            $rech .= " ('$datea','$codeuser','$datea','$codeuser','$datea','','$codeco','$cocl_codeco','$cocl_codeper',";
            $rech .= "'$cocl_codeage','$cocl_codecli','$cocl_delai','$cocl_nbs','$cocl_typh','$dated','$datef','$cocl_preavis','','',";
            $rech .= "'','','','','" . $db->escape(decode_str($str_matos)) . "','$nval','$str_rlp','$sitep','$cocl_codetva','$cocl_renauto')";
            $db->query($rech);

            // Mise à jour fiche contrat client
            $upd = "UPDATE `" . TBCOCL;
            $upd .= "` SET `cocl_datemod`='" . $datea . "', `cocl_codemod`='" . $codeuser . "', `cocl_renouv`='1',";
            $upd .= "  `cocl_rnum`='" . $db->escape($codeco) . "' WHERE `cocl_code` = '" . $db->escape($codecocl) . "'";
            $db->query($upd);

            // Suppression des annexes non signées de l'ancien contrat
            $rech = "DELETE FROM `" . TBCOCLA . "` WHERE `cocla_datesig` = '0000-00-00' AND `cocla_codecocl` = '" . $db->escape($codecocl) . "'";
            $db->query($rech);

            $db->disconnect();

            // Envoi d'email vers le client
            envoi_mail("", _("Renouvellement de votre contrat"), "con", "ren", "xxx", "cli", $codecocl, "", "", FALSE);
            // Envoi d'email vers l'agence
            if (@$_SESSION["niv_log"] <> 4)
                envoi_mail("", _("Proposition de renouvellement de contrat"), "con", "ren", "xxx", "age", $codecocl, "", "", FALSE);
            // Envoi d'email vers le centre de gestion
            envoi_mail("", _("Proposition de renouvellement de contrat"), "con", "ren", "xxx", "cdg", $codecocl, "", "", TRUE);

            $msg = _("Nouveau contrat (N°") . $codeco . ") " . _("créé");
            $retourliste = TRUE;
        }
    }
} else
    $pbm_cocl = TRUE;
?>
<!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 _("Renouvellement de contrat"); ?></title>

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

    <?PHP
    if ($okval == FALSE) {
        ?>
            <script language="javascript">
            <!--
            var tab1_champ = ["nom:datedf ; format:date ; masque:<?PHP echo $_SESSION['date_fmtfull']; ?> ; req:Y ; vmn:<?PHP if (datetolocal($cocl_datef)<>"") echo datetolocal(ajoute_un_jour_date($cocl_datef)); else echo $cocl_dated; ?> ; txt:<?PHP echo _("Date début"); ?> ; stok:frmok ; stbad:frmbad",
                "nom:dateff ; format:date ; masque:<?PHP echo $_SESSION['date_fmtfull']; ?> ; req:N ; txt:<?PHP echo _("Date fin"); ?> ; stok:frmok ; stbad:frmbad",
                "nom:valpour ; format:reel_ns ; req:Y ; txt:<?PHP echo _("Pourcentage revalorisation"); ?> ; lmx:10 ; stok:frmok ; stbad:frmbad",
                "nom:scli[] ; format:listem ; req:Y ; txt:<?PHP echo _("Sites clients"); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad"];
            //-->
            </script>
    <?PHP
    }
    ?>

    <script type="text/javascript">
        <!--
        function init_datepicker() {
            $.datepicker.setDefaults({
                closeText: "<?PHP echo _("Fermer"); ?>",
                prevText: "<?PHP echo _("Précédent"); ?>",
                nextText: "<?PHP echo _("Suivant"); ?>",
                currentText: "<?PHP echo _("Aujourd'hui"); ?>",
                monthNames: ["<?PHP echo implode('","',$lng_tmoisf); ?>"],
                monthNamesShort: ["<?PHP echo implode('","',$lng_tmoism); ?>"],
                dayNames: ["<?PHP echo implode('","',$lng_tjourf); ?>"],
                dayNamesShort: ["<?PHP echo implode('","',$lng_tjourm); ?>"],
                dayNamesMin: ["<?PHP echo implode('","',$lng_tjours); ?>"],
                weekHeader: "<?PHP echo _("Sem."); ?>",
                dateFormat: "<?PHP echo $_SESSION['date_fmtshort']; ?>",
                firstDay: 1,
                isRTL: !1,
                changeMonth: true,
                changeYear: true,
                showMonthAfterYear: !1,
                yearSuffix: "",
                showButtonPanel: true,
                showOn: "both",
                buttonImageOnly: true,
                buttonImage: "../img/calendar.png",
                buttonText: "<?PHP echo _("Calendrier"); ?>"
            });
            $("#datedf").datepicker({
                onSelect: function (datesel) {
                    $("#datedf").blur();
                    return chk_datedif(datesel, this.id, '<?PHP echo $_SESSION['date_fmtshort']; ?>', true, '', '', 'dateff',false);
                }
            });
            $("#dateff").datepicker({
                onSelect: function (datesel) {
                    $("#dateff").blur();
                    return chk_datedif(datesel, this.id, '<?PHP echo $_SESSION['date_fmtshort']; ?>', true, 'datedf', '', '',false);
                }
            });
        }

        function init_all() {
            init_Body();
            init_datepicker();
            <?PHP
            if ($okval == FALSE)
                echo "init_valid_form('enr','coclren_maj','".$_SESSION['date_fmtshort']."',tab1_champ,'','');";
            else
            {
                $url_cocl = "cocl_maj.php?td=edit&co=".$codeco."&cc=".$cocl_codecli;
                echo "init_warn('coclren','','".$url_cocl."','','');";
            }
            ?>
            init_fdeci('valpour', 2,'');
            init_fdeci('nval', <?PHP echo $_SESSION['num_nbdec']; ?>,'');
            init_calc_hausse('valpour', 'valpour', 'nval', 'exval', 2, 'to_mt');
            init_calc_hausse('nval', 'valpour', 'nval', 'exval', 2, 'to_pour');
            init_autohref('ann', 'click', 'coclren_lst.php?ord=DES&tri=Code',false);
            init_autoraz('razdatedf', 'datedf', 'click');
            init_autoraz('razdateff', 'dateff', 'click');
            Focus_first();
        }

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

</head>

<body>

<?php
include_once("../inc/entete.inc.php");
?>
<p align="center"><span class="titrepage"><?PHP echo _("RENOUVELLEMENT DE CONTRAT"); ?></span></p>
<?PHP
if ($pbm_cocl == FALSE) {
    ?>
    <div align="center"><?PHP echo _("Contrat N°") . $codecocl; ?></div>
    <?PHP
    if ($okval == TRUE) {
        echo '<p align="center">';
        if ($retourliste == FALSE)
            echo '<span class="alerte1">';
        else
            echo '<span class="annot_std_gras">';
        echo $msg;
        echo '</span>';
        echo '</p>';
        echo '<p align="center" class="annot_std_it">'._("Passage en mode édition...").'</p>';
    } else {
        ?>
        <br />
        <form name="coclren_maj" id="coclren_maj"  method="post" action="coclren_maj.php">
            <input name="co" type="hidden" id="code" value="<?PHP echo $codecocl ?>">
            <input name="nbutton" type="hidden" id="nbutton" value="">
            <!-- Date de départ -->
            <table width="900" border="0" align="center">
                <tr>
                    <td width="160" class="rubfrm" id="f_datedf" align="right"><?PHP echo _("Début / Fin"); ?></td>
                    <td>
                        <?PHP
                        echo '<input name="datedf" type="text" id="datedf" value="" size="10" maxlength="10" readonly="1">';
                        echo ' <img src="../img/raz.png" id="razdatedf" border="0" align="absmiddle">';
                        echo ' / ';
                        echo '<input name="dateff" type="text" id="dateff" value="" size="10" maxlength="10" readonly="1">';
                        echo ' <img src="../img/raz.png" id="razdateff" border="0" align="absmiddle">';
                        echo '<span class="annot_petit_it">(' . _("Pas de de date de fin si illimité") . ')</span>';
                        echo '<div class="annot_petit_it">';
                        echo '(' . _("Ancienne période") . ' : ' . _("du") . ' ' . datetolocal($cocl_dated) . ' ' . _("au").' ';
                        if (datetolocal($cocl_datef) <> "")
                            echo datetolocal($cocl_datef);
                        else
                            echo '...';
                        echo ')';
                        echo '</div>';
                        ?>
                    </td>
                </tr>
            </table>
            <table width="900" border="0" align="center">
                <tr>
                    <td width="160" class="rubfrm" id="f_valpour" align="right"
                        rowspan="2"><?PHP echo _("Valorisation"); ?></td>
                    <td width="120" align="right" class="annot_petit_it"><?PHP echo _("Taux"); ?> :</td>
                    <td class="annot_petit_it">
                        <?PHP
                        $pxrevient = px_revient_cocl($cocl_code, TRUE);
                        $mge = 0;
                        if ($cocl_pvht <> 0)
                            $mge = (($cocl_pvht - $pxrevient) / $cocl_pvht) * 100;
                        $pv_annexes = px_vte_cocla($cocl_code, '', TRUE);
                        $pv_total = $cocl_pvht + $pv_annexes;
                        ?>
                        <input name="exval" type="hidden" id="exval" value="<?PHP echo $pv_total; ?>">
                        <?PHP
                        cre_input_num('valpour', 0);
                        echo ' %';
                        echo '<br /> (' . _("Ancien montant HT") . ' ' . full_num_format($pv_total, '', '', TRUE, $pays = '') . ' (' . _("dont annexes") . ' : ' . full_num_format($pv_annexes, '', '', TRUE, $pays = '') . ') - Prix revient : ' . full_num_format($pxrevient, '', '', TRUE, $pays = '') . ' -> marge : ' . full_num_format($mge, '', '', FALSE, $pays = '') . '%)';
                        ?>
                    </td>
                </tr>
                <tr>
                    <td align="right" class="annot_petit_it"><?PHP echo _("Nouveau montant HT"); ?> :</td>
                    <td class="annot_petit_it">
                        <?PHP
                        cre_input_num('nval', $pv_total, TRUE);
                        ?>
                    </td>
                </tr>
            </table>
            <table width="900" border="0" align="center">
                <tr>
                    <td width="160" class="rubfrm" id="f_scli" align="right"><?PHP echo _("Sites client"); ?></td>
                    <td>
                        <?PHP
                        echo '<select name="scli[]" id="scli" size="5" multiple="multiple">';
                        echo '<option>-- '._("Choisissez les sites concernés").' --</option>';
                        echo '<option value="0"';

                        // On vérifie si dans le contrat ou une annexe
                        $in_cocl = FALSE;
                        $in_cocla = FALSE;

                        // Dans contrat ?
                        if ($cocl_sitep == 1)
                            $in_cocl = TRUE;

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

                        // Dans Annexe ?
                        $rech2 = "SELECT cocla_id FROM `" . TBCOCLA . "` WHERE cocla_sitep = '1' AND cocla_codecocl = '" . $db->escape($codecocl) . "'";
                        $row2 = $db->get_row($rech2, ARRAY_A);
                        if ($row2)
                            $in_cocla = TRUE;

                        if (($in_cocl == TRUE) OR ($in_cocla == TRUE))
                            echo ' selected';
                        $txt_sitep = _("Site principal");
                        if (($in_cocl == TRUE) OR ($in_cocla == TRUE)) {
                            if ($in_cocl == TRUE)
                                $txt_sitep .= ' (' . _("Dans contrat principal") . ')';
                            if ($in_cocla == TRUE)
                                $txt_sitep .= ' (' . _("Dans annexe contrat") . ')';
                        }
                        echo '>' . $txt_sitep . '</option>';

                        // création de la liste des sites actifs
                        $rech = "SELECT scli_id,scli_ste,scli_ville FROM `" . TBSCLI . "`  WHERE scli_actif = '1' AND scli_codecli = '" . $cocl_codecli . "' 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);
                                extract($row);
                                echo '<option value="' . $scli_id . '"';

                                // On vérifie si dans le contrat ou une annexe
                                $in_cocl = FALSE;
                                $in_cocla = FALSE;

                                // Dans contrat ?
                                $rech2 = "SELECT sclic_id FROM `" . TBSCLIC . "` WHERE sclic_idscli = '" . $scli_id . "' AND sclic_codecocl = '" . $db->escape($codecocl) . "'";
                                $row2 = $db->get_row($rech2, ARRAY_A);
                                if ($row2)
                                    $in_cocl = TRUE;

                                // Dans annexe ?
                                $rech2 = "SELECT sclia_idcocla FROM `" . TBSCLIA . "` WHERE sclia_idscli = '" . $scli_id . "' AND sclia_codecocl = '" . $db->escape($codecocl) . "'";
                                $row2 = $db->get_row($rech2, ARRAY_A);
                                if ($row2) {
                                    $row2 = encode_str($row2);
                                    extract($row2);
                                    $rech3 = "SELECT cocla_datesig FROM `" . TBCOCLA . "` WHERE cocla_id = '" . $sclia_idcocla . "'";
                                    $row3 = $db->get_row($rech3, ARRAY_A);
                                    if ($row3) {
                                        $row3 = encode_str($row3);
                                        extract($row3);
                                        if (datetolocal($cocla_datesig) <> "")
                                            $in_cocla = TRUE;
                                    }
                                }

                                if (($in_cocl == TRUE) OR ($in_cocla == TRUE))
                                    echo ' selected';
                                $txt_scli = $scli_ste . ", " . Retournecp_Id($scli_ville, FALSE) . " " . Retourneville_Id($scli_ville, FALSE);

                                if (($in_cocl == TRUE) OR ($in_cocla == TRUE)) {
                                    if ($in_cocl == TRUE)
                                        $txt_scli .= ' (' . _("Dans contrat principal") . ')';
                                    if ($in_cocla == TRUE)
                                        $txt_scli .= ' (' . _("Dans annexe contrat") . ')';
                                }

                                echo '>' . $txt_scli . '</option>';
                            }
                        }
                        $db->disconnect();
                        echo '</select>';
                        echo ' <img src="../img/oblig.png" align="absmiddle" alt="' . _("Champ obligatoire") . '">';
                        ?>
                        <div class="annot_petit_it">
                            (<?PHP echo _("Sélectionnez les sites avec Ctrl + clic gauche"); ?>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td width="160" class="rubfrm" id="f_incannexes"
                        align="right"><?PHP echo _("Reprendre annexes"); ?></td>
                    <td class="annot_petit_it">
                        <?PHP
                        cre_select('incannexes', 'incannexes', $non_oui, '');
                        ?>
                        <div class="annot_petit_it">
                            <?PHP echo _("Si vous cochez 'oui', les sites et produits/licences des annexes rattachés à ce contrat seront réintégrées dans le nouveau contrat"); ?>
                        </div>
                        <div class="annot_petit_it">
                            <?PHP echo _("Dans tous les cas, les annexes non encore signées seront supprimées"); ?>
                            <br /> <?PHP echo _("et les annexes non signées ne sont pas prises en compte"); ?>
                        </div>
                    </td>
                </tr>
            </table>
            <?PHP /* if ($cocl_renauto==1) {
echo '<br />';
echo '<div align="center" class="annot_gras_it">Ce contrat est en reconduction tacite. Il en sera automatiquement accusé réception dès que vous aurez validé</div>';
echo '<br />';
} */
            ?>
            <p align="center">
                <?PHP
                echo '<input name="enr" type="button" class="bton_std" id="enr" value="'._("Valider").'">';
                echo '<input name="annul" type="button" class="bton_std" id="annul" value="'._("Annuler").'">';
                ?>
            </p>
        </form>
    <?PHP
    }
} else
    pop_ret_auto( _("Merci de choisir un de vos contrats"), 'warn', "coclren_lst.php?ord=DES&tri=Code");
include_once("pied.php");
?>
</body>
</html>