<?php 
/**
 * ARQUIVO: index.php
 * OBJETIVO: Painel de Gestão de Notas com visual DBGrid profissional em tela cheia.
 */
 session_start();
if (!isset($_SESSION['id'])) { header("Location: ../index/index.php"); exit(); }
include '../config.php';
require_once "../configuracao/modelo.php"; 

// Filtro de Status
$filtro = $_GET['status'] ?? '';
$sql = "SELECT c.*, p.reg_0150_nome 
        FROM nf_cab c
        LEFT JOIN reg_0150 p ON c.nf_cab_cod_part = p.reg_0150_cod_part";

if ($filtro !== '') {
    $statusSeguro = $mysqli->real_escape_string($filtro);
    $sql .= " WHERE c.nf_cab_status = '$statusSeguro'";
}

$sql .= " ORDER BY c.codigo DESC";
$resultado = $mysqli->query($sql);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Gestão - Meu Mec</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; margin: 0; padding: 10px; overflow: hidden; }
        
        /* Layout Full Screen */
        .main-wrapper { height: 95vh; display: flex; flex-direction: column; }
        
        /* Estilo DBGrid */
        .dbgrid-container { 
            background: white; 
            border-radius: 8px; 
            box-shadow: 0 4px 6px rgba(0,0,0,0.1); 
            display: flex;
            flex-direction: column;
            flex-grow: 1; /* Faz ocupar o restante da altura */
            overflow: hidden;
        }

        .table-responsive { 
            flex-grow: 1; 
            overflow-y: auto; /* Rolagem apenas no corpo da tabela */
        }

        .table thead { background-color: #2c3e50; color: #ffffff; position: sticky; top: 0; z-index: 10; }
        .table thead th { font-weight: 600; text-transform: uppercase; font-size: 0.85rem; letter-spacing: 0.5px; padding: 15px; border: none; }
        .table tbody tr { transition: all 0.2s ease; border-bottom: 1px solid #eee; }
        .table tbody tr:hover { background-color: #f8f9fa; cursor: pointer; }
        .table td { padding: 10px 15px; vertical-align: middle; font-size: 0.9rem; }
        
        /* Status Badges */
        .badge-status { width: 100px; font-weight: bold; padding: 6px 0; border-radius: 4px; }
        .status-P { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
        .status-F { background-color: #e2e3e5; color: #383d41; border: 1px solid #d6d8db; }
        
        .valor-nf { font-family: 'Courier New', Courier, monospace; font-weight: bold; color: #2c3e50; }
        .btn-action { transition: transform 0.1s; }
        .btn-action:active { transform: scale(0.95); }
    </style>
</head>
<body>

<div class="container-fluid main-wrapper">
    <div class="d-flex justify-content-between align-items-center mb-2 px-2">
        <div>
            <h4 class="mb-0 fw-bold text-dark">Notas Fiscais</h4>
            <p class="text-muted small mb-0">Gestão de estoque e validação financeira C140</p>
        </div>
        <div class="btn-group shadow-sm">
            <a href="index.php" class="btn btn-outline-primary <?= $filtro === '' ? 'active' : '' ?>">Todas</a>
            <a href="index.php?status=P" class="btn btn-outline-primary <?= $filtro === 'P' ? 'active' : '' ?>">Pendentes</a>
            <a href="index.php?status=F" class="btn btn-outline-primary <?= $filtro === 'F' ? 'active' : '' ?>">Fechadas</a>
        </div>
    </div>

    <div class="dbgrid-container">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th class="text-center">ID</th>
                        <th>Cliente / Nome da Nota</th>
                        <th class="text-center">Status</th>
                        <th class="text-center">Tipo</th>
                        <th class="text-end">Valor Total</th>
                        <th class="text-center">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($nota = $resultado->fetch_assoc()): ?>
                        <tr>
                            <td class="text-center fw-bold text-muted">#<?= $nota['codigo'] ?></td>
                            <td>
                                <div class="fw-bold text-dark"><?= htmlspecialchars($nota['nf_cab_nome'] ?? $nota['reg_0150_nome'] ?? 'SEM NOME') ?></div>
                                <div class="text-muted" style="font-size: 0.75rem;">Processamento Digital v2.0</div>
                            </td>
                            <td class="text-center">
                                <?php if($nota['nf_cab_status'] == 'P'): ?>
                                    <div class="badge-status status-P mx-auto">PENDENTE</div>
                                <?php else: ?>
                                    <div class="badge-status status-F mx-auto">FECHADA</div>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <span class="badge rounded-pill <?= $nota['nf_cab_c_v'] == 'E' ? 'bg-info' : 'bg-dark' ?>">
                                    <?= $nota['nf_cab_c_v'] == 'E' ? 'ENTRADA' : 'SAÍDA' ?>
                                </span>
                            </td>
                            <td class="text-end valor-nf">
                                R$ <?= number_format((float)$nota['nf_cab_tot_nf'], 2, ',', '.') ?>
                            </td>
                            <td class="text-center">
                                <div class="btn-group">
                                    <a href="visualizar.php?id=<?= $nota['codigo'] ?>" class="btn btn-outline-secondary btn-sm" title="Visualizar">
                                        <i class="bi bi-eye"></i> Visualizar
                                    </a>
                                    
                                    <?php if($nota['nf_cab_status'] == 'P'): ?>
                                        <button class="btn btn-success btn-sm fw-bold btn-action" 
                                                onclick="fecharNota(<?= $nota['codigo'] ?>)">
                                            <i class="bi bi-shield-check"></i> VALIDAR E FECHAR
                                        </button>
                                    <?php else: ?>
                                        <button class="btn btn-primary btn-sm" onclick="gerarTXT(<?= $nota['codigo'] ?>)">
                                            <i class="bi bi-file-earmark-text"></i> Gerar TXT
                                        </button>
                                        <button class="btn btn-warning btn-sm" onclick="enviarNota(<?= $nota['codigo'] ?>)">
                                            <i class="bi bi-send"></i> Enviar
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <div class="bg-light p-2 border-top d-flex justify-content-between align-items-center">
            <span class="text-muted small">Registros: <strong><?= $resultado->num_rows ?></strong></span>
            <span class="text-muted small"><?= date('d/m/Y H:i') ?></span>
        </div>
    </div>
</div>

<script>
function fecharNota(id) {
    if(confirm("Deseja iniciar o processo de fechamento da nota #" + id + "?\n\nEste processo irá:\n1. Validar financeiro (C140)\n2. Movimentar estoque (H010)\n3. Alterar status para Fechado.")) {
        fetch('processar.php?id=' + id)
            .then(response => response.json())
            .then(data => {
                if(data.status === 'sucesso') {
                    alert("SUCESSO!\n" + data.message);
                    location.reload();
                } else {
                    alert("ERRO NO PROCESSAMENTO:\n\n" + data.message);
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                alert("Erro crítico de rede ou servidor.");
            });
    }
}

function gerarTXT(id) { alert("Gerando arquivo TXT para a nota #" + id); }
function enviarNota(id) { alert("Iniciando envio da nota #" + id); }
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>