<?php
require_once(dirname(__DIR__) . '/config/db.php');

// ===========================
// FILTRO DE STATUS
// ===========================
$filtro = $_GET['status'] ?? 'ativas';
switch ($filtro) {
    case 'inativas': $where = "WHERE flativo = 1"; break;
    case 'todas': $where = ""; break;
    default: $where = "WHERE flativo = 0";
}

// ===========================
// ORDENAÇÃO DE COLUNAS
// ===========================
$colunasPermitidas = ['dsmoeda', 'simbolo', 'formato'];
$order = $_GET['order'] ?? 'dsmoeda';
$dir = $_GET['dir'] ?? 'asc';

if (!in_array($order, $colunasPermitidas)) $order = 'dsmoeda';
$dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
$nextDir = $dir === 'asc' ? 'desc' : 'asc';

// ===========================
// PAGINAÇÃO
// ===========================
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;
if ($limit < 0) $limit = 100;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page <= 0) $page = 1;

$offset = ($page - 1) * $limit;

// Conta total de registros
$totalStmt = $pdo->query("SELECT COUNT(*) AS total FROM back.moeda " . ($where ?: ""));
$total = $totalStmt->fetch(PDO::FETCH_ASSOC)['total'];

// Calcula total de páginas
$totalPages = $limit > 0 ? ceil($total / $limit) : 1;

// Consulta principal com LIMIT/OFFSET
$sql = "SELECT * FROM back.moeda $where ORDER BY $order $dir";
if ($limit != 0) $sql .= " LIMIT $limit OFFSET $offset";
$stmt = $pdo->query($sql);
$moedas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<h4 class="mb-3"><i class="bi bi-currency-exchange"></i> Cadastro de Moedas</h4>
<hr>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <a href="?m=moedas&status=ativas" class="btn btn-outline-success btn-sm <?= $filtro=='ativas'?'active':'' ?>">Ativas</a>
        <a href="?m=moedas&status=inativas" class="btn btn-outline-secondary btn-sm <?= $filtro=='inativas'?'active':'' ?>">Inativas</a>
        <a href="?m=moedas&status=todas" class="btn btn-outline-dark btn-sm <?= $filtro=='todas'?'active':'' ?>">Todas</a>
    </div>

    <button class="btn btn-outline-light btn-sm shadow-sm border-secondary text-dark bg-light"
            data-bs-toggle="modal" data-bs-target="#modalMoeda">
        <i class="bi bi-plus-circle"></i> Nova Moeda
    </button>
</div>

<table class="table table-striped table-hover align-middle">
    <thead class="table-dark">
        <tr>
            <th>#</th>
            <th>
                <a href="?m=moedas&status=<?= $filtro ?>&order=dsmoeda&dir=<?= $nextDir ?>" class="text-white text-decoration-none">
                    Nome <?= $order === 'dsmoeda' ? ($dir === 'asc' ? '▲' : '▼') : '' ?>
                </a>
            </th>
            <th>
                <a href="?m=moedas&status=<?= $filtro ?>&order=simbolo&dir=<?= $nextDir ?>" class="text-white text-decoration-none">
                    Símbolo <?= $order === 'simbolo' ? ($dir === 'asc' ? '▲' : '▼') : '' ?>
                </a>
            </th>
            <th>
                <a href="?m=moedas&status=<?= $filtro ?>&order=formato&dir=<?= $nextDir ?>" class="text-white text-decoration-none">
                    Formato <?= $order === 'formato' ? ($dir === 'asc' ? '▲' : '▼') : '' ?>
                </a>
            </th>
            <th>Padrão</th>
            <th>Status</th>
            <th class="text-center">Ações</th>
        </tr>
    </thead>
    <tbody>
        <?php if ($moedas): ?>
            <?php foreach ($moedas as $m): ?>
                <tr>
                    <td><?= $m['cdmoeda'] ?></td>
                    <td><?= htmlspecialchars($m['dsmoeda']) ?></td>
                    <td><?= htmlspecialchars($m['simbolo']) ?></td>
                    <td><?= $m['formato'] == 'decimal' ? '0,00' : '0' ?></td>
                    <td>
                        <?= $m['padrao'] == 1 ? '<span class="badge bg-info"><i class="bi bi-check-circle"></i> Sim</span>' : '<span class="badge bg-light text-dark">Não</span>' ?>
                    </td>
                    <td>
                        <?= $m['flativo'] == 0 ? '<span class="badge bg-success">Ativa</span>' : '<span class="badge bg-secondary">Inativa</span>' ?>
                    </td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-outline-secondary"
                                data-bs-toggle="modal" data-bs-target="#modalMoeda"
                                data-id="<?= $m['cdmoeda'] ?>"
                                data-nome="<?= htmlspecialchars($m['dsmoeda']) ?>"
                                data-simbolo="<?= htmlspecialchars($m['simbolo']) ?>"
                                data-formato="<?= $m['formato'] ?>"
                                data-padrao="<?= $m['padrao'] ?>">
                            <i class="bi bi-pencil"></i>
                        </button>

                        <a href="?m=moedas&inativar=<?= $m['cdmoeda'] ?>&status=<?= $filtro ?>"
                           class="btn btn-sm btn-outline-danger"
                           onclick="return confirm('Deseja realmente inativar esta moeda?')">
                            <i class="bi bi-power"></i>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr><td colspan="6" class="text-center text-muted">Nenhuma moeda encontrada.</td></tr>
        <?php endif; ?>
    </tbody>
</table>

<!-- ======================== -->
<!-- PAGINAÇÃO -->
<!-- ======================== -->
<div class="d-flex justify-content-between align-items-center mt-3">
    <div>
        <form method="get" class="d-flex align-items-center gap-2">
            <input type="hidden" name="m" value="moedas">
            <input type="hidden" name="status" value="<?= $filtro ?>">
            <input type="hidden" name="order" value="<?= $order ?>">
            <input type="hidden" name="dir" value="<?= $dir ?>">
            <label class="text-muted small">Exibir:</label>
            <select name="limit" class="form-select form-select-sm w-auto" onchange="this.form.submit()">
                <option value="25"  <?= $limit==25?'selected':'' ?>>25</option>
                <option value="50"  <?= $limit==50?'selected':'' ?>>50</option>
                <option value="100" <?= $limit==100?'selected':'' ?>>100</option>
                <option value="500" <?= $limit==500?'selected':'' ?>>500</option>
                <option value="0"   <?= $limit==0?'selected':'' ?>>Todos *</option>
            </select>
        </form>
    </div>

    <div>
        <nav>
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?= $page<=1?'disabled':'' ?>">
                    <a class="page-link" href="?m=moedas&status=<?= $filtro ?>&order=<?= $order ?>&dir=<?= $dir ?>&limit=<?= $limit ?>&page=1">&laquo;</a>
                </li>
                <li class="page-item <?= $page<=1?'disabled':'' ?>">
                    <a class="page-link" href="?m=moedas&status=<?= $filtro ?>&order=<?= $order ?>&dir=<?= $dir ?>&limit=<?= $limit ?>&page=<?= $page-1 ?>">&lsaquo;</a>
                </li>

                <?php
                $start = max(1, $page - 2);
                $end = min($totalPages, $page + 2);
                for ($i = $start; $i <= $end; $i++): ?>
                    <li class="page-item <?= $i==$page?'active':'' ?>">
                        <a class="page-link" href="?m=moedas&status=<?= $filtro ?>&order=<?= $order ?>&dir=<?= $dir ?>&limit=<?= $limit ?>&page=<?= $i ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
                    <a class="page-link" href="?m=moedas&status=<?= $filtro ?>&order=<?= $order ?>&dir=<?= $dir ?>&limit=<?= $limit ?>&page=<?= $page+1 ?>">&rsaquo;</a>
                </li>
                <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
                    <a class="page-link" href="?m=moedas&status=<?= $filtro ?>&order=<?= $order ?>&dir=<?= $dir ?>&limit=<?= $limit ?>&page=<?= $totalPages ?>">&raquo;</a>
                </li>
            </ul>
        </nav>
    </div>

    <div class="text-muted small">
        <?= $limit>0 ? "Exibindo " . count($moedas) . " de $total registros" : "Exibindo todos os $total registros" ?>
    </div>
</div>

<!-- ======================== -->
<!-- MODAL DE CADASTRO/EDIÇÃO -->
<!-- ======================== -->
<div class="modal fade" id="modalMoeda" tabindex="-1" aria-labelledby="modalMoedaLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalMoedaLabel">Cadastrar Moeda</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="cdmoeda" id="cdmoeda">

        <div class="mb-3">
          <label>Nome da Moeda</label>
          <input type="text" class="form-control" name="dsmoeda" id="dsmoeda" required>
        </div>

        <div class="mb-3">
          <label>Símbolo</label>
          <input type="text" class="form-control" name="simbolo" id="simbolo" required>
        </div>

        <div class="mb-3">
          <label>Formato</label>
          <select class="form-select" name="formato" id="formato" required>
            <option value="decimal">0,00 (decimal)</option>
            <option value="inteiro">0 (inteiro)</option>
          </select>
        </div>

        <div class="mb-3">
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" name="padrao" id="padrao" value="1">
            <label class="form-check-label" for="padrao">
              Moeda Padrão
              <i class="bi bi-question-circle" 
                 data-bs-toggle="tooltip" 
                 title="Moeda Padrão para Calculo de Cotação"
                 style="cursor: help; color: #6c757d;"></i>
            </label>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="salvar" class="btn btn-success">Salvar</button>
      </div>
    </form>
  </div>
</div>

<script>
const modalMoeda = document.getElementById('modalMoeda');
modalMoeda.addEventListener('show.bs.modal', event => {
  const button = event.relatedTarget;
  const id = button?.getAttribute('data-id');
  const nome = button?.getAttribute('data-nome');
  const simbolo = button?.getAttribute('data-simbolo');
  const formato = button?.getAttribute('data-formato');
  const padrao = button?.getAttribute('data-padrao');

  modalMoeda.querySelector('#cdmoeda').value = id || '';
  modalMoeda.querySelector('#dsmoeda').value = nome || '';
  modalMoeda.querySelector('#simbolo').value = simbolo || '';
  modalMoeda.querySelector('#formato').value = formato || 'decimal';
  modalMoeda.querySelector('#padrao').checked = padrao == 1;

  modalMoeda.querySelector('#modalMoedaLabel').innerText = id ? 'Editar Moeda' : 'Cadastrar Moeda';

  // Inicializar tooltips
  const tooltipElements = modalMoeda.querySelectorAll('[data-bs-toggle="tooltip"]');
  tooltipElements.forEach(el => {
    const tooltip = new bootstrap.Tooltip(el);
  });
});
</script>

<?php
// ========================
// CRUD SALVAR / INATIVAR
// ========================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['salvar'])) {
    $id = $_POST['cdmoeda'] ?? null;
    $nome = trim($_POST['dsmoeda']);
    $simbolo = trim($_POST['simbolo']);
    $formato = $_POST['formato'];
    $padrao = isset($_POST['padrao']) ? 1 : 0;

    // Validação: Se tentando salvar como padrão, verifica se já existe outra
    if ($padrao == 1) {
        $stmt = $pdo->prepare("SELECT COUNT(*) AS total FROM back.moeda WHERE padrao=1 AND cdmoeda != ?");
        $stmt->execute([$id ?? -1]);
        $resultado = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($resultado['total'] > 0) {
            echo "<script>
                alert('Já existe uma moeda padrão cadastrada!\\nNão é permitido ter mais de uma moeda padrão para cálculo de cotação.');
                window.history.back();
            </script>";
            exit;
        }
    }

    if ($id) {
        $stmt = $pdo->prepare("UPDATE back.moeda SET dsmoeda=?, simbolo=?, formato=?, padrao=? WHERE cdmoeda=?");
        $stmt->execute([$nome, $simbolo, $formato, $padrao, $id]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO back.moeda (dsmoeda, simbolo, formato, padrao) VALUES (?, ?, ?, ?)");
        $stmt->execute([$nome, $simbolo, $formato, $padrao]);
    }

    echo "<script>window.location='?m=moedas';</script>";
}

if (isset($_GET['inativar'])) {
    $id = $_GET['inativar'];
    $pdo->prepare("UPDATE back.moeda SET flativo = 1 WHERE cdmoeda = ?")->execute([$id]);
    echo "<script>window.location='?m=moedas';</script>";
}
?>
