<?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="clientes";
$coluna="NOME ASC";
$primaria='idcliente';
if (isset($_SESSION['tabela'])) {
    unset($_SESSION['tabela']);
}
if (isset($_SESSION['coluna'])) {
    unset($_SESSION['coluna']);
}
if (isset($_SESSION['primaria'])) {
    unset($_SESSION['primaria']);
}
unset($_SESSION['tabela']);
unset($_SESSION['coluna']);
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-users me-2'></i>Clientes</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"></th>
                            <th>Nome</th>
                            <th class="col-3 text-end"></th>

                        </tr>
                    </thead>
                    <tbody>

                       
                    </tbody>
                </table>

            </div>

        </div>

    </div>



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

    <?php include "includes/libs.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">Novo Cadastro</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='mb-1'>

                            <input type='text' id='NOME' name='NOME' class='form-control text-uppercase'
                                placeholder="Nome..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='FANTASIA' name='FANTASIA' class='form-control text-uppercase'
                                placeholder="Fantasia..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CEP' onchange="buscacep($(this).val(),1)" name='CEP'
                                placeholder="CEP" class='form-control cep' maxlength="9" minlength="9" required>
                        </div>

                        <div class='mb-1'>

                            <input type='text' id='ENDERECO' name='ENDERECO' class='form-control text-uppercase'
                                placeholder="Endereço..." required>
                        </div>

                        <div class='mb-1'>

                            <input type='text' id='BAIRRO' name='BAIRRO' class='form-control text-uppercase'
                                placeholder="Bairro..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='NUM' placeholder="Núm" name='NUM' class='form-control' required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='COMPL' name='COMPL' class='form-control  text-uppercase'
                                placeholder="Complemento...">
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CIDADE' name='CIDADE' class='form-control  text-uppercase'
                                placeholder="Cidade..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' maxlength="2" minlength="2" id='UF' name='UF'
                                class='form-control text-uppercase' placeholder="UF" required>
                        </div>

                        <div class='mb-1'>

                            <input type='text' id='CGC' name='CGC' class='form-control cnpj' placeholder="CNPJ"
                                required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='INSCEST' name='INSCEST' class='form-control'
                                placeholder="Insc.Estadual...">
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='RG' name='RG' placeholder="RG.." class='form-control'>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CELULAR' name='CELULAR' class='form-control fone'
                                placeholder="(99)99999-9999" required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CONTATO' name='CONTATO' class='form-control  text-uppercase'
                                placeholder="Contato...">
                        </div>
                        <div class='mb-1'>

                            <input type='email' id='EMAIL' name='EMAIL' class='form-control  text-lowercase'
                                placeholder="E-mail..." required>
                        </div>
                        <div class='mb-2'>

                            <input type='text' id='OBS' name='OBS' placeholder="Obs..." class='form-control'>
                        </div>

                        <div class='mb-0'>

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

                        <button type='submit' class='btn btn-success w-100 text-light' id="btnCadastro">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">Cadastro</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">

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


                        <div class='mb-1'>

                            <input type='text' id='NOME2' value="" name='NOME' class='form-control text-uppercase'
                                placeholder="Nome..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='FANTASIA2' value="" name='FANTASIA'
                                class='form-control text-uppercase' placeholder="Fantasia..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CEP2' value="" onchange="buscacep($(this).val(),2)" name='CEP'
                                placeholder="CEP" class='form-control cep' maxlength="9" minlength="9" required>
                        </div>

                        <div class='mb-1'>

                            <input type='text' id='ENDERECO2' value="" name='ENDERECO'
                                class='form-control text-uppercase' placeholder="Endereço..." required>
                        </div>

                        <div class='mb-1'>

                            <input type='text' id='BAIRRO2' value="" name='BAIRRO' class='form-control text-uppercase'
                                placeholder="Bairro..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='NUM2' value="" placeholder="Núm" name='NUM' class='form-control'
                                required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='COMPL2' value="" name='COMPL' class='form-control  text-uppercase'
                                placeholder="Complemento...">
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CIDADE2' value="" name='CIDADE' class='form-control  text-uppercase'
                                placeholder="Cidade..." required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' maxlength="2" value="" minlength="2" id='UF2' name='UF'
                                class='form-control text-uppercase' placeholder="UF" required>
                        </div>

                        <div class='mb-1'>

                            <input type='text' id='CGC2' name='CGC' value="" class='form-control cnpj'
                                placeholder="CNPJ" required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='INSCEST2' value="" name='INSCEST' class='form-control'
                                placeholder="Insc.Estadual...">
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='RG2' name='RG' value="" placeholder="RG.." class='form-control'>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CELULAR2' value="" name='CELULAR' class='form-control fone'
                                placeholder="(99)99999-9999" required>
                        </div>
                        <div class='mb-1'>

                            <input type='text' id='CONTATO2' value="" name='CONTATO'
                                class='form-control  text-uppercase' placeholder="Contato...">
                        </div>
                        <div class='mb-1'>

                            <input type='email' id='EMAIL2' value="" name='EMAIL' class='form-control  text-lowercase'
                                placeholder="E-mail..." required>
                        </div>
                        <div class='mb-2'>

                            <input type='text' id='OBS2' value="" name='OBS' placeholder="Obs..." class='form-control'>
                        </div>

                        <div class='mb-0'>

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

                        <div class='mb-0'>

                            <input type='hidden' value="" id='idcliente2' name='idcliente' class='form-control'>
                        </div>

                        <button type='submit' class='btn btn-success w-100 text-light' id="btnCadastro2">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>


    <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();

        $.get('./rest/buscacliente.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');

            });

        }

    }
    </script>


</body>

</html>