<?php
session_start();
require 'verifica_cookie.php';
require 'conexao.php';
require 'config.php';

$termo = (isset($_POST['termo'])) ? strtoupper($_POST['termo']) : '';
$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}";

if ($termo != ''):
  $sql .= "AND mes_003 = '".$termo."' ";
endif;

$sql .= " ORDER BY mes_001";
$stm = $pdo->prepare($sql);
$stm->execute();
$mesas = $stm->fetchAll(PDO::FETCH_OBJ);

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