<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.4
 *
 * Copyright (C) 2006-2016  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) {
    header('Location: ../index.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/fic_droits.inc.php');
include_once('../inc/fic_ot.inc.php');
include_once('../inc/fic_plan.inc.php');
include_once('../inc/fic_tec.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(valsession('code_log'));

$enr_ok = FALSE;
$pbm_oth = FALSE;
$pbm_enr_oth = FALSE;
$action_to_do = '';
$tecr = '';
$td = 'add'; // Le mode par défaut est en ajout
$tdh = 'add'; // Mode $td pour l'historique affiché (si $id <>0)

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

if (isset($_GET['co'])) {
    $codeot = valget('co');
} else {
    $codeot = valpost('co');
}

if (isset($_GET['td'])) {
    $td = valget('td');
    if (($td <> 'edit') AND ($td <> 'del')) {
        $pbm_oth = TRUE;
    } else {
        $tdh = $td;
    }
}
$id = 0;
if (isset($_GET['id'])) {
    $id = (int)valget('id');
} else {
    $id = (int)valpost('id');
}

// Lecture des paramètres planning
$row = lit_enr_pprm();
if ($row) {
    $row = encode_str($row);
    extract($row);
}


$url_lst = 'oth_maj.php?co=' . $codeot . '&cc=' . $cc . '&si=' . $si . '&ca=' . $ca . '&tr=' . $tecr;
if ($codeot <> '') {
    $row = lit_enr_ot($codeot);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
    } else {
        $pbm_oth = TRUE;
    }

    // Si pas d'enregistrement de détail horaire, on ne peut que ajouter
    if ((nb_oth($codeot) == 0) AND CheckNivLog('10-11-9')) {
        $td = 'add';
    }

    // Si intervention close ou si client/donneurs d'ordres, on ne peut que voir
    if (datetolocal($ot_datefin) <> '') {
        $td = 'view';
    }

    // vérification tentative de hack d'un sous-traitant
    if (CheckNivLog('10-11') AND ($ot_codest <> valsession('code_st'))) {
        $pbm_oth = TRUE;
    }
} else {
    $pbm_oth = TRUE;
}

if ($pbm_oth == FALSE) {
    if ($id > 0) {
        $row = lit_enr_oth($id);
        if (is_array($row)) {
            extract($row);
            $oth_heurea = substr($oth_heurea, 0, 5);
            $oth_heured = substr($oth_heured, 0, 5);
            $datef = datetolocal($oth_date);
        }
    }
}

if ($pbm_oth == FALSE) {
    switch ($_POST['nbutton']) {
        case 'enr' :
            $action_to_do = 'add';
            break;
        case 'val' :
            $action_to_do = 'valid';
            break;
        case 'del' :
            $action_to_do = 'del';
            break;
        default :
            break;
    }

    if ($action_to_do <> '') {
        switch ($action_to_do) {
            case 'add' :
            case 'valid' :
                $datef = valpost('date');
                $date = '';
                if ($datef <> '') {
                    $date = datetomysql($datef);
                }
                $codetec = valpost('codetec');
                $codelieu = valpost('codelieu');
                $heurea = valpost('heurea');
                $heurea_full = $heurea . ':00';
                $heured = valpost('heured');
                $heured_full = $heured . ':00';
                $offert = 0;
                if (strtolower(valpost('offert')) == 'on') {
                    $offert = 1;
                }

                if (($date <> '') AND ($codelieu <> '') AND ($codetec <> '') AND ($heurea <> '') AND ($heured <> '')) {
                    if (heure_sec($heured_full) >= heure_sec($heurea_full)) {
                        $codeuser = valsession('code_log');

                        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST, 'utf8');
                        if ($action_to_do == 'add') {
                            $rech = 'INSERT INTO `' . TBOTH . '`';
                            $rech .= ' (oth_datecrea,oth_codecrea,oth_datemod,oth_codemod,oth_codeot,oth_date,oth_codetec,oth_codelieu,oth_heurea,oth_heured,oth_offert) VALUES';
                            $rech .= " ('$datea','$codeuser','$datea','$codeuser','$codeot','$date','$codetec','$codelieu','$heurea_full','$heured_full','$offert')";
                        } else {
                            if ($id <> 0) {
                                $rech = 'UPDATE `' . TBOTH;
                                $rech .= "` SET `oth_datemod`='" . $datea . "',`oth_codemod`='" . $codeuser . "', `oth_date`='" . $date . "', `oth_codetec`='" . $codetec . "', `oth_codelieu`='" . $codelieu . "', `oth_heurea`='" . $heurea_full . "', `oth_heured`='" . $heured_full . "', `oth_offert`='" . $offert . "'  WHERE `oth_id` = '" . $id . "'";
                            }
                        }
                        $db->query($rech);
                        close_database();
                        $enr_ok = TRUE;
                        $td = 'add';
                    } else {
                        $pbm_enr_oth = TRUE;
                        $msg = _('Problème sur les heures choisies');
                    }
                }
                break;
            case 'del':
                if ($id <> 0) {
                    $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST, 'utf8');
                    $rech = 'DELETE FROM `' . TBOTH . "` WHERE `oth_id` = '$id'";
                    $db->query($rech);
                    close_database();
                }
                $enr_ok = TRUE;
                $td = 'add';
                break;
        }
    }
}

if ($pbm_oth == FALSE) {
    // Récupération du total travaillé & Techniciens traitants
    $nbtotalsec = 0;
    $nbtotalsecoff = 0;
    $str_tec_traitants = '';

    $nbtotalsec = tps_travaille_ot($codeot, TRUE);
    $nbtotalsecoff = tps_offert_ot($codeot, TRUE);
    $str_tec_traitants = str_tec_traitants_ot($codeot, TRUE);
}

switch ($tdh) {
    case 'add' :
        $titre = _('Ajout');
        break;
    case 'edit' :
        $titre = _('Edition');
        break;
    case 'view' :
        $titre = _('Visualisation');
        break;
    case 'del' :
        $titre = _('Suppression');
        break;
    default :
        $pbm_oth = 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 _('Détail Horaire Ordre de Travail'); ?></title>

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

    <script language="javascript">
        <!--
        var tab1_champ = ["nom:date ; format:date ; masque:<?php echo $_SESSION['date_fmtfull']; ?> ; req:Y ; txt:<?php echo _('Date'); ?> ; stok:frmok ; stbad:frmbad",
            "nom:codetec ; format:liste ; req:Y ; txt:<?php echo _('Technicien'); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad",
            "nom:codelieu ; format:liste ; req:Y ; txt:<?php echo _('Lieu'); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad",
            "nom:heurea ; format:liste ; req:Y ; txt:<?php echo _('Heure de début'); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad",
            "nom:heured ; format:liste ; req:Y ; txt:<?php echo _('Heure de fin'); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad"];
        //-->
    </script>

    <script type="text/javascript">
        <!--
        function init_datepicker() {
            <?php include_once ('../jscript/datepicker_prm.js.php'); ?>
            $("#date").datepicker({
                onSelect: function (datesel) {
                    $("#date").blur();
                    <?php
                    if ($regul == FALSE) {
                        echo "chk_datedif(datesel,this.id,'".valsession('date_fmtshort')."',true,'dateddef','','',true);";
                    }
                    ?>
                }
            });
        }

        function init_all() {
            init_Body();
            init_autohref_classe('falselnkimg', '');
            init_datepicker();
            init_maj_tps('<?php echo heure_to_hhmm(sec_heure($nbtotalsec,3,TRUE)); ?>', '<?php echo heure_to_hhmm(sec_heure($nbtotalsecoff,3,TRUE)); ?>', '<?php echo $str_tec_traitants; ?>');
            <?php
            if ($enr_ok == TRUE)
                {echo "clear_form_elements('oth_maj');";}

            switch ($tdh)
            {
                case 'add' :
                case 'edit' :
                    echo "init_autoraz('razdate','date','click');";
                    echo "init_chk_heuredif('heurea','change',true,'','','heured');";
                    echo "init_chk_heuredif('heured','change',true,'heurea','','');";
                    echo "init_autoraz('razheurea','heurea','click');";
                    echo "init_autoraz('razheured','heured','click');";
                    echo "init_valid_oth('enr','oth_maj',tab1_champ,'','');";
                    echo "init_valid_oth('val','oth_maj',tab1_champ,'','');";
                    break;
                case 'view' :
                    echo 'readonly_all();';
                    break;
                case 'del' :
                    echo "init_valid_oth('del','oth_maj',tab1_champ,'','');";
                    echo 'readonly_all();';
                    break;
            }
            ?>
            init_autohref('annul', 'click', '<?php echo $url_lst; ?>', false);
            add_func_click('quit', 'sclose', '');
            Focus_first();
        }

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

</head>

<body>
<?php
if (($pbm_oth == FALSE) AND ($pbm_enr_oth == FALSE)) {
    cre_ent_form(_('DETAIL HORAIRE'), '', '', '', FALSE);
    ?>
    <p align="center"><span class="titre_gras"><?php echo _("Pour l'ordre"); ?> : <?php echo $codeot; ?> </span></p>
    <div align="right">
        <input name="quit" type="button" class="bton_std" id="quit" value="<?php echo _('Quitter'); ?>">
    </div>

    <?php
    $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST, 'utf8');
    $rech = 'SELECT * FROM `' . TBOTH . "` WHERE `oth_codeot`= '" . $codeot . "' ORDER BY oth_date, oth_heurea";

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

    if ($rows) {

        echo '<table class="MtableD" border="0" width="890" cellpadding="0" cellspacing="0" align="center">';

        // création de l'entête de la table "détail intervention"
        echo '<th>';
        echo _('Date');
        echo '</th>';
        echo '<th>';
        echo _('Technicien');
        echo '</th>';
        echo '<th>';
        echo _('Lieu');
        echo '</th>';
        echo '<th>';
        echo _('Heure début');
        echo '</th>';
        echo '<th>';
        echo _('Heure fin');
        echo '</th>';
        echo '<th>';
        echo _('Temps passé');
        echo '</th>';
        echo '<th>';
        echo _('Offert ?');
        echo '</th>';
        echo '<th>';
        echo _('Cliquer');
        echo '</th>';

        foreach ($rows as $row) {
            $row = encode_str($row);
            // création de l'entête de ligne (TR)
            echo '<tr>';

            echo '<td align="center">';
            echo datetolocal($row['oth_date']);
            echo '<td>';
            echo $row['oth_codetec'];
            // Récupération et affichage détail technicien
            $rech2 = 'SELECT * FROM `' . TBTEC . "` WHERE `tec_code`= '" . $row['oth_codetec'] . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                $row2 = encode_str($row2);
                extract($row2);
                echo '<br />';
                echo '<span class="annot_petit_it">';
                echo $tec_nom . ' ' . $tec_prenom;
                echo '</span>';
            } else {
                echo '&nbsp;';
            }
            echo '</td>';
            echo '</td>';
            echo '<td align="center">';
            // Récupération et affichage libellé lieu
            $rech2 = 'SELECT * FROM `' . TBLIEU . "` WHERE `lieu_code`= '" . $row['oth_codelieu'] . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2) {
                $row2 = encode_str($row2);
                extract($row2);
                echo $lieu_desc;
            } else {
                echo '&nbsp;';
            }
            echo '</td>';
            echo '<td align="center">';
            echo substr($row['oth_heurea'], 0, 5);
            echo '</td>';
            echo '<td align="center">';
            echo substr($row['oth_heured'], 0, 5);
            echo '</td>';
            echo '<td align="center">';
            echo heure_to_hhmm(sec_heure(diff_time_sec($row['oth_heurea'], $row['oth_heured'])));
            echo '</td>';
            echo '<td align="center">';
            echo $non_oui2[$row['oth_offert']];
            echo '</td>';
            echo '<td align="center">';
            if ($td <> 'view') {
                $lst_maj = TRUE;
                cre_falselnk_img('', 'oth_edit_' . $row['oth_id'], 'span', 'center', _('Edition'), 'lnk', 'oth_maj.php?td=edit&co=' . $codeot . '&id=' . $row['oth_id'], '../img/edit.png');
                $lst_del = TRUE;
                cre_falselnk_img('', 'oth_del_' . $row['oth_id'], 'span', 'center', _('Suppression'), 'lnk', 'oth_maj.php?td=del&co=' . $codeot . '&id=' . $row['oth_id'], '../img/edit.png');
            } else {
                echo '-';
            }
            echo '</td>';

            echo '</tr>';
        }

        /* Totaux */

        // Total Général

        // création de l'entête de ligne (TR)
        echo '<tr>';

        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td align="right">';
        echo '<span class="annot_std_gras">';
        echo _('Temps total ') . ' : ';
        echo '</span>';
        echo '</td>';
        echo '<td align="center">';
        echo '<span class="annot_std_gras">';
        echo heure_to_hhmm(sec_heure($nbtotalsec, 3, TRUE));
        echo '</span>';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';

        // Temps offert

        // création de l'entête de ligne (TR)
        echo '<tr>';

        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td align="right">';
        echo '<span class="annot_std_gras">';
        echo _('Temps offert') . ' : ';
        echo '</span>';
        echo '</td>';
        echo '<td align="center">';
        if ($nbtotalsecoff <> 0) {
            echo '<span class="annot_std_gras">';
            echo heure_to_hhmm(sec_heure($nbtotalsecoff, 3, TRUE));
            echo '</span>';
        } else {
            echo '-';
        }
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';

        // Temps retenu

        // création de l'entête de ligne (TR)
        echo '<tr>';

        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td align="right">';
        echo '<span class="annot_std_gras">';
        echo _('Temps retenu') . ' : ';
        echo '</span>';
        echo '</td>';
        echo '<td align="center">';
        echo '<span class="annot_std_gras">';
        echo heure_to_hhmm(sec_heure($nbtotalsec - $nbtotalsecoff, 3, TRUE));
        echo '</span>';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';
        echo '<td>';
        echo '&nbsp;';
        echo '</td>';

        echo '</table>';
        // Fin affichage table détail horaire

        $pas_horaire = FALSE;
    } else {
        $pas_horaire = TRUE;
        ?>
        <p class="annot_petit_it"><?php echo _('Aucun détail horaire enregistré'); ?></p>
        <?php
    }
    close_database();

    $taille_piedla = '';
    include_once('piedla.inc.php');

    if ($td <> 'view') {
        ?>
        <br/>
        <form name="oth_maj" id="oth_maj" class="bord_pointilles" method="post" action="oth_maj.php">
            <p align="center" class="annot_std_gras"><?php echo $titre; ?></p>

            <p align="center" class="annot_petit_it"><?php echo _('Tous les champs sont obligatoires'); ?></p>
            <input name="td" type="hidden" id="td" value="<?php echo $td; ?>">
            <input name="co" type="hidden" id="co" value="<?php echo $codeot; ?>">
            <input name="id" type="hidden" id="id" value="<?php echo $id; ?>">
            <input name="nbutton" type="hidden" id="nbutton" value="">
            <table width="580" border="0" align="center">
                <tr>
                    <td width="30%" class="rubfrm" id="f_date" align="right"><?php echo _('Date'); ?></td>
                    <td align="left">
                        <input name="date" type="text" id="date" value="<?php echo $datef; ?>" size="10" maxlength="10"
                               readonly>
                        <a href="javascript:"><img src="../img/raz.png" id="razdate" border="0" align="absmiddle"></a>
                    </td>
                </tr>
                <tr>
                    <td width="30%" class="rubfrm" id="f_tec" align="right"><?php echo _('Technicien'); ?></td>
                    <td align="left">
                        <?php
                        $rows = give_tab_rows_tec_st($ot_codest);

                        if (count($rows) > 0) {
                            cre_select_tab('codetec', 'codetec', $rows, 'tec_code', 'tec_nom', 'tec_prenom-tec_codest', $oth_codetec, '', _('-- Faites votre choix --'));
                        } else {
                            $tab_nosel = [];
                            $tab_nosel[''] = _('>-- Pas de technicien actif chez ce sous-traitant --');
                            cre_select('codetec', 'codetec', $tab_nosel, '');
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <td width="30%" class="rubfrm" id="f_lieu" align="right"><?php echo _('Lieu'); ?></td>
                    <td align="left">
                        <?php
                        // création de la liste des Types Lieux
                        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST, 'utf8');
                        $rech = 'SELECT * FROM `' . TBLIEU . '` ORDER BY lieu_desc';
                        $rows = $db->get_results($rech, ARRAY_A);
                        close_database();
                        cre_select_tab('codelieu', 'codelieu', $rows, 'lieu_code', 'lieu_desc', '', $oth_codelieu, '', _('-- Faites votre choix --'));
                        ?>
                    </td>
                </tr>
                <tr>
                    <td width="30%" class="rubfrm" id="f_horaires" align="right"><?php echo _('Horaires'); ?></td>
                    <td align="left">
                        <?php
                        // $tab_heures = give_tab_heures(0, 86400, ($pla_stepmin * 60));
                        $tab_heures = give_tab_heures($pprm_firsthour * 3600, $pprm_lasthour * 3600, $pla_stepmin * 60);

                        echo ' ' . _('Début') . ' ';
                        cre_select('heurea', 'heurea', $tab_heures, substr($oth_heurea, 0, 5));

                        if ($tdh <> 'view') {
                            echo ' <a href="javascript:;"><img src="../img/raz.png" id="razheurea" border="0" align="absmiddle"></a>';
                        }

                        echo ' / Fin ';

                        cre_select('heured', 'heured', $tab_heures, substr($oth_heured, 0, 5));

                        echo ' <a href="javascript:;"><img src="../img/raz.png" id="razheured" border="0" align="absmiddle"></a>';
                        ?>
                    </td>
                </tr>
                <tr>
                    <td width="30%" class="rubfrm" id="f_offert" align="right">
                        Offert
                    </td>
                    <td align="left">
                        <?php
                        echo '<input type="checkbox" name="offert" style="background : #FFFFFF;"';
                        if ($oth_offert == 1) {
                            echo ' checked';
                        }
                        echo '>';
                        ?>
                    </td>
                </tr>
            </table>
            <?php
            echo '<p align="center">';
            echo '<input name="annul" type="button" class="bton_std" id="annul" value="' . _('Annuler') . '">';
            switch ($tdh) {
                case 'add' :
                    echo '<input name="enr" type="button" class="bton_std" id="enr" value="' . _('Ajouter') . '">';
                    break;
                case 'edit' :
                    echo '<input name="val" type="button" class="bton_std" id="val" value="' . _('Valider') . '">';
                    break;
                case 'del' :
                    echo '<input name="del" type="button" class="bton_std" id="del" value="' . _('Supprimer') . '">';
                    break;
                default :
                    break;
            }
            echo '</p>';
            ?>
        </form>
        <?php
    }
} else {
    if ($pbm_oth == TRUE) {
        close_fen_auto('', '');
    }

    if ($pbm_enr_oth == TRUE) {
        pop_ret_auto($msg, 'warn', 'oth_maj.php?co=' . $codeot . '&td=' . $td . '&id=' . $id);
    }
}
?>
</body>
</html>
