<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.2
 *
 * Copyright (C) 2006-2015  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");

/**************************************************/
/* Fonctions pour les accès aux fichiers produits */
/* et fichiers rattachés                          */
/**************************************************/

/**
 * Nombre d'articles
 *
 * @param bool $open
 *
 * @return null
 */

function nb_pdt($open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDT . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Lecture d'un enregistrement produit
 *
 * @param      $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_pdt($code, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDT . "` WHERE `pdt_code` = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification de la présence d'un article dans une fiche intervention
 *
 * @param      $code
 * @param bool $open
 *
 * @return bool
 */
function exist_pdt_in_int($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTI . "` WHERE `pdti_codepdt` = '" . $db->escape($code) . "'";
    $nbres = $db->get_var($rexist);
    if ($nbres <> 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Lit un article dans une fiche intervention
 *
 * @param      $codep
 * @param      $codei
 * @param bool $open
 * @return array|null
 */
function lit_enr_pdt_in_int($codep, $codei, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDTI . "` WHERE `pdti_codepdt` = '" . $db->escape($codep) . "' AND `pdti_codeint` = '$codei'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification de la présence d'un produit dans une fiche intervention non close
 *
 * @param      $code
 * @param bool $open
 *
 * @return bool
 */
function exist_pdt_in_int_ouv($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT " . TBPDTI . ".pdti_codepdt, " . TBPDTI . ".pdti_codeint, " . TBINT . ".int_code, ";
    $rech2 .= TBINT . ".int_datefin FROM `" . TBPDTI . "`, `" . TBINT . "` WHERE (" . TBPDTI . ".pdti_codepdt = '" . $db->escape($code) . "' AND " . TBPDTI . ".pdti_codeint = " . TBINT . ".int_code AND " . TBINT . ".int_datefin = '0000-00-00')";
    $rows = $db->get_results($rech2, ARRAY_A);
    if ($rows)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Récupère un article dans le tableau des articles historiques interventions
 *
 * @param $codep
 *
 * @return array
 */
function recup_pdt_tab_in_inth($codep)
{
    global
    $_SESSION;

    $lig_recup = [];

    if (count($_SESSION["pdtih"]) > 0) {
        foreach ($_SESSION["pdtih"] as $row) {
            if ($row["pdtih_codepdt"] == $codep)
                $lig_recup = $row;
        }
    }

    return $lig_recup;
}

/**
 * Retourne un tableau avec les enregistrements produits rattachés un historique intervention
 *
 * @param      $codeint
 * @param      $idinth
 * @param bool $open
 *
 * @return array
 */
function give_tab_pdtih($codeint, $idinth, $open = TRUE)
{
    global
    $db;
    $tab_pdtih = [];

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDTIH . "` WHERE `pdtih_codeint` = '$codeint' AND `pdtih_idhisto` = '$idinth'";
    $rech2 .= " ORDER BY pdtih_id";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            $row2 = encode_str($row2);
            $tab_pdtih[] = $row2;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $tab_pdtih;
}

/**
 * Création du code Javascript pour affichage des taxes du produit
 *
 * @param $id_html
 * @param $td
 * @param $code
 * @param $from
 * @param bool $open
 */
function cre_html_tpfa($id_html, $td, $code, $from, $open = TRUE)
{
    global
    $db,
    $_SESSION;

    // Création de la chaine HTML
    $str_html = '';

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

    if (nb_tpf_in_pdt($code,FALSE) > 0) {

        $str_html = "<table class=\"Ltable\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";

        // Création entête
        $str_html .= "<th>";
        $str_html .= _("Code");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Désignation");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Valeur TTC");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Forfait ?");
        $str_html .= "</th>";

        if ($td == "edit") {
            $str_html .= "<th>";
            $str_html .= _("Cliquer");
            $str_html .= "</th>";
        }

        // Lignes du tableau
        $rech = "SELECT * FROM `" . TBTPFA . "` WHERE tpfa_codepdt='" . $code . "' ORDER BY 'tpfa_id'";
        $rows = $db->get_results($rech, ARRAY_A);

        $i = 0;

        foreach ($rows as $row) {
            $row = encode_str($row);
            extract($row);

            if ($i % 2 == 0)
                $str_html .= "<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter1'\" class=\"TRalter1\">";
            else
                $str_html .= "<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter2'\" class=\"TRalter2\">";

            // Code Taxe
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $tpfa_codetpf;
            $str_html .= "</td>";

            $rech2 = "SELECT tpf_desc,tpf_pour,tpf_typmt,tpf_asaisir FROM `" . TBTPF . "` WHERE tpf_code='" . $row["tpfa_codetpf"] . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);

            if ($row2)
                extract($row2);

            // Désignation
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $tpf_desc;
            $str_html .= "</td>";

            // Valeur
            if ($tpf_pour == TRUE) {
                $txt = full_num_format($tpfa_mt, '', '', FALSE,'',FALSE);
                $txt .= "%";
            }
            else
                $txt = full_num_format($tpfa_mt, '', '', TRUE,'',FALSE);
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Unique ?
            if ($tpf_typmt == FALSE)
                $txt = _("Non");
            else
                $txt = _("Oui");
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            if ($td == "edit") {
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                if ($tpf_asaisir == TRUE) {
                    $urledittpf = "tpfa_maj.php?td=edit&cp=" . $tpfa_codepdt . "&tpf=" . $tpfa_codetpf;
                    /// $str_html .= cre_falselnk_img('', 'tpfa_edit_'.$tpfa_id, 'span', '', _("Edition"), 'lnkpop', $urledittpf, '../img/edit.png', 900 , 500, true);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urledittpf."','tpfa_edit_".$tpfa_id."',900,500,'yes')\")>";
                    $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                    $str_html .= " ";
                }
                $urldeltpf = "tpfa_maj.php?td=del&cp=" . $row["tpfa_codepdt"] . "&tpf=" . $row["tpfa_codetpf"];
                // $str_html .= cre_falselnk_img('', 'tpfa_del_'.$tpfa_id, 'span', '', _("Suppression"), 'lnkpop', $urldeltpf, '../img/del.png', 900 , 500, true);
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldeltpf."','tpfa_del_".$tpfa_id."',900,500,'yes')\")>";
                $str_html .= '<img src="../img/del.png" border="0" align="absmiddle" title="' . _("Suppression") . '"></a>';
                $str_html .= " ";
                $str_html .= "</td>";
            }

            $str_html .= "</tr>";
            $i++;
        }
        // Fermeture de la table
        $str_html .= "</table>";
    }

    if ($open == TRUE)
        $db->disconnect();

    echo 'function tbtpfa() {';
    echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
    echo $from . "$('#" . $id_html . "').html('" . str_replace("'", "\'", $str_html) . "');";
    echo '}';
    echo '}';
}

/**
 * Récupère un article dans le tableau des taxes historiques interventions
 *
 * @param $codet
 *
 * @return array
 */
function recup_tpf_tab_in_inth($codet)
{
    global
    $_SESSION;

    $lig_recup = [];

    if (count($_SESSION["tpfih"]) > 0) {
        foreach ($_SESSION["tpfih"] as $row) {
            if ($row["tpfih_codetpf"] == $codet)
                $lig_recup = $row;
        }
    }

    return $lig_recup;
}

/**
 * Retourne un tableau avec les enregistrements taxes rattachées un historique intervention
 *
 * @param      $codeint
 * @param      $idinth
 * @param bool $open
 *
 * @return array
 */
function give_tab_tpfih($codeint, $idinth, $open = TRUE)
{
    global
    $db;
    $tab_tpfih = [];

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBTPFIH . "` WHERE `tpfih_codeint` = '$codeint' AND `tpfih_idhisto` = '$idinth'";
    $rech2 .= " ORDER BY tpfih_id";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            $row2 = encode_str($row2);
            $tab_tpfih[] = $row2;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $tab_tpfih;
}

// Familles

/**
 * Vérification du nombre de familles produits
 *
 * @param bool $open
 *
 * @return null
 */
function nb_fam($open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBFAM . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();
    return $nbexist;
}

// Unités de vente

/**
 * Vérification du nombre d'unités de vente
 *
 * @param bool $open
 *
 * @return null
 */
function nb_pdtu($open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTU . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}
