<?php
session_start();
include "classes/db.class.php";
include "classes/fc.class.php";
include "config.php";


if (!isset($_SESSION['uid'])) {
    header("Location: login.php");
    exit;
}
$tabela = "servicos";
$coluna = "ABERTURA DESC";
$primaria = 'idservicos';
if (isset($_SESSION['tabela'])) {
    unset($_SESSION['tabela']);
}
if (isset($_SESSION['coluna'])) {
    unset($_SESSION['coluna']);
}
if (isset($_SESSION['primaria'])) {
    unset($_SESSION['primaria']);
}

$_SESSION['primaria'] = $primaria;
$_SESSION['tabela'] = $tabela;
$_SESSION['coluna'] = $coluna;

$uid = $_SESSION['uid'];
$nome = $_SESSION['un'];
$email = $_SESSION['ue'];
$idsql = $_SESSION['uids'];

$pag = $_SERVER['REQUEST_URI'];
$pag = explode("/", $pag);
$page = $pag[2];





?>
<!DOCTYPE html>

<html lang="pt-br">

<head>

    <?php include "includes/header.php"; ?>

</head>

<body>

    <!-- navbar -->
    <?php include "includes/navbar.php"; ?>


    <div id="corpo" class="container card shadow-lg  my-2 py-1">

        <div class="row align-items-center justify-content-center my-2">

            <div class="col-7 col-md-7 text-start">
                <h4 class="text-dark"><i class='fas fa-tools me-2'></i>Ordens Serviços</h4>


            </div>
            <div class="col-5 col-md-5  text-end">

                <a href="#" class="btn btn-success text-light float-end" data-bs-toggle="modal"
                    data-bs-target="#mReg"><i class='fas fa-plus-circle'></i></a>


            </div>



        </div>

    </div>

    <div class="container card shadow-lg  mb-3 py-1">

        <div class="row mb-3">

            <div class="col-12 col-md-12 col-sm-12 col-lg-12 col-xl-12 mb-3">

                <table class="table table-striped mb-3   table-hover">

                    <thead class="border-0 border-1 border-bottom border-secondary">
                        <tr>
                            <th class="col-2 text-center">Data</th>
                            <th class='col-5 text-start'>Solicitado</th>
                            <th class="col-2 text-center">Valor OS</th>
                            <th class="col-3 text-end"></th>

                        </tr>
                    </thead>
                    <tbody>


                    </tbody>
                </table>

            </div>

        </div>

    </div>



    <!-- footer -->
    <?php include "includes/footer.php"; ?>



    <!-- Modal -->
    <div class="modal fade" id="mReg" tabindex="-1" aria-labelledby="mRegLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mRegLabel">Nova O.S:</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">

                    <form id="fcad" class="was-validated" method='POST'>

                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='CODIGO' name='CODIGO' value="0" class='form-control' required>
                        </div>

                        <div class='col-md-6 col-sm-12 mb-1'>
                           
                            <input type='hidden' id='ABERTURA' name='ABERTURA' value="<?php echo date('Y-m-d h:i:s') ?>" class='form-control'  required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='PREVISTA' class='form-label'>PREVISTA:</label>
                            <input type='date' id='PREVISTA' name='PREVISTA' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='RAZAO' class='form-label'>RAZAO:</label>
                            <input type='text' id='RAZAO' name='RAZAO' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='MODELO' class='form-label'>MODELO:</label>
                            <input type='text' id='MODELO' name='MODELO' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='SERIE' class='form-label'>SERIE:</label>
                            <input type='text' id='SERIE' name='SERIE' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='MECANICO' name='MECANICO' value="<?php echo $idsql; ?>" class='form-control' required>
                        </div>
                        <div class='col-md-12 col-sm-12 mb-1'>
                            <label for='CLIENTE' class='form-label'>CLIENTE:</label>
                            <select id='CLIENTE' name='CLIENTE' class='form-select  font-weight-bold' data-placeholder="Selecione uma opção...">
                                <!--  <option value=''>Selecione um cliente...</option> -->
                                <?php
                                $con = DB::conecta();
                                $sql = "SELECT CODIGO,NOME FROM clientes ORDER BY NOME ASC";
                                $res = $con->query($sql);
                                $res->execute();
                                $row = $res->fetchAll(PDO::FETCH_ASSOC);
                                for ($ii = 0; $ii < count($row); $ii++) {
                                    $cod = $row[$ii]['CODIGO'];
                                    $nome = $row[$ii]['NOME'];


                                ?>
                                    <option value='<?php echo $cod; ?>'><?php echo $nome; ?></option>
                                <?php
                                }
                                ?>
                            </select>
                        </div>
                        <div class='col-md-12 col-sm-12 mb-1'>
                            <label for='SOLICITADO' class='form-label'>SOLICITADO:</label>
                            <input type='text' readonly id='SOLICITADO' name='SOLICITADO' class='form-control text-uppercase'>
                        </div>

                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='PAGAMENTO' class='form-label'>PAGAMENTO:</label>
                            <input type='number' id='PAGAMENTO' name='PAGAMENTO' class='form-control'>
                        </div>
                        <div class="row">
                            <div class='col-md-6 col-sm-6 mb-1'>
                                <label for='ENTRACLIENTE' class='form-label'>ENT.CLIENTE:</label>
                                <input type='date' id='ENTRACLIENTE' name='ENTRACLIENTE' class='form-control'>
                            </div>
                            <div class='col-md-6 col-sm-6 mb-1'>
                                <label for='SAIDACLIENTE' class='form-label'>SAIDA CLIENTE:</label>
                                <input type='date' id='SAIDACLIENTE' name='SAIDACLIENTE' class='form-control'>
                            </div>
                        </div>
                        <div class='col-md-6 col-sm-6 mb-1'>

                            <input type='hidden' id='PRONTA' name='PRONTA' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-6 mb-1'>

                            <input type='hidden' id='ENTREGUE' name='ENTREGUE' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='FECHAMENTO' name='FECHAMENTO' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='POS' class='form-label'>POS:</label>
                            <input type='text' id='POS' name='POS' class='form-control' required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='CANCELA' name='CANCELA' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='TOTALPROD' name='TOTALPROD' value="0" class='form-control' required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='TOTALSERVICO' name='TOTALSERVICO' class='form-control' value="0" required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='TOTAL' value="0" name='TOTAL' class='form-control' required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='OBS' class='form-label'>OBS:</label>
                            <input type='text' id='OBS' name='OBS' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='DEFRECLAM1' class='form-label'>DEF.RECLAM:</label>
                            <input type='text' id='DEFRECLAM1' name='DEFRECLAM1' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='CARACTENT1' class='form-label'>CARACTENT1:</label>
                            <input type='text' id='CARACTENT1' name='CARACTENT1' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' value="" id='DEFEITENC1' name='DEFEITENC1' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-6 mb-1'>

                            <input type='hidden' maxlength="5" minlength="5" value="" id='SEQUENCIA' name='SEQUENCIA' class='form-control' required>
                        </div>
                        <div class='col-md-6 col-sm-6 mb-1'>

                            <input type='hidden' id='ANO' name='ANO' value="<?php echo date('Y'); ?>" class='form-control' required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='IMPRESSO' value="0" name='IMPRESSO' class='form-control'>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>

                            <input type='hidden' id='VENDEDOR' name='VENDEDOR' value="<?php echo $idsql; ?>" class='form-control' required>
                        </div>
                        <div class='col-md-6 col-sm-12 mb-1'>
                            <label for='RECEBIDO' class='form-label'>RECEBIDO:</label>
                            <input type='text' id='RECEBIDO' name='RECEBIDO' class='form-control' required>
                        </div>
                        <button type='submit' id='btnSalvar' class='btn btn-success text-light w-100'>Salvar<i class='fas fa-location-arrow ms-2'></i></button>
                    </form>


                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning  w-100" data-bs-dismiss="modal">Cancelar</button>

                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="mDados" tabindex="-1" aria-labelledby="mDadosLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mDadosLabel">Ordem Serviço:</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">




                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning  w-100" data-bs-dismiss="modal">Cancelar</button>

                </div>
            </div>
        </div>
    </div>

    <?php include "includes/libs.php"; ?>


    <script>
        $(function() {
            // Initialize tooltips
            pulse('Carregando...');

        });
        $(document).ready(function() {
            removeloader();

            var page = '<?php echo $page; ?>';
            if (page == 'clientes.php') {
                $('#btnradio2').prop('checked', true);
                $('#btnradio3').prop('checked', false);
                $('#btnradio4').prop('checked', false);
                $('#btnradio1').prop('checked', false);
            } else if (page == 'servicos.php') {
                $('#btnradio3').prop('checked', true);
                $('#btnradio2').prop('checked', false);
                $('#btnradio4').prop('checked', false);
                $('#btnradio1').prop('checked', false);
            } else if (page == 'produtos.php') {
                $('#btnradio4').prop('checked', true);
                $('#btnradio2').prop('checked', false);
                $('#btnradio3').prop('checked', false);
                $('#btnradio1').prop('checked', false);
            } else if (page == 'index.php') {
                $('#btnradio1').prop('checked', true);
                $('#btnradio2').prop('checked', false);
                $('#btnradio3').prop('checked', false);
                $('#btnradio4').prop('checked', false);
            }

            var lista = $('.table tbody');
            lista.empty();

            $('#CLIENTE').select2({
                theme: "bootstrap-5",
                dropdownParent: "#mReg"
            });

            $('#CLIENTE').on('select2:select', function(e) {
                var data = e.params.data;
                //console.log(data);
                $('#SOLICITADO').val(data.text);
            });

            $.get('./rest/buscaos.php', function(resposta) {

                if (resposta != 'erro') {

                    lista.html(resposta);
                    $('.table').dataTable({
                        dom: 'Bfrtip',
                        buttons: [
                            'copy',
                            'excel',
                            'pdf',
                            'print'
                        ],
                        language: {
                            url: './langPT.json'
                        }

                    });

                } else {
                    mensagem('Erro ao carregar Registros!', 'erro');
                }


            });



            /* $('#fcad').submit(function(e) {
                e.preventDefault(); // Prevent the default form submission

                $('#btnCadastro').prop('disabled',
                true); // Disable the button to prevent multiple submissions
                
                

                loaders('Cadastrando cliente...');

                var formData = $(this).serialize(); // Serialize the form data
                
                

                $.ajax({
                    type: 'POST',
                    url: 'rest/cadcliente.php',
                    data: formData,
                    success: function(response) {

                        //alert(response);
                        removeloader();
                        $('#btnCadastro').prop('disabled', false);

                        if (response == 'ok') {

                            mensagem('Cliente cadastrado com sucesso!', 'sucesso');
                            $('#mReg').modal('hide');
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                        } else {
                            if (response == 'existe') {
                                mensagem('Cliente já cadastrado!', 'atencaoerro');
                            } else {
                                mensagem('Erro ao cadastrar cliente!', 'erro');
                            }
                            //mensagem('Erro ao cadastrar cliente!', 'erro');
                        }

                        //console.log(response);
                    },
                    error: function(xhr, status, error) {
                        alert(error);

                        removeloader();
                        $('#btnCadastro').prop('disabled', false);
                        mensagem('Ocorreu um erro ao cadastrar o cliente.', 'erro');
                    }
                });
            });

            $('#fdados').submit(function(e) {
                e.preventDefault(); // Prevent the default form submission

                $('#btnCadastro2').prop('disabled',
                true); // Disable the button to prevent multiple submissions

                loaders('Atualizando cliente...');

                var formData = $(this).serialize(); // Serialize the form data

                $.ajax({
                    type: 'POST',
                    url: 'rest/editcliente.php',
                    data: formData,
                    success: function(response) {

                        //alert(response);
                        removeloader();
                        $('#btnCadastro2').prop('disabled', false);

                        if (response == 'ok') {

                            mensagem('Cliente atualizado com sucesso!', 'sucesso');
                            $('#mDados').modal('hide');
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                        } else {
                            mensagem('Erro ao atualizar cliente!', 'erro');
                        }

                        //console.log(response);
                    },
                    error: function(xhr, status, error) {
                        alert(error);

                        removeloader();
                        $('#btnCadastro2').prop('disabled', false);
                        mensagem('Ocorreu um erro ao atualizar o cliente.', 'erro');
                    }
                });
            }); */


        });

        function removeloader() {



            Notiflix.Loading.remove(1923);
            // $('#corpo').fadeIn(500);
            //
        }


        function dados(id, tipo) {

            // alert(id);

            if (id != '' || id != null) {

                //$('#idcliente').val(id);

                $.post('rest/bscliente.php', {
                    id: id
                }, function(e) {

                    //console.log(e);
                    //console.log(e['NOME']);
                    var ds = JSON.parse(e);
                    $.each(ds[0], function(key, value) {
                        //console.log(key+' - '+value);
                        $('#' + key + '2').val(value);


                    });

                    $('#mDados').modal('show');
                    //alert($('#idcliente2').val());

                    if (tipo == 1) {
                        $('#mDados input').prop('disabled', false); // Enable all input fields 
                        $('#btnCadastro2').prop('disabled', false); // Enable the button to allow submission again 
                    } else {
                        $('#mDados input').prop('disabled', true); // Disable all input fields
                        $('#btnCadastro2').prop('disabled', true); // Enable the button to allow submission again
                    }



                    $('#mDadosLabel').html(tipo == 1 ? 'Alterar Cadastro' : 'Dados do Cadastro');

                });

            }

        }

        function selcliente(cliente) {
            alert(cliente);
            $('#SOLICITADO').val(cliente);
        }
    </script>


</body>

</html>