<?php
$getPage = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
$Pager = new Pager('painel.php?exe=usuario/index&page=');
$Pager->ExePager($getPage, 20);
?>
<ul class="page-breadcrumb breadcrumb">
    <li>
        <span>Usuários</span>
        <i class="fa fa-circle"></i>
    </li>
    <li>
        <span>Listar</span>
    </li>
</ul>
<?php
$empty = filter_input(INPUT_GET, 'create', FILTER_VALIDATE_BOOLEAN);
if ($empty):
    WSErro("<b>Sucesso:</b> O usuario foi cadastrado no sistema", WS_ACCEPT);
endif;

$empty = filter_input(INPUT_GET, 'plano', FILTER_VALIDATE_BOOLEAN);
if ($empty):
    WSErro("<b>Sucesso:</b> O plano do usuario foi extendido com sucesso", WS_ACCEPT);
endif;

$delUser = filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT);
if ($delUser):
    require ('_models/AdminUsuario.class.php');
    $deletar = new AdminUsuario;
    $deletar->ExeDelete($delUser);

    WSErro($deletar->getError()[0], $deletar->getError()[1]);
endif;
?>
<div class="portlet">
    <div class="portlet-title">
        <div class="caption">
            <span class="caption-subject font-dark bold uppercase">Lista de usuários</span>
        </div>
        <div class="actions">
            <a href="painel.php?exe=usuario/novo" class="btn btn-xs blue" alt="Add Novo" title="Add Novo"><i class="fa fa-plus"></i> <span> Novo</span></a>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="portlet light bordered">
                <!--                <div class="portlet-title">
                                    <form class="form-inline pull-right" action="#">
                                        <div class="input-group input-medium">
                                            <input type="text" class="form-control" placeholder="Buscar" id="campo_busca" name="campo_busca">
                                            <span class="input-group-btn">
                                                <button type="button" class="btn green" onclick="javascript:busca_orcamento(1);">
                                                    <i class="fa fa-search"></i>
                                                </button>
                                            </span>
                                        </div>
                                    </form>
                                </div>-->
                <div class="portlet-body">
                    <table class="table table-striped table-bordered table-hover table-checkable order-column" id="sample_1">
                        <thead>
                            <tr>
<!--                                <th>
                                    <label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                                        <input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes">
                                        <span></span>
                                    </label>
                                </th>-->
                                <th> Nome de usuário </th>
                                <th> E-mail </th>
                                <th> Status </th>
                                <th> Perfil </th>
                                <th> Expira </th>
                                <th> </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $Read = new Read;
                            $Read->ExeRead("tp_usuarios", "LIMIT :limit OFFSET :offset", "limit={$Pager->getLimit()}&offset={$Pager->getOffset()}");
                            if (!$Read->getResult()):
                                ?>
                                <tr class="odd gradeX">
                                    <td class="text-center" colspan="6">
                                        Sem resultados!
                                    </td>
                                </tr>
                                <?php
                            else:
                                foreach ($Read->getResult() as $usuarios):
                                    extract($usuarios);
                                    ?>
                                    <tr>                                        
                                        <td><?= $usuario_nome ?></td>
                                        <td><?= $usuario_email ?></td>
                                        <td><?= $status = ($usuario_status == 1 ? "Ativo" : "Bloqueado"); ?></td>
                                        <td><?= $nivel = ($usuario_nivel == 1 ? "Administrador" : "Padrão"); ?></td>
                                        <td>
                                            <?php
                                            if ($usuario_nivel == 1):
                                                echo '<small>Não aplica</small>';
                                            else:
                                                if (date('Y-m-d') <= $usuario_data_exp):
                                                    // calculo para dias restantes
                                                    $data1 = new DateTime(date('Y-m-d'));
                                                    $data2 = new DateTime($usuario_data_exp);
                                                    $intervalo = $data1->diff($data2);
                                                    $expira = $intervalo->format('%a');
                                                    echo "{$expira} dias";
                                                else:
                                                    echo 'Expirado';
                                                endif;
                                            endif;
                                            ?>
                                        </td>
                                        <td>
                                            <?php
                                            if ($usuario_nivel > 1):
                                                ?>
                                                <a href="javascript:plano(<?= $usuario_id ?>);" class="btn btn-xs yellow"><i class="fa fa-user-plus"></i></a>
                                                <?php
                                            endif;
                                            ?>
                                            <a href="javascript:view_senha(<?= $usuario_id ?>);" class="btn btn-xs green"><i class="fa fa-key"></i></a>
                                            <a href="painel.php?exe=usuario/update&userid=<?= $usuario_id ?>" class="btn btn-xs blue"><i class="fa fa-edit"></i></a>
                                            <a href="javascript:excluir(<?= $usuario_id ?>);" class="btn btn-xs red"><i class="fa fa-times"></i></a>
                                            <!--<a href="painel.php?exe=usuario/index&delete=<?= $usuario_id ?>" class="btn btn-xs red"><i class="fa fa-times"></i></a>-->
                                        </td>
                                    </tr>
                                    <?php
                                endforeach;
                            endif;
                            ?>
                        </tbody>
                    </table>
                </div>
                <div class="inbox-footer">
                    <div class="row">
                        <div class="col-md-5">
                        </div>
                        <div class="col-md-7">
                            <?php
                            $Pager->ExePaginator("tp_usuarios");
                            echo $Pager->getPaginator();
                            ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<div class="modal fade bs-modal-sm" id="excluir" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h4 class="modal-title">ATENÇÃO</h4>
            </div>
            <div class="modal-body"> Tem certeza que deseja excluir? </div>
            <div class="modal-footer">
                <a href="" id="yes" class="btn green">Sim</a>
                <button type="button" class="btn dark btn-outline" data-dismiss="modal">Não</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>

<div class="modal fade bs-modal-sm" id="plano" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;">
    <div class="modal-dialog modal-sm">
        <form class="form-horizontal" id="formPlano" name="UseForm" method="POST" action="" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                    <h4 class="modal-title">Extender Plano</h4>
                </div>
                <div class="modal-body"> 
                    <div class="form-group j_plano" style="margin: 0">
                        <label>Quantos meses pretende extender?</label>
                        <select class="form-control" name="plano_id" id="expiracao">
                            <option selected="selected">Selecione...</option>
                            <?php
                            $Read = new Read;
                            $Read->ExeRead("tp_planos");
                            if ($Read->getResult()):
                                foreach ($Read->getResult() as $planos):
                                    extract($planos);
                                    ?>

                                    <option value="<?= $plano_id; ?>"><?= $plano_nome; ?></option>

                                    <?php
                                endforeach;
                            endif;
                            ?>
                        </select>
                        <input type="hidden" name="action" value="plano">
                        <input type="hidden" name="usuario_id" id="user_id">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" name="SendPostForm" value="enviar" class="btn green">Confirmar</button>
                    <button type="button" class="btn dark btn-outline" data-dismiss="modal">Cancelar</button>
                </div>
            </div>
        </form>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>

<div class="modal fade bs-modal-sm" id="senha" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h4 class="modal-title">SENHA DO USUÁRIO</h4>
            </div>
            <div class="modal-body" id="key_user">  </div>
            <div class="modal-footer">
                <button type="button" class="btn blue" data-dismiss="modal">OK</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>

<script>
    function excluir(id) {
        console.log(id);
        $('#excluir').modal('show');

        $("#yes").attr('href', 'painel.php?exe=usuario/index&delete=' + id);
    }

    function plano(id) {
        console.log(id);
        $('#plano').modal('show');

        $("#user_id").val(id);
    }

    function view_senha(id) {
        console.log(id);
        $('#senha').modal('show');

        $.ajax({
            url: '__jsc/ajax/password.php',
            data: {id: id},
            type: 'POST',
            dataType: 'json',
            beforeSend: function () {
                console.log('LOADING...');
            },
            success: function (data) {
                console.log(data)
                $("#key_user").html(data.senha);
            }
        })
    }
    
    $(function () {
        // Ação de validação e cadastro do formulario de usuario
        $("#formPlano").validate({
            //definir as regras
            rules: {
                plano_id: {
                    required: true
                }
            },
            //Definir as mensagens de erro para cada regra
            messages: {
                plano_id: {
                    required: "Escolha um plano!"
                }
            },
            submitHandler: function (form) {
                var dados = $(form).serialize();
                console.log(dados);
                $('.trigger').hide()
                $.ajax({
                    type: "POST",
                    url: "__jsc/ajax/usuario_crud.php",
                    data: dados,
                    dataType: 'json',
                    success: function (data)
                    {
                        console.log(data);
                        if (data.error[1] == 'accept') {
                            console.log('sucesso')
                            document.location.href = 'painel.php?exe=usuario/index&plano=true';
                            $("<div class=\"trigger trigger-" + data.error[1] + "\">" + data.error[0] + "</div>").prependTo(".j_plano");
                        } else {
                            $("<div class=\"trigger trigger-" + data.error[1] + "\">" + data.error[0] + "</div>").prependTo(".j_plano");
                        }
                    }
                });

                return false;
            }
        });
    });
</script>