<?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");

include_once("../inc/func.inc.php");
include_once("../inc/func_date.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_time.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../inc/fic_cli.inc.php");
include_once("../inc/fic_cocl.inc.php");
include_once("../inc/fic_droits.inc.php");
include_once("../inc/fic_int.inc.php");
include_once("../inc/fic_statut.inc.php");
include_once("../inc/lst.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"]);
$_SESSION["typ_filtres"] = "coclhd";

// Variables Formulaire
fix_magic_quotes();
$_GET = clean_str($_GET);

$orig = $_GET['or']; // Récupération origine de l'appel
$cc = $_GET['cc']; // Récupération code Client
$search = $_GET['search']; // Récupération clef de recherche

$pbm_cocl = FALSE;

if ($cc <> "") {
    // Récupération des informations clients
    $row = lit_enr_cli($cc, TRUE);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
    } else
        $pbm_cocl = 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 _("Historique des Contrats"); ?></title>

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

    <script type="text/javascript">
        <!--
        function init_all() {
            init_Body();
            add_func_click('ferm', 'sclose', '');
            init_autosubmit('search', 'change', 'dde_cocl');
            Focus_first();
        }

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

</head>

<body>

<p align="center"><span class="titrepage"><?PHP echo _("HISTORIQUE DES CONTRATS"); ?></span></p>
<?PHP
if ($pbm_cocl == FALSE) {
    ?>
    <p align="center"><span class="titre_gras">
<?php
if ($cli_ste <> "")
    echo $cli_ste;
else
    echo $cli_civilite . " " . $cli_prenom . " " . $cli_nom;
echo ' ('._("Compte").' : ' . $cc . ')';
?>
</span></p>

    <!-- Formulaire de demande du Numéro de contrat -->
    <form name="dde_cocl" id="dde_cocl" method="GET" action="coclhd_lst.php">
        <input name="cc" type="hidden" id="cc" value="<?PHP echo $cc ?>">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td>
                    <?PHP
                    echo '<select name="search" size="1" id="search">';
                    // Création de la liste des contrats
                    echo '<option value=""';
                    if ($co == "")
                        echo ' selected';
                    echo '>'._("-- Choisissez un contrat --").'</option>';

                    $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
                    $rech = "SELECT * FROM `" . TBCOCL . "` WHERE `cocl_codecli` = '" . $db->escape($cc) . "' ORDER BY cocl_code";
                    $rows = $db->get_results($rech, ARRAY_A);

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

                            $rech2 = "SELECT * FROM `" . TBCO . "` WHERE co_code = '" . $cocl_codeco . "'";
                            $row2 = $db->get_row($rech2, ARRAY_A);
                            if ($row2) {
                                $row2 = encode_str($row2);
                                extract($row2);
                            }
                            $txt_cocl = $cocl_code . " - " . $co_nom . " (";
                            if ($cocl_typh == 1)
                                $txt_cocl .= _("Quota horaire");
                            else
                                $txt_cocl .= _("Classique");
                            if ($cocl_delai <> 0)
                                $txt_cocl .= ", " . $cocl_delai . "h";
                            else
                                $txt_cocl .= ", " . _("Pas de délai");
                            if ($cocl_datef <> "0000-00-00")
                                $txt_cocl .= ", " . _("echéance") . " " . datetolocal($cocl_datef);
                            else
                                $txt_cocl .= ", " . _("sans echéance") . " ";
                            $txt_cocl .= ")";

                            if (datetolocal($cocl_datefin) <> "")
                                $txt_cocl .= " - " . _("CLOT");
                            else
                                $txt_cocl .= " - " . _("OUVERT");
                            if (datetolocal($cocl_datesig) == "")
                                $txt_cocl .= " - " . _("A SIGNER");
                            else
                                $txt_cocl .= " - " . _("SIGNE");

                            echo '<option value="' . $cocl_code . '"';
                            if ($cocl_code == $search)
                                echo ' selected';
                            echo '>' . $txt_cocl . '</option>';
                        }
                    }
                    $db->disconnect();
                    echo '</select>';
                    ?>
                </td>
            </tr>
        </table>
    </form>
    <!-- Fin de formulaire de demande du Numéro de contrat -->
    <?PHP
    if (isset($_GET['search']) && !empty($_GET['search'])) {
        $row = lit_enr_cocl($_GET['search']);
        if (is_array($row)) {
            $row = encode_str($row);
            extract($row);
            $nbh = sec_heure($cocl_nbs, 3, TRUE);
            $deduit = tps_trav_clot_sec($_GET['search'], TRUE);
            $a_deduire = tps_trav_non_clot_sec($_GET['search'], TRUE);
            $soldes = solde_contrat_sec($_GET['search'], TRUE);
            $solde_reel = solde_reel_contrat_sec($_GET['search'], TRUE);
            $apports = apport_vers_contrat_sec($_GET['search'], TRUE);
            $reports = report_depuis_contrat_sec($_GET['search'], TRUE);

            echo "<br />";
            echo "<div class=\"annot_gras_it\">";
            echo _("Détail des interventions");
            echo "<span class=\"annot_petit_it\">";
            echo ' ('._("laisser souris sur les icônes pour les détails").')';
            echo "</span>";
            echo "</div>";

            $i = 0;
            // *** Affichage de la table
            echo "<table class=\"Mtable\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">\n";

            // Création entête
            titlst($coclh_titre_col);

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

            // Détail des interventions
            $rech = cree_strrechlstcoclh();
            $rech .= crestr_triord($coclh_titre_col, "int_code", FALSE, $limit);

            $rows = $db->get_results($rech, ARRAY_A);

            if (($rows) AND (count($rows) > 0)) {
                $offert = FALSE;
                $indice = FALSE;

                foreach ($rows as $row) {
                    $row = encode_str($row);
                    // Affichage résumé Contrat Client

                    // création de l'entête de ligne (TR)
                    creetrlst($i);

                    // Récupération du total travaillé
                    $tpstotalsec = 0;
                    $tpsoffsec = 0;
                    $tpsretsec = 0;

                    $rech2 = "SELECT * FROM `" . TBINTH . "` WHERE `inth_codeint`= '" . $row["int_code"] . "'";
                    $rows2 = $db->get_results($rech2, ARRAY_A);
                    if (($rows2) AND (count($rows2) > 0)) {
                        foreach ($rows2 as $row2) {
                            $row2 = encode_str($row2);
                            $tpspassesec = diff_time_sec($row2["inth_heurea"], $row2["inth_heured"]);
                            // Calcul du temps réellement passé
                            $tpstotalsec = $tpstotalsec + $tpspassesec;
                            // C'est du temps offert ?
                            // Oui : on ajoute juste au temps total offert
                            // Non : on ajoute au temps total retenu
                            if ($row2["inth_offert"] == 1) {
                                // Calcul du temps offert
                                $tpsoffsec = $tpsoffsec + $tpspassesec;
                                $offert = TRUE;
                            } else {
                                // Calcul du temps retenu
                                $ind_coeff = 1;
                                if ($row2["inth_codeind"] == "-1")
                                    $tpsretsec = $tpsretsec + $tpspassesec;
                                else {
                                    $indice = TRUE;
                                    $row3 = lit_enr_ind($row2["inth_codeind"], FALSE);
                                    if (is_array($row3)) {
                                        $row3 = encode_str($row3);
                                        extract($row3);
                                        $tpsretsec = $tpsretsec + ($tpspassesec * $ind_coeff);
                                    }
                                }
                            }
                        }
                    }

                    // Si un utilisateur a quitté avant de sauver (bien qu'ayant modifié le détail horaire),
                    // on remet en état car seul le détail horaire et technicien enregistré est valable
                    if ($row["int_durees"] <> $tpsretsec) {
                        $rech2 = "UPDATE `" . TBINT . "` SET `int_datemod`='" . $datea . "', `int_codemod`='" . $codeuser . "',`int_durees`='" . $tpsretsec . "'";
                        $rech2 .= " WHERE `int_code` = '" . $db->escape($ci) . "'";
                        $db->query($rech2);
                        $row["int_durees"] = $tpsretsec;
                    }

                    echo "<td align=\"center\">";
                    echo $row["int_code"];
                    if ($tpstotalsec <> $tpsretsec)
                        echo ' <a href="#" class="popa"><img src="../img/clock.png" alt="'._("Détail").'" class="icones"><span>'._("Temps réel").' : ' . heure_to_hhmm(sec_heure($tpstotalsec, 3, TRUE)) . '</span></a>';
                    /*
                    else
                        echo ' <img src="../img/none.gif" style="width:16px;">';
                    */
                    if ($tpsoffsec <> 0)
                        echo ' <a href="#" class="popa"><img src="../img/gift.png" alt="'._("Détail").'" class="icones"><span>'._("Temps offert").' : ' . heure_to_hhmm(sec_heure($tpsoffsec, 3, TRUE)) . '</span></a>';
                    /*
                    else
                        echo ' <img src="../img/none.gif" style="width:16px;">';
                    */
                    if (datetolocal($row["int_datefin"]) == "")
                        echo ' <a href="#" class="popa"><img src="../img/out.png" alt="'._("Détail").'" class="icones"><span>'. _("Intervention à déduire") . '</span></a>';
                    /*
                    else
                        echo ' <img src="../img/none.gif" style="width:16px;">';
                    */
                    $url = "int_maj.php?td=edit&ci=" . $row["int_code"] . "&cc=" . $row["coclh_codecli"] . "&ca=" . $row["int_codeage"];
                    $desc = _("Voir fiche d'intervention");
                    echo '<a href="javascript:void(0)" onClick="javascript: window.opener.location=\''.$url.'\'; self.close();")>';
				    echo '<img src="../img/hcon.png" title="'.$desc.'" class="icones">';
				    echo '</a>';
                    echo "</td>\n";
                    echo "<td align=\"center\">";
                    echo datetolocal($row["int_datedde"]);
                    echo "</td>\n";
                    echo "<td align=\"center\">";
                    if (datetolocal($row["int_daterdv"]) <> "")
                        echo datetolocal($row["int_daterdv"]);
                    else
                        echo "-";
                    echo "</td>\n";
                    echo "<td align=\"center\">";
                    if (datetolocal($row["int_datefin"]) <> "")
                        echo datetolocal($row["int_datefin"]);
                    else
                        echo "-";
                    echo "</td>\n";
                    echo "<td align=\"center\">" . $row["int_codeage"] . "</td>\n";
                    echo "<td align=\"center\">";
                    if ($tpsretsec <> 0)
                        echo heure_to_hhmm(sec_heure($tpsretsec, 3, TRUE));
                    else
                        echo "-";
                    echo "</td>\n";

                    // Affichage icône Statut

                    echo "<td align=\"center\">";

                    echo str_div_ico_statut($row["int_codestatut"], '', FALSE);

				 echo "</td>\n";
		
				 echo "</tr>\n";
			 // Fin affichage résumé Contrat Client
				
				$i++;    
			}
            } else {
                creetrlst($i);
                echo '<td colspan="7" align="center">' . _("Aucun historique interventions sur ce contrat") . '</td>';
                echo "</tr>\n";
            }

            // Totaux
            creetrlst($i);
            echo "<td colspan=\"7\" align=\"center\">&nbsp;</td>\n";
            echo "</tr>\n";

            $i++;
            creetrlst($i);
            echo "<td colspan =\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Temps déjà utilisé") . " : </td>\n";
            echo "<td align=\"center\" class=\"annot_std_gras\">";
            if ($deduit <> 0)
                echo heure_to_hhmm(sec_heure($deduit, 3, TRUE));
            else
                echo "-";
            echo "</td>\n";
            echo "<td align=\"center\">&nbsp;</td>\n";
            echo "</tr>\n";

            $i++;
            creetrlst($i);
            echo "<td colspan =\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Temps à déduire") . " : </td>\n";
            echo "<td align=\"center\" class=\"annot_std_gras\">";
            if ($a_deduire <> 0)
                echo heure_to_hhmm(sec_heure($a_deduire, 3, TRUE));
            else
                echo "-";
            echo "</td>\n";
            echo "<td align=\"center\">&nbsp;</td>\n";
            echo "</tr>\n";

            $i++;
            creetrlst($i);
            echo "<td colspan =\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Sous-total temps déductible") . " : </td>\n";
            echo "<td style=\"border-top:thin solid;\" align=\"center\" class=\"annot_std_gras\">";
            if (($deduit + $a_deduire) <> 0)
                echo heure_to_hhmm(sec_heure($deduit + $a_deduire, 3, TRUE));
            else
                echo "-";
            echo "</td>\n";
            echo "<td align=\"center\">&nbsp;</td>\n";
            echo "</tr>\n";

            $i++;
            creetrlst($i);
            echo "<td colspan=\"7\" align=\"center\">&nbsp;</td>\n";
            echo "</tr>\n";

            if ($cocl_typh == 1) {
                $i++;
                creetrlst($i);
                echo "<td colspan=\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Quota initial d'heures") . " : </td>\n";
                echo "<td align=\"center\" class=\"annot_std_gras\">";
                echo substr($nbh, 0, 5);
                echo "</td>\n";
                echo "<td align=\"center\">&nbsp;</td>\n";
                echo "</tr>\n";

                if ($apports <> 0) {
                    $i++;
                    creetrlst($i);
                    echo "<td colspan=\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Total apports") . " (<a href=\"#detapp\">" . _("cf détails apports") . "</a>) : </td>\n";
                    echo "<td align=\"center\" class=\"annot_std_gras\">";
                    echo heure_to_hhmm(sec_heure($apports, 3, TRUE));
                    echo "</td>\n";
                    echo "<td align=\"center\">&nbsp;</td>\n";
                    echo "</tr>\n";
                }

                if ($reports > 0) {
                    $i++;
                    creetrlst($i);
                    echo "<td colspan=\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Total reports") . " (<a href=\"#detrep\">" . ("cf détails reports") . "</a>) : </td>\n";
                    echo "<td align=\"center\" class=\"annot_std_gras\">";
                    echo "-" . heure_to_hhmm(sec_heure($reports, 3, TRUE));
                    echo "</td>\n";
                    echo "<td align=\"center\">&nbsp;</td>\n";
                    echo "</tr>\n";
                }

                $i++;
                creetrlst($i);
                echo "<td colspan=\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Temps disponible") . " : </td>\n";
                echo "<td style=\"border-top:thin solid;\" align=\"center\" class=\"annot_std_gras\">";
                $tpsdispo = $cocl_nbs + $apports - $reports;
                echo heure_to_hhmm(sec_heure($tpsdispo, 3, TRUE));
                echo "</td>\n";
                echo "<td align=\"center\">&nbsp;</td>\n";
                echo "</tr>\n";

                $i++;
                creetrlst($i);
                echo "<td colspan=\"7\" align=\"center\">&nbsp;</td>\n";
                echo "</tr>\n";

                $i++;
                creetrlst($i);
                echo "<td colspan=\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Solde hors interventions en cours") . " : </td>\n";
                echo "<td align=\"center\" class=\"annot_std_gras\">";
                echo heure_to_hhmm(sec_heure($soldes, 3, TRUE));
                echo "</td>\n";
                echo "<td align=\"center\">&nbsp;</td>\n";
                echo "</tr>\n";

                $i++;
                creetrlst($i);
                echo "<td colspan=\"5\" align=\"right\" class=\"annot_std_gras\">" . _("Solde réél théorique (inclus 'à déduire')") . " : </td>\n";
                echo "<td align=\"center\" class=\"annot_std_gras\">";
                echo heure_to_hhmm(sec_heure($solde_reel, 3, TRUE));
                echo "</td>\n";
                echo "<td align=\"center\">&nbsp;</td>\n";
                echo "</tr>\n";

                // Si contrat clot, on dit vers quel contrat cela a été reporté
                if (datetolocal($cocl_datefin) <> "") {
                    $rech = "SELECT coclr_cocldest FROM `" . TBCOCLR . "` WHERE coclr_coclori = '" . $_GET['search'] . "' AND coclr_nbsrep = " . $solde_reel . "";
                    $row = $db->get_row($rech, ARRAY_A);
                    if ($row) {
                        $row = encode_str($row);
                        extract($row);
                        $i++;
                        creetrlst($i);
                        echo "<td colspan=\"5\" align=\"right\" class=\"annot_gras_it\">" . _("Solde reporté vers contrat") . " </td>\n";
                        echo "<td align=\"center\" class=\"annot_gras_it\">";
                        echo $coclr_cocldest;
                        echo "</td>\n";
                        echo "<td align=\"center\">&nbsp;</td>\n";
                        echo "</tr>\n";
                    }
                }
            }
            echo "</table>\n";
            // *** Fin affichage de la table

            // création de la liste des apports affectés à ce contrat (s'il y en a)
            $rech = "SELECT * FROM `" . TBCOCLR . "` WHERE coclr_cocldest = '" . $_GET['search'] . "' ORDER BY coclr_codeint";
            $rows = $db->get_results($rech, ARRAY_A);

            if (($rows) AND (count($rows) > 0)) {
                echo "<br />";
                echo "<div class=\"annot_gras_it\">";
                echo '<a id="detapp"></a>';
                echo _("Détails des apports affectés à ce contrat");
                echo "</div>";

                $totalreport = 0;

                // *** Affichage de la table
                echo "<table class=\"Mtable\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">\n";

                // création de l'entête de la table "détails reports"
                echo "<th>";
                echo _("Libellé");
                echo "</th>\n";
                echo "<th>";
                echo _("Durée");
                echo "</th>\n";

                $j = 0;

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

                    // création de l'entête de ligne (TR)
                    creetrlst($j);

                    echo "<td>\n";
                    if ($coclr_nbsrep > 0)
                        $txt = _("Report non").' ';
                    else
                        $txt = _("Déduction sur").' ';
                    $txt .= _("consommé du contrat") . " " . $coclr_coclori;
                    if ($coclr_codeint <> '')
                        $txt .= " (" . _("Intervention") . " " . $coclr_codeint . ")";
                    else
                        $txt .= " (" . _("Clôture manuelle") . ")";
                    echo $txt;
                    echo "</td>\n";

                    echo "<td align=\"center\">\n";
                    echo heure_to_hhmm(sec_heure($coclr_nbsrep, 3, TRUE));
                    $totalreport = $totalreport + $coclr_nbsrep;
                    echo "</td>\n";

                    echo "</tr>\n";

                    $j++;
                }

                // Total
                creetrlst($j);

                echo "<td align=\"right\" class=\"annot_std_gras\">" . _("Total général") . " :</td>\n";

                echo "<td align=\"center\" class=\"annot_std_gras\">\n";
                echo heure_to_hhmm(sec_heure($totalreport, 3, TRUE));
                echo "</td>\n";

                echo "</tr>\n";

                echo "</table>\n";
                // Fin affichage table détails reports
            }

            // création de la liste des reports affectés depuis ce contrat (s'il y en a)
            $rech = "SELECT * FROM `" . TBCOCLR . "` WHERE coclr_coclori = '" . $_GET['search'] . "' AND coclr_nbsrep > 0 ORDER BY coclr_codeint";
            $rows = $db->get_results($rech, ARRAY_A);

            if (($rows) AND (count($rows) > 0)) {
                echo "<br />";
                echo "<div class=\"annot_gras_it\">";
                echo '<a id="detrep"></a>';
                echo _("Détails des reports effectués depuis ce contrat");
                echo "</div>";

                $totalreport = 0;

                // *** Affichage de la table
                echo "<table class=\"Mtable\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">\n";

                // création de l'entête de la table "détails reports"
                echo "<th>";
                echo _("Détail des reports");
                echo "</th>\n";
                echo "<th>";
                echo _("Durée");
                echo "</th>\n";

                $j = 0;

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

                    // création de l'entête de ligne (TR)
                    creetrlst($j);

                    echo "<td>\n";
                    if ($coclr_nbsrep > 0)
                        $txt = _("Report non") . " ";
                    else
                        $txt = _("Déduction sur-");
                    $txt .= _("consommé vers contrat") . " " . $coclr_cocldest;
                    if ($coclr_codeint <> '')
                        $txt .= " (" . _("Intervention") . " " . $coclr_codeint . ")";
                    else
                        $txt .= " (" . _("Clôture manuelle") . ")";
                    echo $txt;
                    echo "</td>\n";

                    echo "<td align=\"center\">\n";
                    echo heure_to_hhmm(sec_heure($coclr_nbsrep, 3, TRUE));
                    $totalreport = $totalreport + $coclr_nbsrep;
                    echo "</td>\n";

                    echo "</tr>\n";

                    $j++;
                }

                // Total
                creetrlst($j);

                echo "<td align=\"right\" class=\"annot_std_gras\">" . _("Total général") . " :</td>\n";

                echo "<td align=\"center\" class=\"annot_std_gras\">\n";
                echo heure_to_hhmm(sec_heure($totalreport, 3, TRUE));
                echo "</td>\n";

                echo "</tr>\n";

                echo "</table>\n";
                // Fin affichage table détails reports

            }
        }
        $db->disconnect();
    } else
        echo "<br /><span class=\"annot_std_gras\">" . _("Merci de choisir un contrat") . "</span><br />";

    ?>
    <br />
    <div align="center">
        <input name="ferm" type="button" class="bton_std" id="ferm" value="<?PHP echo _("Fermer la fenêtre"); ?>">
    </div>
<?PHP
} else
    close_fen_auto('', 'fscomp');
?>
</body>
</html>
