<?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_hum.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_txt.inc.php");
include_once("../inc/func.inc.php");
include_once("../inc/func_time.inc.php");
include_once("../inc/func_date.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../inc/func_txtcm.inc.php");
include_once("../inc/func_mail.inc.php");
include_once("../classes/phpmailer/class.phpmailer.php");
include_once("../classes/phpmailer/class.smtp.php");
include_once("../inc/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);

$rlp_choisis = @$_SESSION["rlp_choisis"];
$titre = @$_POST["titre"];
$td = @$_POST["td"];

$datecrea = datetomysql(@$_POST["datecreaf"]);
$code = str_majuscules(@$_POST["code"]);
$codecli = str_majuscules(@$_POST["codecli"]);
$prev = @$_POST["prev"];
$sitep = intval(@$_POST["sitep"]);
$codeage = str_majuscules(@$_POST["codeage"]);
$co = str_majuscules(@$_POST["co"]);
$cope = str_majuscules(@$_POST["cope"]);

$per_nbj = 0;
$row = lit_enr_per($cope);
if (is_array($row) == TRUE) {
    $row = encode_str($row);
    extract($row);
}
$delai = @$_POST["delai"];
$nbh = @$_POST["nbh"] . ":00";
$nbs = heure_sec($nbh);
$indexnbsnc = @$_POST["nbsnc"];
if ($indexnbsnc == "0")
    $nbsnc = 0;
else
    $nbsnc = 1;
$indexnbsdep = @$_POST["nbsdep"];
if ($indexnbsdep == "0")
    $nbsdep = 0;
else
    $nbsdep = 1;
$indextyph = @$_POST["typh"];
if ($indextyph == "0")
    $typh = 0;
else
    $typh = 1;

$datedf = @$_POST["datedf"];
if ($datedf <> "")
    $dated = datetomysql($datedf);
else
    $dated = $datedf;
$dateff = @$_POST["dateff"];
if ($dateff <> "")
    $datef = datetomysql($dateff);
else
    $datef = $dateff;
$indexrenauto = @$_POST["renauto"];
if ($indexrenauto == "0")
    $renauto = 0;
else
    $renauto = 1;

$preavis = @$_POST["preavis"];

// On ne peut pas avoir un préavis inférieur au maximum ("dernier délai") choisi
if ($preavis < preavis_max())
    $preavis = preavis_max();

// On ne peut pas avoir un préavis supérieur au maximum ("premier délai autorisé") choisi
if ($preavis > preavis_min())
    $preavis = preavis_min();

$matos = @$_POST["matos"];

$datesigf = @$_POST["datesig"];
if ($datesigf <> "")
    $datesig = datetomysql($datesigf);
else
    $datesig = "";
$signe = @$_POST["signe"];

$datefinf = @$_POST["datefinf"];
if ($datefinf <> "")
    $datefin = datetomysql($datefinf);
else
    $datefin = "";

if ($td == "add") {
    $renouv = 0;
    $rnum = "";
} else {
    $renouv = @$_POST["renouv"];
    $rnum = @$_POST["num"];
}

$tva = @$_POST["tva"];
$pu = floatval(@$_POST["pu"]);
$codeadev = str_majuscules(@$_POST["codeadev"]);

$codeuser = @$_SESSION["code_log"];

$enr_ok = TRUE;
$pcli = FALSE;
$retourliste = TRUE;
$enrimp = FALSE;

switch ($_POST["nbutton"]) {
    case "enrimp" :
        $retourliste = FALSE;
        $enrimp = TRUE;
        break;
    default :
        break;
}

switch ($td) {
    // Ajout de la fiche Contrat Client
    case "add" :
        $codeco = crecode("CO", TRUE);

        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
        $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_codeadev,cocl_coderlp,cocl_sitep,cocl_codetva,";
        $rech .= "cocl_nbsnc,cocl_renauto,cocl_nbsdep)";
        $rech .= " VALUES";
        $rech .= " ('$datecrea','$codeuser','$datea','$codeuser','$datea','$codeuser','$codeco','$co','$cope',";
        $rech .= "'$codeage','$codecli','$delai','$nbs','$typh','$dated','$datef','$preavis','','',";
        $rech .= "'$renouv','$rnum','$datefin','','" . $db->escape($matos) . "','$pu','$codeadev','$rlp_choisis','$sitep','$tva',";
        $rech .= "'$nbsnc','$renauto','$nbsdep')";
        $db->query($rech);

        // Remise à niveau type client
        upd_nivcli($codecli, FALSE);

        // Balayage et activation des sites sélectionnés
        if (trim($_SESSION["scli_choisis"]) <> "") {
            $tab_sites = explode("-", $_SESSION["scli_choisis"]);
            foreach ($tab_sites as $id_site) {
                if (($id_site <> "") AND ($id_site <> 0)) {
                    $rech = "INSERT INTO `" . TBSCLIC . "`";
                    $rech .= " (sclic_datecrea,sclic_datemod,sclic_idscli,sclic_codecocl)";
                    $rech .= " VALUES";
                    $rech .= " ('$datecrea','$datea','$id_site','$codeco')";
                    $db->query($rech);
                }
            }
        }
        $db->disconnect();

        $msg = _("Contrat") . " " . $codeco . " " . _("créé");

        if ($retourliste == TRUE) {
            // Envoi d'email vers le client
            if ($prev == 0)
                envoi_mail("", "création de votre contrat " . $codeco, "con", "cre", "xxx", "cli", $codeco, "", "", FALSE);
            else {
                if ($prev <> 4) // Le niveau 4 est "Ne pas prévenir"
                {
                    $pcli = TRUE;
                    $txtcorps = cre_corps_txtc("con", "cre", "xxx", "cli", $codeco, "", "");
                    $_SESSION["txt"] = $txtcorps;
                }
                // Envoi d'email vers le webmaster
                envoi_mailwm("", "création d'un contrat", "con", "cre", "xxx", "cli", $codeco, "", "");
            }
            // Envoi d'email vers l'agence
            if (@$_SESSION["niv_log"] <> 4)
                envoi_mail("", "création de contrat", "con", "cre", "xxx", "age", $codeco, "", "", FALSE);
            // Envoi d'email vers le centre de gestion
            envoi_mail("", "création de contrat", "con", "cre", "xxx", "cdg", $codeco, "", "", TRUE);
        }
        break;

    // MAJ de la fiche Contrat Client
    case "edit" :
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
        $rech = "UPDATE `" . TBCOCL;
        $rech .= "` SET `cocl_datemod`='" . $datea . "', `cocl_codemod`='" . $codeuser . "', `cocl_codeco`='" . $co . "', `cocl_codeper`='" . $cope . "', `cocl_codecli`='" . $codecli . "', `cocl_delai`='" . $delai . "', `cocl_nbs`='" . $nbs . "', `cocl_typh`='" . $typh . "',";
        $rech .= " `cocl_dated`='" . $dated . "', `cocl_datef`='" . $datef . "', `cocl_preavis`='" . $preavis . "', `cocl_renouv`='" . $renouv . "', `cocl_rnum`='" . $rnum . "', `cocl_datefin`='" . $datefin . "',";
        $rech .= " `cocl_signe`='" . $db->escape($signe) . "', `cocl_matos`='" . $db->escape($matos) . "', `cocl_pvht`='" . $pu . "', `cocl_codeadev`='" . $codeadev . "', `cocl_coderlp`='" . $rlp_choisis . "', `cocl_sitep`='" . $sitep . "', `cocl_codetva`='" . $tva . "',";
        $rech .= " `cocl_nbsnc`='" . $nbsnc . "', `cocl_renauto`='" . $renauto . "', `cocl_nbsdep`='" . $nbsdep . "'";
        $rech .= " WHERE `cocl_code` = '" . $db->escape($code) . "'";

        $db->query($rech);

        // Remise à niveau type client
        upd_nivcli($codecli, FALSE);

        // Mise à jour des sites sélectionnés

        // On vide d'abord tout
        $rech = "DELETE FROM `" . TBSCLIC . "` WHERE `sclic_codecocl`= '" . $db->escape($code) . "'";
        $db->query($rech);

        // On reconstruit si des sites ont été choisis
        if (trim($_SESSION["scli_choisis"]) <> "") {
            $tab_sites = explode("-", $_SESSION["scli_choisis"]);
            foreach ($tab_sites as $id_site) {
                if (($id_site <> "") AND ($id_site <> 0)) {
                    $rech = "INSERT INTO `" . TBSCLIC . "`";
                    $rech .= " (sclic_datecrea,sclic_datemod,sclic_idscli,sclic_codecocl)";
                    $rech .= " VALUES";
                    $rech .= " ('$datecrea','$datea','$id_site','$code')";
                    $db->query($rech);
                }
            }
        }

        $db->disconnect();

        if ($retourliste == TRUE) {
            if ($datefin <> "") // Si date de clôture, on prévient le client
            {
                // Envoi d'email vers le client
                if ($prev == 0)
                    envoi_mail("", "Clôture de votre contrat " . $code, "con", "clo", "xxx", "cli", $code, "", "", FALSE);
                else {
                    if ($prev <> 4) // Le niveau 4 est "Ne pas prévenir"
                    {
                        $pcli = TRUE;
                        $txtcorps = cre_corps_txtc("con", "cli", "xxx", "cli", $code, "", "");
                        $_SESSION["txt"] = $txtcorps;
                    }
                    envoi_mailwm("", "Clôture du contrat " . $code, "con", "clo", "xxx", "cli", $code, "", "");
                }
                // Envoi d'email vers l'agence
                if (@$_SESSION["niv_log"] <> 4)
                    envoi_mail("", "Clôture du contrat " . $code, "con", "clo", "xxx", "age", $code, "", "", FALSE);
                // Envoi d'email vers le centre de gestion
                envoi_mail("", "Clôture du contrat " . $code, "con", "clo", "xxx", "cdg", $code, "", "", TRUE);
            } else // Si pas de date de clôture, on le prévient simplement de la modification
            {
                // Envoi d'email vers le client
                if ($prev == 0)
                    envoi_mail("", "Modification de votre contrat " . $code, "con", "mod", "xxx", "cli", $code, "", "", FALSE);
                else {
                    if ($prev <> 4) // Le niveau 4 est "Ne pas prévenir"
                    {
                        $pcli = TRUE;
                        $txtcorps = cre_corps_txtc("con", "cli", "xxx", "cli", $code, "", "");
                        $_SESSION["txt"] = $txtcorps;
                    }
                    // Envoi d'email vers le webmaster
                    envoi_mailwm("", "Modification du contrat " . $code, "con", "mod", "xxx", "cli", $code, "", "");
                }
                // Envoi d'email vers l'agence
                if (@$_SESSION["niv_log"] <> 4)
                    envoi_mail("", "Modification du contrat " . $code, "con", "mod", "xxx", "age", $code, "", "", FALSE);
                // Envoi d'email vers le centre de gestion
                envoi_mail("", "Modification du contrat " . $code, "con", "mod", "xxx", "cdg", $code, "", "", FALSE);
            }
        }
        $msg = _("Contrat") . " " . $code . " " . _("modifié");
        break;

    // Suppression de la fiche Contrat Client
    case "del" :
        if ($datefin == "") {
            if (nb_cocl_in_coclh($code) == 0) {
                $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

                // Contrôle que ce contrat n'est pas un renouvellement
                $rech = "SELECT `cocl_id` FROM `" . TBCOCL . "` WHERE `cocl_renouv` = 1 AND `cocl_rnum` = '" . $db->escape($code) . "'";
                $rows = $db->get_results($rech, ARRAY_A);

                if (($rows) AND (count($rows) > 0)) {
                    // Oui, on supprime alors l'info de renouvellement
                    foreach ($rows as $row) {
                        $rech2 = "UPDATE `" . TBCOCL;
                        $rech2 .= "` SET `cocl_datemod`='" . $datea . "', `cocl_codemod`='" . $codeuser . "', ";
                        $rech2 .= " `cocl_renouv`='0', `cocl_rnum`=''";
                        $rech2 .= " WHERE `cocl_id` = '" . $row["cocl_id"] . "'";
                        $db->query($rech2);
                    }
                }

                // On supprime le contrat
                $rech = "DELETE FROM `" . TBCOCL . "` WHERE `cocl_code` = '" . $db->escape($code) . "'";
                $db->query($rech);

                // On supprime les affectations de sites
                $rech = "DELETE FROM `" . TBSCLIC . "` WHERE `sclic_codecocl`= '" . $db->escape($code) . "'";
                $db->query($rech);

                // Suppression des tâches rattachées à ce contrat
                $rech = "DELETE FROM `" . TBTAC . "` WHERE `tac_coderat` = '" . $db->escape($code) . "'";
                $db->query($rech);

                $db->disconnect();

                $msg = _("Contrat") . " " . $code . " " . _("supprimé");
            } else {
                $msg = _("Le contrat") . " " . $code . " " . _("a déjà été utilisé dans une intervention");
                $retourliste = FALSE;
                $enrimp = FALSE;
            }
        } else {
            $msg = _("Impossible de supprimer un contrat clôt");
            $retourliste = FALSE;
            $enrimp = FALSE;
        }
}
?>
<!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 _("Fiche Contrat Client"); ?></title>

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

    <script type="text/javascript">
        <!--
        function init_all() {
            init_Body();
            <?PHP
            if ($retourliste == FALSE)
                echo "warn_txt('" . str_escape($msg) . "');";
            if ($pcli == TRUE)
               echo 'fen_prev_cli('.$prev.');';
            ?>
            init_new_fen('imprim','impression','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 $titre ?></span></p>

<p align="center">&nbsp;</p>
<?PHP
if ($retourliste == FALSE) {
    if ($enrimp == TRUE) {
        if ($td == "add")
            $urlimp = "cocl_pdf.php?code=" . $codeco . "&timp=0";
        else
            $urlimp = "cocl_pdf.php?code=" . $code . "&timp=0";
        echo '<div id="imprim" align="center" title="' . $urlimp . '" class="falselnk">';
        echo '<img src="../img/print.png" title="' . _("Imprimer") . '" border="0" align="absmiddle"> ' . _("Imprimer");
        echo '</div>';
    }
    aff_ret_idx_man($td, "cocl_lst.php?ord=DES&tri=Code", _("Retour à la liste"), TRUE);
} else
    pop_ret_auto($msg, 'ok', "cocl_lst.php?ord=DES&tri=Code");
include_once("pied.php");
?>
</body>
</html>