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

function calculaTempo($hora_inicial, $hora_final)
{
  $inicio = DateTime::createFromFormat('H:i:s', $hora_inicial);
  $fim = DateTime::createFromFormat('H:i:s', $hora_final);
  $intervalo = $inicio->diff($fim);
  print $intervalo->format('%H:%I:%S');
}

$venda = (isset($_GET['venda'])) ? $_GET['venda'] : '';
$item  = (isset($_GET['item'])) ? $_GET['item'] : '';

$labelControle = '';
if ($_SESSION['TIPO'] == 'M'):
  $labelControle = 'Mesa ' . str_pad($_SESSION['CONTROLE'], 2, '0', STR_PAD_LEFT);
elseif ($_SESSION['TIPO'] == 'C'):

  switch (TIPO_COMANDA):
    case 0:
      if (!empty($_SESSION['CONTROLE'])):
        $labelControle = 'Comanda ' . str_pad($_SESSION['CONTROLE'], 2, '0', STR_PAD_LEFT);
      endif;

      if (!empty($_SESSION['CLIENTE'])):
        $labelControle = $_SESSION['CLIENTE'];
        $labelControle .= (!empty($_SESSION['CONTROLE'])) ? ' | Nº: ' . str_pad($_SESSION['CONTROLE'], 2, '0', STR_PAD_LEFT) : '';
      endif;
      break;
    case 1:
      if (!empty($_SESSION['CONTROLE'])):
        $labelControle = 'Comanda ' . str_pad($_SESSION['CONTROLE'], 2, '0', STR_PAD_LEFT);
      endif;
      break;
    case 2:
      if (!empty($_SESSION['CONTROLE'])):
        $labelControle = 'Com.: ' . str_pad($_SESSION['CONTROLE'], 2, '0', STR_PAD_LEFT);
      endif;

      if (!empty($_SESSION['CLIENTE'])):
        $labelControle .= (!empty($_SESSION['CONTROLE'])) ? ' | ' . str_pad($_SESSION['CLIENTE'], 2, '0', STR_PAD_LEFT) : '';
      endif;
      break;
    default:
      $labelControle = 'Não Identificado';
      break;
  endswitch;
endif;

$pdo  = Conexao::getInstance();
$sql = "SELECT i.ite_001, i.mat_001, i.ite_002, m.mat_003, i.ite_011, i.ite_005, i.ven_001, ";
$sql .= "i.ite_006, i.ite_009, i.tamanho, i.gar_001, v.ven_025, v.ven_026, v.ven_024, m.b_venda_tamanho ";
$sql .= "FROM venda v INNER JOIN vendaitem i ON v.ven_001 = i.ven_001 ";
$sql .= "INNER JOIN materiais m ON m.mat_001 = i.mat_001 ";
$sql .= "WHERE i.sit_001 = 4 AND v.sit_001 = 8 ";
$sql .= "AND i.ite_001 = {$item} AND v.ven_001 = {$venda}";
$sql .= "ORDER BY i.ite_001 ";
$stm = $pdo->prepare($sql);
$stm->execute();
$item = $stm->fetch(PDO::FETCH_OBJ);

$sql = 'SELECT o.descricao, o.valor ';
$sql .= 'FROM vendaitemopcional v INNER JOIN opcional o ON v.id_opcional = o.id_opcional ';
$sql .= 'WHERE id_venda = :id_venda and id_vendaitem = :item';
$stm = $pdo->prepare($sql);
$stm->bindValue(':id_venda', $item->ven_001);
$stm->bindValue(':item', $item->ite_001);
$stm->execute();
$opcionais = $stm->fetchAll(PDO::FETCH_OBJ);

$sql = 'SELECT usu_002 FROM usuarios ';
$sql .= 'WHERE usu_001 = :id_usuario';
$stm = $pdo->prepare($sql);
$stm->bindValue(':id_usuario', $item->gar_001);
$stm->execute();
$usuario = $stm->fetch(PDO::FETCH_OBJ);

$sql = 'SELECT b_cancelamento_mesa 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);

// Busca dados do cliente vinculado à venda
$clienteVenda = null;
$nomeClienteVenda = '';
$idClienteVenda = 0;
if (!empty($venda)) :
  $sql = "SELECT COALESCE(cli_001, 0) as cli_001, ven_027 FROM venda WHERE ven_001 = :venda";
  $stm = $pdo->prepare($sql);
  $stm->bindValue(':venda', $venda);
  $stm->execute();
  $clienteVenda = $stm->fetch(PDO::FETCH_OBJ);
  if ($clienteVenda) :
    $idClienteVenda = $clienteVenda->cli_001;
    if (!empty($idClienteVenda)) :
      $sql = "SELECT cli_002 FROM clientes WHERE cli_001 = :id AND sit_001 = 4";
      $stm = $pdo->prepare($sql);
      $stm->bindValue(':id', $idClienteVenda);
      $stm->execute();
      $dadosCli = $stm->fetch(PDO::FETCH_OBJ);
      if ($dadosCli) :
        $nomeClienteVenda = $dadosCli->cli_002;
      endif;
    elseif (!empty($clienteVenda->ven_027)) :
      $nomeClienteVenda = $clienteVenda->ven_027;
    endif;
  endif;
endif;

$sql = "SELECT DISTINCT tamanho_p, tamanho_m, tamanho_g, tamanho_gg, tamanho_extra ";
$sql .= "FROM desc_tamanho_material ";
$stm = $pdo->prepare($sql);
$stm->execute();
$tamanhos = $stm->fetch(PDO::FETCH_OBJ);

switch ($item->tamanho):
  case 'P':
    $descricao = $tamanhos->tamanho_p;
    break;
  case 'M':
    $descricao = $tamanhos->tamanho_m;
    break;
  case 'G':
    $descricao = $tamanhos->tamanho_g;
    break;
  case 'GG':
    $descricao = $tamanhos->tamanho_gg;
    break;
  case 'E':
    $descricao = $tamanhos->tamanho_extra;
    break;
endswitch;

?>
<!DOCTYPE html>
<html>

<head>
  <title>Comanda Eletrônica</title>
  <?php require 'includes/inc_head.php'; ?>
  <style>
    * {
      box-sizing: border-box;
    }

    .det-page {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      background: #f5f6fa;
    }

    .det-header {
      background: #3f51b5;
      color: #fff;
      padding: 10px 12px;
      display: flex;
      align-items: center;
      gap: 8px;
      flex-shrink: 0;
      z-index: 10;
    }

    .det-header .btn-voltar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      border: none;
      background: rgba(255, 255, 255, 0.15);
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      flex-shrink: 0;
    }

    .det-header .btn-voltar i {
      font-size: 20px;
    }

    .det-header-title {
      font-size: 15px;
      font-weight: 700;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      flex: 1;
    }

    .det-content {
      flex: 1;
      padding: 16px 12px 100px;
      width: 100%;
    }

    .det-card {
      background: #fff;
      border-radius: 14px;
      border: 1px solid #e0e3eb;
      overflow: hidden;
    }

    .det-card-header {
      background: linear-gradient(135deg, #3f51b5, #5c6bc0);
      padding: 16px;
      color: #fff;
    }

    .det-card-header-nome {
      font-size: 15px;
      font-weight: 700;
      line-height: 1.3;
    }

    .det-card-header-qtde {
      font-size: 12px;
      opacity: 0.85;
      margin-top: 2px;
    }

    .det-card-body {
      padding: 0;
    }

    .det-row {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f3;
    }

    .det-row:last-child {
      border-bottom: none;
    }

    .det-row-icon {
      width: 34px;
      height: 34px;
      border-radius: 50%;
      background: #e8eaf6;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }

    .det-row-icon i {
      font-size: 18px;
      color: #3f51b5;
    }

    .det-row-info {
      flex: 1;
      min-width: 0;
    }

    .det-row-label {
      font-size: 10px;
      font-weight: 700;
      text-transform: uppercase;
      color: #9e9e9e;
      letter-spacing: 0.3px;
    }

    .det-row-value {
      font-size: 14px;
      font-weight: 600;
      color: #212121;
      word-break: break-word;
    }

    .det-row-icon.tempo {
      background: #fff3e0;
    }

    .det-row-icon.tempo i {
      color: #e65100;
    }

    .det-opcionais-list {
      padding: 0;
      margin: 0;
      list-style: none;
    }

    .det-opcionais-list li {
      padding: 2px 0;
      font-size: 13px;
      font-weight: 500;
      color: #424242;
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .det-opcionais-list li::before {
      content: '';
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #3f51b5;
      flex-shrink: 0;
    }

    .det-aviso {
      background: #fff3e0;
      border: 1.5px solid #ffb74d;
      border-radius: 10px;
      padding: 10px 14px;
      margin-top: 14px;
      font-size: 12px;
      font-weight: 600;
      color: #e65100;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .det-aviso i {
      font-size: 18px;
    }

    /* Cliente */
    .det-header .btn-cliente-header {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      border: none;
      background: rgba(255, 255, 255, 0.15);
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      flex-shrink: 0;
      position: relative;
    }

    .det-header .btn-cliente-header i {
      font-size: 20px;
    }

    .det-header .btn-cliente-header .badge-cliente {
      position: absolute;
      top: -2px;
      right: -2px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background: #4caf50;
      border: 2px solid #3f51b5;
      display: none;
    }

    .det-header .btn-cliente-header .badge-cliente.ativo {
      display: block;
    }

    .det-cliente-info {
      background: #fff;
      border-radius: 14px;
      border: 1px solid #e0e3eb;
      padding: 14px 16px;
      margin-bottom: 14px;
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .det-cliente-info .cli-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: #e8f5e9;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }

    .det-cliente-info .cli-icon i {
      font-size: 22px;
      color: #2e7d32;
    }

    .det-cliente-info .cli-dados {
      flex: 1;
      min-width: 0;
    }

    .det-cliente-info .cli-label {
      font-size: 10px;
      font-weight: 700;
      text-transform: uppercase;
      color: #9e9e9e;
      letter-spacing: 0.3px;
    }

    .det-cliente-info .cli-nome {
      font-size: 14px;
      font-weight: 600;
      color: #212121;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .det-cliente-info .cli-trocar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      border: 1px solid #dde1ea;
      background: #fff;
      color: #3f51b5;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      flex-shrink: 0;
    }

    .det-cliente-info .cli-trocar i {
      font-size: 18px;
    }

    /* Modal Cliente */
    .modal-cliente-overlay {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 9999;
      justify-content: center;
      align-items: flex-start;
      padding-top: 50px;
    }

    .modal-cliente-container {
      background: #fff;
      border-radius: 14px;
      width: 94%;
      max-width: 440px;
      margin: 0 auto;
      max-height: 85vh;
      display: flex;
      flex-direction: column;
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
      overflow: hidden;
    }

    .modal-cliente-header {
      padding: 16px 20px;
      border-bottom: 1px solid #e0e0e0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #f5f6fa;
    }

    .modal-cliente-header h5 {
      margin: 0;
      color: #3f51b5;
      font-size: 17px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .modal-cliente-header h5 i {
      font-size: 20px;
    }

    .modal-cliente-close {
      color: #999;
      font-size: 24px;
      text-decoration: none;
      cursor: pointer;
      background: none;
      border: none;
      line-height: 1;
    }

    .modal-cliente-search {
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f3;
    }

    .modal-cliente-search input {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ccc;
      border-radius: 8px;
      font-size: 15px;
      box-sizing: border-box;
      outline: none;
      transition: border-color 0.2s;
    }

    .modal-cliente-search input:focus {
      border-color: #3f51b5;
    }

    .modal-cliente-results {
      flex: 1;
      overflow-y: auto;
      padding: 0 16px 12px;
      -webkit-overflow-scrolling: touch;
      max-height: 40vh;
    }

    .modal-cliente-cadastro {
      border-top: 1px solid #e0e0e0;
      padding: 14px 16px;
      background: #fafafa;
    }

    .modal-cliente-cadastro summary {
      font-size: 13px;
      font-weight: 700;
      color: #3f51b5;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 6px;
      user-select: none;
    }

    .modal-cliente-cadastro summary i {
      font-size: 18px;
    }

    .modal-cliente-cadastro .campos-cadastro {
      margin-top: 12px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .modal-cliente-cadastro .campo-grupo {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .modal-cliente-cadastro .campo-grupo label {
      font-size: 12px;
      color: #666;
      display: block;
    }

    .modal-cliente-cadastro .campo-grupo input {
      width: 100%;
      padding: 10px;
      margin: 8px 0;
      border: 1px solid #ccc;
      border-radius: 4px;
      font-size: 15px;
      box-sizing: border-box;
      outline: none;
      transition: border-color 0.2s;
    }

    .modal-cliente-cadastro .campo-grupo input:focus {
      border-color: #3f51b5;
    }

    .modal-cliente-cadastro .campo-grupo input.input-nome {
      text-transform: uppercase;
      font-weight: bold;
    }

    .msg-erro-det {
      color: #e74c3c;
      font-size: 13px;
      text-align: center;
      margin: 5px 0;
      min-height: 18px;
    }

    .modal-cadastro-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      gap: 10px;
    }

    .modal-cadastro-actions button {
      flex: 1;
      padding: 10px;
      border: none;
      border-radius: 4px;
      font-size: 14px;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.2s;
    }

    .btn-cancelar-cadastro {
      background-color: #e74c3c;
      color: #fff;
    }

    .btn-salvar-cadastro {
      background-color: #3f51b5;
      color: #fff;
    }

    .det-footer {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1000;
      display: flex;
    }

    .det-footer .btn-footer {
      flex: 1;
      height: 50px;
      border: none;
      font-size: 14px;
      font-weight: 700;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      color: #fff;
      transition: all 0.15s ease;
    }

    .det-footer .btn-footer:active {
      filter: brightness(0.88);
    }

    .det-footer .btn-footer i {
      font-size: 20px;
    }

    .det-footer .btn-voltar-footer {
      background: #3f51b5;
    }

    .det-footer .btn-excluir-footer {
      background: #e74c3c;
    }

    /* ── Dark Theme Overrides ── */
    [data-theme="dark"] .det-page {
      background: var(--bg-body);
    }

    [data-theme="dark"] .det-header {
      background: var(--bg-header);
    }

    [data-theme="dark"] .det-card {
      background: var(--bg-card);
      border-color: var(--border-color);
    }

    [data-theme="dark"] .det-card-header {
      background: linear-gradient(135deg, #1a237e, #283593);
    }

    [data-theme="dark"] .det-row {
      border-bottom-color: var(--border-color);
    }

    [data-theme="dark"] .det-row-icon {
      background: #1a237e;
    }

    [data-theme="dark"] .det-row-icon i {
      color: var(--color-primary);
    }

    [data-theme="dark"] .det-row-icon.tempo {
      background: #3e2200;
    }

    [data-theme="dark"] .det-row-icon.tempo i {
      color: #ffb74d;
    }

    [data-theme="dark"] .det-row-label {
      color: var(--text-secondary);
    }

    [data-theme="dark"] .det-row-value {
      color: var(--text-primary);
    }

    [data-theme="dark"] .det-opcionais-list li {
      color: var(--text-primary);
    }

    [data-theme="dark"] .det-aviso {
      background: #3e2200;
      border-color: #8a5600;
      color: #ffb74d;
    }

    /* Cliente info */
    [data-theme="dark"] .det-cliente-info {
      background: var(--bg-card);
      border-color: var(--border-color);
    }

    [data-theme="dark"] .det-cliente-info .cli-icon {
      background: #1b3a1d;
    }

    [data-theme="dark"] .det-cliente-info .cli-icon i {
      color: #66bb6a;
    }

    [data-theme="dark"] .det-cliente-info .cli-label {
      color: var(--text-secondary);
    }

    [data-theme="dark"] .det-cliente-info .cli-nome {
      color: var(--text-primary);
    }

    [data-theme="dark"] .det-cliente-info .cli-trocar {
      border-color: var(--border-color);
      background: var(--bg-surface);
      color: var(--color-primary);
    }

    /* Modal cliente */
    [data-theme="dark"] .modal-cliente-container {
      background: var(--bg-card);
    }

    [data-theme="dark"] .modal-cliente-header {
      background: var(--bg-surface);
      border-bottom-color: var(--border-color);
    }

    [data-theme="dark"] .modal-cliente-header h5 {
      color: var(--color-primary);
    }

    [data-theme="dark"] .modal-cliente-close {
      color: var(--text-secondary);
    }

    [data-theme="dark"] .modal-cliente-search {
      border-bottom-color: var(--border-color);
    }

    [data-theme="dark"] .modal-cliente-search input {
      background: var(--bg-input);
      color: var(--text-primary);
      border-color: var(--border-color);
    }

    [data-theme="dark"] .modal-cliente-cadastro {
      background: var(--bg-surface);
      border-top-color: var(--border-color);
    }

    [data-theme="dark"] .modal-cliente-cadastro summary {
      color: var(--color-primary);
    }

    [data-theme="dark"] .modal-cliente-cadastro .campo-grupo label {
      color: var(--text-secondary);
    }

    [data-theme="dark"] .modal-cliente-cadastro .campo-grupo input {
      background: var(--bg-input);
      color: var(--text-primary);
      border-color: var(--border-color);
    }
  </style>
</head>

<body>
  <script>
    loadPagina()
  </script>
  <div class="det-page" id="page" style="display:none">

    <!-- HEADER -->
    <div class="det-header">
      <button class="btn-voltar" onclick="window.history.go(-1)">
        <i class="material-icons">arrow_back</i>
      </button>
      <span class="det-header-title"><?= htmlspecialchars($labelControle) ?> — Detalhes</span>
      <button class="btn-cliente-header" id="btn-abrir-cliente" title="Cliente da venda">
        <i class="material-icons">person_add</i>
        <span class="badge-cliente <?= !empty($idClienteVenda) || !empty($nomeClienteVenda) ? 'ativo' : '' ?>"></span>
      </button>
    </div>

    <?php if ($item): ?>
      <div class="det-content">

        <!-- Info do cliente vinculado -->
        <div class="det-cliente-info" id="det-cliente-info" style="<?= empty($idClienteVenda) && empty($nomeClienteVenda) ? 'display:none;' : '' ?>">
          <div class="cli-icon">
            <i class="material-icons">person</i>
          </div>
          <div class="cli-dados">
            <div class="cli-label">Cliente</div>
            <div class="cli-nome" id="det-cli-nome"><?= htmlspecialchars($nomeClienteVenda) ?></div>
          </div>
          <button class="cli-trocar" id="btn-trocar-cli-det" title="Trocar cliente">
            <i class="material-icons">swap_horiz</i>
          </button>
        </div>
        <div class="det-card">
          <div class="det-card-header">
            <div class="det-card-header-nome"><?= htmlspecialchars($item->mat_003) ?></div>
            <div class="det-card-header-qtde">Qtde: <?= number_format($item->ite_002, 3, ',', '.') ?></div>
          </div>
          <div class="det-card-body">
            <div class="det-row">
              <div class="det-row-icon"><i class="material-icons">person</i></div>
              <div class="det-row-info">
                <div class="det-row-label">Garçom</div>
                <div class="det-row-value"><?= htmlspecialchars($usuario->usu_002) ?></div>
              </div>
            </div>
            <div class="det-row">
              <div class="det-row-icon"><i class="material-icons">attach_money</i></div>
              <div class="det-row-info">
                <div class="det-row-label">Valor</div>
                <div class="det-row-value">R$ <?= number_format($item->ite_005, 2, ',', '.') ?></div>
              </div>
            </div>
            <div class="det-row">
              <div class="det-row-icon"><i class="material-icons">access_time</i></div>
              <div class="det-row-info">
                <div class="det-row-label">Hora</div>
                <div class="det-row-value"><?= htmlspecialchars($item->ite_009) ?></div>
              </div>
            </div>
            <div class="det-row">
              <div class="det-row-icon tempo"><i class="material-icons">timer</i></div>
              <div class="det-row-info">
                <div class="det-row-label">Tempo Decorrido</div>
                <div class="det-row-value"><?= calculaTempo($item->ite_009, date('H:i:s')) ?></div>
              </div>
            </div>
            <?php if ($item->b_venda_tamanho && !empty($item->tamanho)): ?>
              <div class="det-row">
                <div class="det-row-icon"><i class="material-icons">straighten</i></div>
                <div class="det-row-info">
                  <div class="det-row-label">Tamanho</div>
                  <div class="det-row-value"><?= htmlspecialchars($descricao) ?></div>
                </div>
              </div>
            <?php endif; ?>
            <?php if (!empty($opcionais)): ?>
              <div class="det-row">
                <div class="det-row-icon"><i class="material-icons">tune</i></div>
                <div class="det-row-info">
                  <div class="det-row-label">Opcionais</div>
                  <div class="det-row-value">
                    <ul class="det-opcionais-list">
                      <?php foreach ($opcionais as $opcional): ?>
                        <li><?= htmlspecialchars($opcional->descricao) ?></li>
                      <?php endforeach; ?>
                    </ul>
                  </div>
                </div>
              </div>
            <?php endif; ?>
            <?php if (!empty($item->ite_006)): ?>
              <div class="det-row">
                <div class="det-row-icon"><i class="material-icons">speaker_notes</i></div>
                <div class="det-row-info">
                  <div class="det-row-label">Observação</div>
                  <div class="det-row-value"><?= htmlspecialchars($item->ite_006) ?></div>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>

        <?php if ($autorizacao->b_cancelamento_mesa): ?>
          <div class="det-aviso">
            <i class="material-icons">warning</i>
            <span>Itens fracionados serão excluídos todos os produtos</span>
          </div>
        <?php endif; ?>
      </div>

      <!-- FOOTER -->
      <div class="det-footer">
        <button class="btn-footer btn-voltar-footer" onclick="window.history.go(-1)">
          <i class="material-icons">arrow_back</i> VOLTAR
        </button>
        <?php if ($autorizacao->b_cancelamento_mesa): ?>
          <button class="btn-footer btn-excluir-footer btn-excluir">
            <i class="material-icons">delete</i> EXCLUIR
          </button>
        <?php endif; ?>
      </div>

      <!-- Modal Cliente -->
      <div class="modal-cliente-overlay" id="modal-cliente-det">
        <div class="modal-cliente-container">
          <div class="modal-cliente-header">
            <h5><i class="material-icons">person_search</i> Cliente</h5>
            <button class="modal-cliente-close" id="btn-fechar-cliente-det">&times;</button>
          </div>
          <div class="modal-cliente-search">
            <input type="text" id="pesquisa-cli-det" placeholder="Pesquisar por Nome ou Telefone" autocomplete="off">
          </div>
          <div class="modal-cliente-results" id="box-cli-det"></div>
          <div class="modal-cliente-cadastro">
            <details id="details-cadastro">
              <summary><i class="material-icons">person_add</i> Cadastrar novo cliente</summary>
              <div class="campos-cadastro">
                <div class="msg-erro-det" id="msg-erro-cli-det"></div>
                <div class="campo-grupo">
                  <label>Nome *</label>
                  <input type="text" id="cli-novo-nome" class="input-nome" placeholder="Nome do cliente" maxlength="100" autocomplete="off">
                </div>
                <div class="campo-grupo">
                  <label>Telefone *</label>
                  <input type="tel" id="cli-novo-telefone" placeholder="(00) 00000-0000" maxlength="15" autocomplete="off">
                </div>
                <div class="campo-grupo">
                  <label>CPF (opcional)</label>
                  <input type="text" id="cli-novo-cpf" placeholder="000.000.000-00" maxlength="14" autocomplete="off">
                </div>
                <div class="modal-cadastro-actions">
                  <button type="button" class="btn-cancelar-cadastro" id="btn-cancelar-cadastro-det">Cancelar</button>
                  <button type="button" class="btn-salvar-cadastro" id="btn-cadastrar-cli-det">Salvar</button>
                </div>
              </div>
            </details>
          </div>
        </div>
      </div>

    <?php else: ?>
      <div class="det-content" style="display:flex; align-items:center; justify-content:center;">
        <div style="text-align:center; color:#9e9e9e;">
          <i class="material-icons" style="font-size:56px; display:block; margin-bottom:12px; color:#e0e0e0;">search_off</i>
          <p style="font-size:15px; font-weight:600;">Item não encontrado.</p>
        </div>
      </div>
      <div class="det-footer">
        <button class="btn-footer btn-voltar-footer" onclick="window.history.go(-1)" style="width:100%;">
          <i class="material-icons">arrow_back</i> VOLTAR
        </button>
      </div>
    <?php endif; ?>
  </div>

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

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

      var venda = '<?= $venda ?>';

      // === CLIENTE ===
      function abrirModalCliente() {
        if (!venda || venda === '') {
          swal('Alerta', 'Venda não identificada!', 'warning');
          return;
        }
        $('#pesquisa-cli-det').val('');
        $('#box-cli-det').html('');
        $('#details-cadastro').removeAttr('open');
        $('#cli-novo-nome').val('');
        $('#cli-novo-telefone').val('');
        $('#cli-novo-cpf').val('');
        $('#msg-erro-cli-det').text('');
        $('#modal-cliente-det').css('display', 'flex');
        setTimeout(function() {
          $('#pesquisa-cli-det').focus();
        }, 200);
      }

      function fecharModalCliente() {
        $('#modal-cliente-det').hide();
      }

      function vincularCliente(id, nome) {
        $.ajax({
          url: 'ajax_gravar_nome_mesa.php',
          type: 'POST',
          dataType: 'json',
          data: {
            venda: venda,
            id_cliente: id
          },
          success: function(retorno) {
            if (retorno.status == 1) {
              $('#det-cli-nome').text(nome);
              $('#det-cliente-info').show();
              $('.badge-cliente').addClass('ativo');
              fecharModalCliente();
              Snackbar.show({
                text: 'Cliente vinculado com sucesso!',
                actionText: 'Fechar',
                duration: 1500,
                pos: 'bottom-left'
              });
            } else {
              $('#msg-erro-cli-det').text('Erro ao vincular cliente!');
            }
          },
          error: function() {
            $('#msg-erro-cli-det').text('Erro de comunicação com o servidor!');
          }
        });
      }

      // Abrir modal pelo header ou botão trocar
      $('#btn-abrir-cliente, #btn-trocar-cli-det').on('click', function() {
        abrirModalCliente();
      });

      // Fechar modal
      $('#btn-fechar-cliente-det').on('click', fecharModalCliente);
      $('#modal-cliente-det').on('click', function(e) {
        if (e.target === this) fecharModalCliente();
      });

      // Pesquisa de clientes
      var timerPesqCli;
      $(document).on('input', '#pesquisa-cli-det', function() {
        var termo = $(this).val();
        clearTimeout(timerPesqCli);
        if (termo.length < 2) {
          $('#box-cli-det').html('');
          return;
        }
        timerPesqCli = setTimeout(function() {
          $.ajax({
            url: 'ajax_pesquisa_cliente.php',
            type: 'POST',
            dataType: 'html',
            data: {
              termo: termo
            },
            beforeSend: function() {
              $('#box-cli-det').html("<div class='text-center' style='padding:16px;'><img src='img/aguarde.gif' width='50'></div>");
            },
            success: function(retorno) {
              $('#box-cli-det').html(retorno);
            }
          });
        }, 300);
      });

      // Selecionar cliente da pesquisa
      $(document).on('click', '#box-cli-det .btn-cliente-resultado', function() {
        var id = $(this).data('id');
        var nome = $(this).data('nome');
        vincularCliente(id, nome);
      });

      // Máscara telefone
      function mascaraTelefoneDet(valor) {
        valor = valor.replace(/\D/g, '');
        if (valor.length > 11) valor = valor.substring(0, 11);
        if (valor.length > 10) {
          valor = valor.replace(/^(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
        } else if (valor.length > 6) {
          valor = valor.replace(/^(\d{2})(\d{4})(\d{0,4})/, '($1) $2-$3');
        } else if (valor.length > 2) {
          valor = valor.replace(/^(\d{2})(\d{0,5})/, '($1) $2');
        } else if (valor.length > 0) {
          valor = valor.replace(/^(\d{0,2})/, '($1');
        }
        return valor;
      }

      // Máscara CPF
      function mascaraCPFDet(valor) {
        valor = valor.replace(/\D/g, '');
        if (valor.length > 11) valor = valor.substring(0, 11);
        if (valor.length > 9) {
          valor = valor.replace(/^(\d{3})(\d{3})(\d{3})(\d{0,2})/, '$1.$2.$3-$4');
        } else if (valor.length > 6) {
          valor = valor.replace(/^(\d{3})(\d{3})(\d{0,3})/, '$1.$2.$3');
        } else if (valor.length > 3) {
          valor = valor.replace(/^(\d{3})(\d{0,3})/, '$1.$2');
        }
        return valor;
      }

      $(document).on('input', '#cli-novo-telefone', function() {
        $(this).val(mascaraTelefoneDet($(this).val()));
      });

      $(document).on('input', '#cli-novo-cpf', function() {
        $(this).val(mascaraCPFDet($(this).val()));
      });

      // Nome sempre maiúsculo
      $(document).on('input', '#cli-novo-nome', function() {
        $(this).val($(this).val().toUpperCase());
      });

      // Cancelar cadastro (fechar details)
      $('#btn-cancelar-cadastro-det').on('click', function() {
        $('#msg-erro-cli-det').text('');
        $('#cli-novo-nome').val('');
        $('#cli-novo-telefone').val('');
        $('#cli-novo-cpf').val('');
        $('#details-cadastro').removeAttr('open');
      });

      // Cadastrar e vincular
      $('#btn-cadastrar-cli-det').on('click', function() {
        var nome = $('#cli-novo-nome').val().trim();
        var telefone = $('#cli-novo-telefone').val().trim();
        var cpf = $('#cli-novo-cpf').val().trim();

        $('#msg-erro-cli-det').text('');

        if (nome.length < 3) {
          $('#msg-erro-cli-det').text('O nome deve ter no mínimo 3 caracteres!');
          $('#cli-novo-nome').focus();
          return;
        }
        if (!telefone || telefone.replace(/\D/g, '').length < 10) {
          $('#msg-erro-cli-det').text('Informe um telefone válido!');
          $('#cli-novo-telefone').focus();
          return;
        }

        var btn = $(this);
        btn.prop('disabled', true).text('Salvando...');

        $.ajax({
          url: 'ajax_gravar_cliente.php',
          type: 'POST',
          dataType: 'json',
          data: {
            nome: nome,
            telefone: telefone,
            cpf: cpf
          },
          success: function(retorno) {
            btn.prop('disabled', false).text('Salvar');
            if (retorno.status == '1') {
              vincularCliente(retorno.id, retorno.nome);
            } else {
              $('#msg-erro-cli-det').text(retorno.text);
            }
          },
          error: function() {
            btn.prop('disabled', false).text('Salvar');
            $('#msg-erro-cli-det').text('Erro ao comunicar com o servidor!');
          }
        });
      });

      // === EXCLUIR ===
      $('.btn-excluir').click(function(event) {
        var item = '<?= $item->ite_001 ?>';
        var venda = '<?= $venda ?>';

        swal({
          title: 'Excluir Item?',
          type: 'question',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Sim, Excluir!',
          cancelButtonText: 'Não Excluir!',
          confirmButtonClass: 'btn btn-success',
          cancelButtonClass: 'btn btn-danger',
          buttonsStyling: false,
          reverseButtons: true
        }).then((result) => {
          if (result.value) {
            $.ajax({
              url: 'ajax_excluir_produto.php',
              type: 'POST',
              dataType: 'JSON',
              data: {
                id_venda: venda,
                item: item
              },
              beforeSend: function() {
                ProcessingModal.show({});
              },
              success: function(retorno) {
                ProcessingModal.hide();
                if (retorno.status == 1) {
                  Snackbar.show({
                    text: 'Produto excluído com sucesso!',
                    actionText: 'Fechar',
                    duration: 2000,
                    pos: 'bottom-left'
                  });
                  setTimeout(function() {
                    window.location = 'pedido.php?venda=<?= $venda ?>&tipo=<?= $item->ven_024 ?>';
                  }, 1000)
                }
              }
            });
          }
        })
      });

    });
  </script>
</body>

</html>