<?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/fic_droits.inc.php");
include_once("../inc/fic_fici.inc.php");
include_once("../inc/fic_hum.inc.php");
include_once("../inc/fic_int.inc.php");
include_once("../inc/fic_st.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_log.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("mail.inc.php");
include_once("../classes/dirtool/class_dirtool.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);

$titre = @$_POST["titre"];
$td = @$_POST["td"];
$codeage = @$_POST["codeage"];

$code = str_majuscules(@$_POST["code"]);
$nom = str_majuscules(@$_POST["nom"]);
$rcs = str_majuscules(@$_POST["rcs"]);
$ape = str_majuscules(@$_POST["ape"]);
$tvai = str_majuscules(@$_POST["tvai"]);
$tcom = str_majuscules(@$_POST["tcom"]);
$adr1 = str_majuscules(@$_POST["adr1"]);
$adr2 = str_majuscules(@$_POST["adr2"]);
$dep = @$_POST["dep"];
$ville = str_majuscules(@$_POST["ville"]);
$pays = str_majuscules(@$_POST["pays"]);
$zone = str_majuscules(@$_POST["zonetxt"]);
$codeadev = str_majuscules(@$_POST["codeadev"]);
$telf = @$_POST["telf"];
$txttelf = @$_POST["txttelf"];
$fax = @$_POST["fax"];
$txtfax = @$_POST["txtfax"];
$web = @$_POST["web"];
$heures = @$_POST["heures"];
$txtent = @$_POST["txtent"];
$rcivil = @$_POST["rcivil"];
$rprenom = @$_POST["rprenom"];
$rnom = @$_POST["rnom"];
$rtelf = @$_POST["rtelf"];
$rtelp = @$_POST["rtelp"];
$email = strtolower(@$_POST["email"]);
$emaild = strtolower(@$_POST["emaild"]);
$emailc = strtolower(@$_POST["emailc"]);
$emailt = strtolower(@$_POST["emailt"]);
$nota = @$_POST["nota"];
$emetf = intval(@$_POST["factures"]);
$actif = intval(@$_POST["actif"]);

$tab_spec = [];
if ((@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 9))
    $tab_spec = $_SESSION["tab_spdes"];

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

$pass = cremdp(FALSE);
$passcrypt = md5($pass);

$msg = "";

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

switch ($td) {
    // Ajout de la fiche sous-traitant
    case "add" :
        $codes = "S" . $code;
        $rech = "SELECT COUNT(*) FROM `" . TBST . "` WHERE st_code = '$codes'";
        $nbres = $db->get_var($rech);
        if ($nbres == 0) {
            // Ajout du compte sous-traitant
            $rech2 = "INSERT INTO `" . TBST . "`";
            $rech2 .= " (st_datecrea,st_codecrea,st_datemod,st_codemod,st_code,st_pass,st_nom,st_rcs,st_ape,st_tvai,";
            $rech2 .= " st_tcom,st_adr1,st_adr2,st_dep,st_ville,st_codepays,st_codeadev,st_telf,st_txttelf,st_fax,st_txtfax,st_txtent,st_resp_civilite,st_resp_prenom,st_resp_nom,st_resp_telf,st_resp_telp,st_email,st_emaild,st_emailc,st_emailt,st_heures,st_web,st_nota,st_fact,st_ouvert,st_datec,st_spe) VALUES";
            $rech2 .= " ('$datea','$codeuser','$datea','$codeuser','$codes','$passcrypt','" . $db->escape($nom) . "','" . $db->escape($rcs) . "','" . $db->escape($ape) . "','" . $db->escape($tvai) . "',";
            $rech2 .= "'" . $db->escape($tcom) . "','" . $db->escape($adr1) . "','" . $db->escape($adr2) . "','$dep','$ville','$pays','$codeadev','$telf','" . $db->escape($txttelf) . "','$fax','" . $db->escape($txtfax) . "','" . $db->escape($txtent) . "',";
            $rech2 .= "'" . $db->escape($rcivil) . "','" . $db->escape($rprenom) . "','" . $db->escape($rnom) . "','$rtelf','$rtelp','$email','$emaild','$emaild','$emailt','" . $db->escape($heures) . "','" . $db->escape($web) . "','" . $db->escape($nota) . "','$emetf','1','0000-00-00','$spe')";
            $db->query($rech2);

            // Ajout du compte pour connexion
            // Niveau par défaut : 10
            // Actif par défaut

            $log_ip = $_SERVER['REMOTE_ADDR']; // Récupération adresse IP
            $rech2 = "INSERT INTO `" . TBPW . "` (pw_code,pw_pass,pw_level,pw_lastsuccess,pw_lastip,pw_actif) VALUES ('$codes','$passcrypt','10','$dateheurea','$log_ip','1')";
            $db->query($rech2);

            // Mise à jour du fichier des zones couvertes
            $tab_zone = explode("_", $zone);
            foreach ($tab_zone as $idx => $value) {
                $rech = "INSERT INTO `" . TBZOC . "`";
                $rech .= " (zoc_code,zoc_codepays,zoc_codedep) VALUES";
                $rech .= " ('$codes','$pays','$value')";
                $db->query($rech);
            }

            // Mise à jour du fichier des spécialités
            if (count($tab_spec)>0)
            {
                foreach ($tab_spec as $key => $value) {
                    $rech = "INSERT INTO `" . TBSTSP . "`";
                    $rech .= " (stsp_codest,stsp_codesp,stsp_niveau) VALUES";
                    $rech .= " ('$codes','$key','".$value["niv"]."')";
                    $db->query($rech);
                }
            }

            $msg = _("Fiche ajoutée");
        } else {
            $msg = _("Ce code existe déjà");
            $retourliste = FALSE;
        }
        $db->disconnect();

        if ($retourliste == TRUE) {
            // Envoi d'email vers l'agence
            envoi_mail("", _("Ouverture de votre compte sous-traitant"), "st", "cre", "xxx", "st", $codes, $pass, "", TRUE);
            // Envoi d'email vers le centre de gestion
            envoi_mail("", _("Ouverture d'un compte sous-traitant"), "st", "cre", "xxx", "cdg", $codes, $pass, "", FALSE);
        }
        break;

    // MAJ de la fiche sous-traitant
    case "edit" :
        $edit_ok = TRUE;

        if ((@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 9)) {
            if ($ouvert == FALSE) // Si fermeture de sous-traitant, quelques Contrôles sont nécessaires
            {
                // Vérifie si utilisé dans une fiche bon de travail non close
                if (exist_st_in_ot_ouv($code, FALSE) == TRUE) {
                    $edit_ok = FALSE;
                    $msg = _("Il faut d'abord clore les bons de travail en cours pour d&easactiver ce sous-traitant");
                }

                // Vérifie si utilisé dans une fiche technicien non licencié
                if (exist_st_in_tec_present($code, FALSE) == TRUE) {
                    $edit_ok = FALSE;
                    if ($msg <> "")
                        $msg .= "<br /><br />";
                    $msg .= _("Il faut d'abord licencier les techniciens présents chez ce sous-traitant pour le fermer");
                    $retourliste = FALSE;
                }
            }
        }

        if ($edit_ok == TRUE) {
            if ((@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 9)) {
                // MAJ de la fiche sous-traitant
                $rech = "UPDATE `" . TBST . "` SET `st_datemod`='" . $datea . "', `st_codemod`='" . $codeuser . "', `st_nom`='" . $db->escape($nom) . "',";
                $rech .= " `st_rcs`='" . $db->escape($rcs) . "', `st_ape`='" . $db->escape($ape) . "', `st_tvai`='" . $db->escape($tvai) . "',";
                $rech .= " `st_tcom`='" . $db->escape($tcom) . "', `st_adr1`='" . $db->escape($adr1) . "', `st_adr2`='" . $db->escape($adr2) . "', `st_dep`='" . $dep . "',";
                $rech .= "`st_ville`='" . $ville . "',`st_codepays`='" . $pays . "', `st_codepays`='" . $pays . "', `st_codeadev`='" . $codeadev . "', `st_telf`='" . $telf . "',";
                $rech .= " `st_txttelf`='" . $db->escape($txttelf) . "', `st_fax`='" . $fax . "', `st_txtfax`='" . $db->escape($txtfax) . "', `st_txtent`='" . $db->escape($txtent) . "',";
                $rech .= " `st_resp_civilite`='" . $rcivil . "', `st_resp_prenom`='" . $db->escape($rprenom) . "', `st_resp_nom`='" . $db->escape($rnom) . "',";
                $rech .= " `st_resp_telf`='" . $rtelf . "', `st_resp_telp`='" . $rtelp . "', `st_email`='" . $email . "', `st_emaild`='" . $emaild . "',";
                $rech .= " `st_emailc`='" . $emailc . "', `st_emailt`='" . $emailt . "', `st_heures`='" . $db->escape($heures) . "', `st_web`='" . $db->escape($web) . "',";
                $rech .= " `st_nota`='" . $db->escape($nota) . "', `st_fact`='" . $emetf. "', `st_ouvert`='" . $actif . "', `st_spe`='" . $spe . "'";
                $rech .= "  WHERE `st_code` = '" . $code . "'";
                $db->query($rech);

                // Mise à jour du fichier des zones couvertes
                $rech = "DELETE FROM `" . TBZOC . "` WHERE `zoc_code` = '$code'";
                $db->query($rech);
                $tab_zone = explode("_", $zone);
                foreach ($tab_zone as $idx => $value) {
                    $rech = "INSERT INTO `" . TBZOC . "`";
                    $rech .= " (zoc_code,zoc_codepays,zoc_codedep) VALUES";
                    $rech .= " ('$code','$pays','$value')";
                    $db->query($rech);
                }

                // Mise à jour du fichier des spécialités
                $rech = "DELETE FROM `" . TBSTSP . "` WHERE `stsp_codest` = '$code'";
                $db->query($rech);

                if (count($tab_spec)>0)
                {
                    foreach ($tab_spec as $key => $value) {
                        $rech = "INSERT INTO `" . TBSTSP . "`";
                        $rech .= " (stsp_codest,stsp_codesp,stsp_niveau) VALUES";
                        $rech .= " ('$code','$key','".$value["niv"]."')";
                        $db->query($rech);
                    }
                }
            }

            if (@$_SESSION["niv_log"] == 10) {
                // MAJ de la fiche sous-traitant
                $rech = "UPDATE `" . TBST . "` SET `st_datemod`='" . $datea . "', `st_codemod`='" . $codeuser . "', `st_telf`='" . $telf . "',";
                $rech .= " `st_txttelf`='" . $db->escape($txttelf) . "', `st_fax`='" . $fax . "', `st_txtfax`='" . $db->escape($txtfax) . "', `st_txtent`='" . $db->escape($txtent) . "',";
                $rech .= " `st_resp_civilite`='" . $rcivil . "', `st_resp_prenom`='" . $db->escape($rprenom) . "', `st_resp_nom`='" . $db->escape($rnom) . "',";
                $rech .= " `st_resp_telf`='" . $rtelf . "', `st_resp_telp`='" . $rtelp . "', `st_email`='" . $email . "', `st_emaild`='" . $emaild . "',";
                $rech .= " `st_emailc`='" . $emailc . "', `st_emailt`='" . $emailt . "', `st_heures`='" . $db->escape($heures) . "', `st_web`='" . $db->escape($web) . "'";
                $rech .= "  WHERE `st_code` = '" . $code . "'";
                $db->query($rech);
            }

            // Si agence, on met à jour la fiche agence
            if (trim($codeage) <> "") {
                // MAJ de la fiche Agence
                $rech = "UPDATE `" . TBAGE . "` SET `age_datemod`='" . $datea . "', `age_codemod`='" . $codeuser . "', ";
                $rech .= " `age_nom`='" . $db->escape($nom) . "', `age_rcs`='" . $db->escape($rcs) . "', `age_ape`='" . $db->escape($ape) . "', `age_tvai`='" . $db->escape($tvai) . "',";
                $rech .= " `age_tcom`='" . $db->escape($tcom) . "', `age_adr1`='" . $db->escape($adr1) . "',";
                $rech .= " `age_adr2`='" . $db->escape($adr2) . "', `age_dep`='" . $dep . "',`age_ville`='" . $ville . "', `age_codepays`='" . $pays . "',  `age_codeadev`='" . $codeadev . "',";
                $rech .= "  `age_telf`='" . $telf . "', `age_txttelf`='" . $db->escape($txttelf) . "', `age_fax`='" . $fax . "', `age_txtfax`='" . $db->escape($txtfax) . "',";
                $rech .= "  `age_txtent`='" . $db->escape($txtent) . "', `age_resp_civilite`='" . $rcivil . "', `age_resp_prenom`='" . $db->escape($rprenom) . "',";
                $rech .= " `age_resp_nom`='" . $db->escape($rnom) . "', `age_resp_telf`='" . $rtelf . "', `age_resp_telp`='" . $rtelp . "', `age_email`='" . $email . "', `age_emaild`='" . $emaild . "',";
                $rech .= " `age_emailc`='" . $emailc . "', `age_emailt`='" . $emailt . "', `age_heures`='" . $db->escape($heures) . "', `age_web`='" . $db->escape($web) . "' ";
                $rech .= " WHERE `age_code` = '" . $codeage . "'";
                $db->query($rech);

                // Mise à jour du fichier des zones couvertes
                $rech = "DELETE FROM `" . TBZCC . "` WHERE `zcc_code` = '$codeage'";
                $db->query($rech);
                $tab_zone = explode("_", $zone);
                foreach ($tab_zone as $idx => $value) {
                    $rech = "INSERT INTO `" . TBZCC . "`";
                    $rech .= " (zcc_code,zcc_codepays,zcc_codedep) VALUES";
                    $rech .= " ('$codeage','$pays','$value')";
                    $db->query($rech);
                }
            }

            $msg = _("Fiche modifiée");
            if (trim($codeage) <> "")
                $msg .= "<br />" . _("La fiche agence rattachée a été modifiée");

            $db->disconnect();

            // Envoi d'email vers le centre de gestion
            envoi_mail("", _("Modification d'un compte sous-traitant"), "st", "mod", "xxx", "cdg", $code, "", "", TRUE);
        } else
            $retourliste = FALSE;
        break;

    // Suppression de la fiche sous-traitant
    case "del" :
        $del_ok = TRUE;

        // Vérifie si utilisée dans une fiche intervention
        if (exist_st_in_ot($code, FALSE) == TRUE) {
            $del_ok = FALSE;
            $msg = _("Ce sous-traitant est utilisé dans un ordre de travail") . '<br />' . _("Vous ne pouvez donc pas le supprimer (Il suffit de le passer en mode 'désactivé')");
        }

        // Vérifie si utilisé dans une fiche technicien
        if (exist_st_in_tec($code, FALSE) == TRUE) {
            $del_ok = FALSE;
            if ($msg <> "")
                $msg .= "<br /><br />";
            $msg .= _("Ce sous-traitant est utilisée dans une fiche technicien") . '<br />' . _("Vous ne pouvez donc pas le supprimer (Il suffit de la passer en mode 'fermé')");
        }

        if ($del_ok == TRUE) {
            // SUPPRESSION de la fiche Sous-traitant
            $rech = "DELETE FROM `" . TBST . "` WHERE `st_code` = '$code'";
            $db->query($rech);

            // Suppression du mot de passe rattaché
            $rech = "DELETE FROM `" . TBPW . "` WHERE `pw_code` = '$code'";
            $db->query($rech);

            // Suppression des zones couvertes
            $rech = "DELETE FROM `" . TBZOC . "` WHERE `zoc_code` = '$code'";
            $db->query($rech);

            // Suppression des spécialités
            $rech = "DELETE FROM `" . TBSTSP . "` WHERE `stsp_codest` = '$code'";
            $db->query($rech);

            $db->disconnect();

            // Suppression des logos spécifiques au donneur d'ordres
            $nomfic = $root . REP . "/logos/log" . strtolower($code);
            if (is_file($nomfic . ".png")) {
                if (!unlink($nomfic . ".png")) {
                    if ($msg <> "")
                        $msg .= "<br /><br />";
                    $msg .= _("Problème de suppression du logo png");
                    $retourliste = FALSE;
                }
            }
            if (is_file($nomfic . ".gif")) {
                if (!unlink($nomfic . ".gif")) {
                    if ($msg <> "")
                        $msg .= "<br /><br />";
                    $msg .= _("Problème de suppression du logo gif");
                    $retourliste = FALSE;
                }
            }
            $msg = _("Fiche supprimée");
            if (trim($codeage) <> "")
                $msg .= "<br />" . _("La fiche agence rattachée n'a pas été modifiée");
        } else
            $retourliste = FALSE;
        break;

    default :
        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 _("Fiche Sous-traitant"); ?></title>

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

    <script type="text/javascript">
        <!--
        function init_all() {
            init_Body();
            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 ((@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 9)) {
    $url_retour = "st_lst.php";
    if ($td == "add")
        $url_retour = "logo_maj.php?td=st";
}
if (@$_SESSION["niv_log"] == 10)
    $url_retour = "index.php";

if ($retourliste == FALSE)
{
    exec_func_js("warn_txt('" . str_escape($msg) . "')");
    pop_ret_auto('', '', $url_retour);
}
else
    pop_ret_auto($msg, 'ok', $url_retour);

include_once("pied.php");
?>
</body>
</html>