<?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
 ****************************************************************************************/

/***************************************************/
/* Récupération ss-traitant en fonction spécialité */
/***************************************************/

session_start();
sleep(1);
if (array_key_exists("sp", $_REQUEST)) {
    $tomorrow = 0; //60*60*24; // en nb de secondes
    header("Cache-Control: max-age=$tomorrow");
    print_plain();
} else {
    print "Usage : $_SERVER[PHP_SELF]?sp=spécialités&nsp=niveaux";
}

/** Liste des sous-traitant en fonction pays, département, et spécialité **/

function print_plain()
{
    require_once("../lib/gettext/gettext.inc");
    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");

    header("Content-type: text/html; charset=UTF-8");
    // Nettoyage de la chaine de paramètres
    /*
    $str_prm=$_REQUEST["sp"];
    $tab_prm=explode("&",$str_prm);
    $tab_prm[1]=str_replace('nsp=','',$tab_prm[1]);
    */

    // Création des tableaux de paramètres
    $tab_tmp_sp = explode('_', $_REQUEST["sp"]);
    $tab_sp_niv = explode('_', $_REQUEST["nsp"]);
    $pays = $tab_tmp_sp[0];
    $dep = $tab_tmp_sp[1];

    $tab_sp = [];
    for ($i = 2; $i < count($tab_tmp_sp); $i++) {
        $tab_sp[] = $tab_tmp_sp[$i];
    }

    // Traitement de retour des résultats
    $result = [];
    if ((count($tab_sp) > 0) AND (count($tab_sp_niv) > 0)) {
        $sp = get_sp($pays, $dep, $tab_sp, $tab_sp_niv);
        // On se connecte a la base
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
        foreach ($sp as $value) {
            $rech2 = "SELECT " . TBST . ".st_code,st_nom FROM `" . TBST . "`";
            $rech2 .= " WHERE st_code='" . $db->escape($value) . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);

            if ($row2) {
                $row2 = encode_str($row2);
                extract($row2);
                $result[] = $st_code . "=" . $st_nom;
            }
        }
        $db->disconnect();
    }
    print implode(";", $result);
}

/**
 * @param $payscli
 * @param $depcli
 * @param $tab_sp
 * @param $tab_sp_niv
 * @return array
 */
function get_sp($payscli, $depcli, $tab_sp, $tab_sp_niv)
{

    require_once("../lib/gettext/gettext.inc");
    include_once("../inc/config.inc.php");
    include_once("../inc/func_txt.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");

    // On se connecte a la base
    $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

    // On cree le resultat

    // Création du tableau des sous-traitants possibles par combinaison spécialité/niveau
    $tab_st_spniv = [];

    $rech2 = "SELECT DISTINCT stsp_codest FROM `" . TBSTSP . "`";

    // On filtre sur les spécialités
    if (in_array("*", $tab_sp) == FALSE) {
        // WHERE existe ?
        if (!stristr($rech2, "WHERE "))
            $rech2 .= " WHERE (";
        else
            $rech2 .= " AND (";

        // *** Filtrage
        if (count($tab_sp) > 0) {
            // Construction de la chaîne de recherche
            foreach ($tab_sp as $value) {
                $rech2 .= " stsp_codesp = '" . $db->escape($value) . "' OR";
            }
            // Suppression du dernier 'OR'
            $rech2 = substr($rech2, 0, strlen($rech2) - 3);
            $rech2 .= ")";
        }
        // *** Fin de Filtrage
    }

    // On filtre sur les niveaux
    if (in_array("*", $tab_sp_niv) == FALSE) {
        // WHERE existe ?
        if (!stristr($rech2, "WHERE "))
            $rech2 .= " WHERE (";
        else
            $rech2 .= " AND (";

        // *** Filtrage
        if (count($tab_sp_niv) > 0) {
            // Construction de la chaîne de recherche
            foreach ($tab_sp_niv as $value) {
                $rech2 .= " stsp_niveau >= '" . $db->escape($value) . "' OR";
            }
            // Suppression du dernier 'OR'
            $rech2 = substr($rech2, 0, strlen($rech2) - 3);
            $rech2 .= ")";
        }
        // *** Fin de Filtrage
    }

    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $tab_st_spniv[] = $stsp_codest;
        }
    }

    // Création du tableau des sous-traitants possibles par zone de chalandise
    $tab_st_zc = [];

    $rech2 = "SELECT DISTINCT " . TBZOC . ".zoc_code FROM `" . TBZOC . "`, `" . TBST . "`";
    $rech2 .= " WHERE " . TBZOC . ".zoc_codepays='" . $db->escape($payscli) . "' AND " . TBZOC . ".zoc_codedep='" . $db->escape($depcli) . "'";
    $rech2 .= " AND " . TBST . ".st_ouvert='1'";
    $rech2 .= " AND " . TBZOC . ".zoc_code=" . TBST . ".st_code";
    $rech2 .= " ORDER BY " . TBST . ".st_nom";

    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $tab_st_zc[] = $zoc_code;
        }
    }
    $db->disconnect();

    $result = array_intersect($tab_st_spniv, $tab_st_zc);

    return $result;
}

?>