<?php
session_start();
require 'conexao.php';
require 'config.php';
require 'includes/inc_verifica_caixa.php';
require 'includes/limpar_session.php';

$praca = (isset($_COOKIE['pPraca'])) ? $_COOKIE['pPraca'] : '';

$pdo  = Conexao::getInstance();	
$condicao = ($praca > 0) ? " AND praca = '{$praca}' " : '';
$sql = "SELECT mes_003, mes_001 FROM mesa WHERE sit_001 = 4 {$condicao} ORDER BY mes_001";
$stm = $pdo->prepare($sql);
$stm->execute();
$mesas = $stm->fetchAll(PDO::FETCH_OBJ);

$sql = 'SELECT b_reabrir_mesa_comanda FROM usuarios ';
$sql .= 'WHERE usu_001 = :id_usuario';
$stm = $pdo->prepare($sql);
$stm->bindValue(':id_usuario', $_COOKIE['id']);
$stm->execute();
$autorizacao = $stm->fetch(PDO::FETCH_OBJ);

?>
<!DOCTYPE html>
<html>
<head>
	<title>Comanda Eletrônica</title>
	<?php require 'includes/inc_head.php'; ?>
</head>
<body>
   <script>loadPagina()</script>
   <div class = "mdl-layout mdl-js-layout mdl-layout--fixed-header" id="page" style="display:none">
     <header class = "mdl-layout__header">
        <div class = "mdl-layout__header-row login">
           <span class = "mdl-layout-title"><?=$_COOKIE['usuario']?></span>      
        </div>
      </header>

      <?php include 'includes/inc_menu.php'; ?> 

  	  <main class="mdl-layout__content">

        <div class="block-center">
          <p class="linha-5"></p>
          <div class = "mdl-textfield mdl-js-textfield mdl-textfield--floating-label pesquisa">
            <input class = "mdl-textfield__input" type = "number" id = "pesquisa">
            <label class = "mdl-textfield__label" for = "text4" autocomplete="nope">Procurar Mesa</label>
          </div>
        </div>

        <div class="box-comandas">
          <?php foreach($mesas as $mesa):
            $link = 'pedido.php?mesa=' . $mesa->mes_001 . '&tipo=M';
            $sql = "SELECT sit_001, ven_001 FROM venda WHERE sit_001 = 8 AND ven_025 = " . $mesa->mes_001;
            $stm = $pdo->prepare($sql);
            $stm->execute();
            $venda = $stm->fetch(PDO::FETCH_OBJ);
            $back  = (empty($venda)) ? '' : 'btn-red';
            $link  = (empty($venda)) ? $link : $link . '&venda=' . $venda->ven_001;

            if (empty($back)):
              $sql = "SELECT sit_001, ven_001 FROM venda WHERE sit_001 = 21 AND ven_025 = " . $mesa->mes_001;
              $stm = $pdo->prepare($sql);
              $stm->execute();
              $venda = $stm->fetch(PDO::FETCH_OBJ);
              $idVenda  = (empty($venda)) ? '' : $venda->ven_001;
              $back  = (empty($venda)) ? '' : 'btn-yellow';
              $link  = (empty($venda)) ? $link : 'javascript:void(0)';
            endif;
            ?>
            <a href='<?=$link?>' data-venda="<?=$idVenda?>" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored btn-mesa <?=$back?>" data-upgraded=",MaterialButton">
              <?=$mesa->mes_003?> 
            </a>
          <?php endforeach;?>
        </div>
  	  </main>
  	</div>
    

  <?php include 'includes/inc_js.php'; ?>
  <?php include 'includes/inc_notifica_js.php'; ?>
  <script>
   function preloader(){
        EasyLoading.hide();
        $('#page').show();
    }
    window.onload = preloader;


    if (localStorage.hasOwnProperty('carrinho')){
        localStorage.removeItem('carrinho')
	 }

   $(document).ready(function($) {

				$('#pesquisa').on('input', function(event) {
					 var termo = $(this).val();

					 if(termo.length >= 0){
							$.ajax({
								 url: 'ajax_pesquisa_mesa.php',
								 type: 'POST',
								 dataType: 'html',
								 data: {termo: termo},
								 beforeSend: function(){
										$('.box-comandas').html("<div class='text-center'><br><br><img src='img/aguarde.gif' width = '100'></div>");
								 },
								 success: function(retorno){
										$('.box-comandas').html(retorno);
								 }
							});

					 }
        });
        
        $(document).on('click', '.btn-yellow', function(){
            var venda = $(this).attr('data-venda');
            var autorizado = '<?= $autorizacao->b_reabrir_mesa_comanda ?>';

            if (autorizado){
              swal({
                title: 'Deseja reabrir a Mesa ?',
                type: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sim, Reabrir !',
                cancelButtonText: 'Não Reabrir !',
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn',
                buttonsStyling: false,
                reverseButtons: true
              }).then((result) => {
                if (result.value) {
                  $.ajax({
                      url: 'ajax_reabrir_venda.php',
                      type: 'POST',
                      dataType: 'json',
                      data: {venda: venda},
                      beforeSend: function(){
                          EasyLoading.show({text: 'Aguarde ...'});
                      },
                      success: function(retorno){
                          if (retorno.status == 1){
                            location.reload();
                          }else{
                            EasyLoading.hide();
                          }
                      }
                    });
                }
              })
            }else{
              swal(
                  'Alerta',
                  'Não é possível reabrir essa mesa !',
                  'warning'
                )
            }
        });
    });
  </script>
</body>
</html>