<?php
// /gabinete/src/views/documentos/lista.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../models/Documento.php';

// Protege rota
if (empty($_SESSION['user_id'])) {
    header('Location: ' . BASE_URL . '/login.php');
    exit;
}

$documento = new Documento();

// Parâmetros de busca e filtros
$busca = $_GET['busca'] ?? '';
$categoria = $_GET['categoria'] ?? '';
$tipo_midia = $_GET['tipo_midia'] ?? '';
$data_inicio = $_GET['data_inicio'] ?? '';
$data_fim = $_GET['data_fim'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

// Buscar documentos
try {
    $filtros = [
        'busca' => $busca,
        'categoria' => $categoria,
        'tipo_midia' => $tipo_midia,
        'data_inicio' => $data_inicio,
        'data_fim' => $data_fim,
        'limit' => $limit,
        'offset' => $offset
    ];
    
    $documentos = $documento->buscarComFiltros($filtros);
    $total = $documento->contarComFiltros($filtros);
    $totalPaginas = ceil($total / $limit);
    
    // Estatísticas
    $stats = $documento->obterEstatisticas();
    
} catch (Exception $e) {
    $erro = "Erro ao carregar documentos: " . $e->getMessage();
    $documentos = [];
    $total = 0;
    $totalPaginas = 0;
    $stats = [];
}

$nome = $_SESSION['nome'] ?? 'Usuário';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documentos - Lista</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #0B1F3A;
            --secondary-color: #102B54;
            --accent-color: #3B82F6;
        }
        
        .navbar-custom {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        }
        
        .card-stats {
            border-left: 4px solid var(--accent-color);
        }
        
        .file-icon {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            color: white;
            font-size: 18px;
        }
        
        .file-icon.documento { background: #6366f1; }
        .file-icon.imagem { background: #10b981; }
        .file-icon.video { background: #f59e0b; }
        .file-icon.audio { background: #ef4444; }
        
        .table-hover tbody tr:hover {
            background-color: #f8f9fa;
        }
        
        .badge-categoria {
            font-size: 0.75rem;
        }
        
        .search-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <span class="navbar-brand">
                <i class="bi bi-folder-fill me-2"></i>
                Documentos & Multimídia
            </span>
            <div class="d-flex align-items-center text-white">
                <span class="me-3">Olá, <?= htmlspecialchars($nome) ?></span>
                <a href="<?= BASE_URL ?>/src/views/dashboard/" class="btn btn-outline-light btn-sm">
                    <i class="bi bi-house-fill me-1"></i>Painel
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <!-- Estatísticas -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-muted mb-0">Total de Documentos</h5>
                                <h3 class="mb-0"><?= number_format($stats['total'] ?? 0) ?></h3>
                            </div>
                            <div class="file-icon documento">
                                <i class="bi bi-file-earmark-text"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-muted mb-0">Imagens</h5>
                                <h3 class="mb-0"><?= number_format($stats['imagens'] ?? 0) ?></h3>
                            </div>
                            <div class="file-icon imagem">
                                <i class="bi bi-image"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-muted mb-0">Vídeos</h5>
                                <h3 class="mb-0"><?= number_format($stats['videos'] ?? 0) ?></h3>
                            </div>
                            <div class="file-icon video">
                                <i class="bi bi-camera-video"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-muted mb-0">Tamanho Total</h5>
                                <h3 class="mb-0"><?= formatBytes($stats['tamanho_total'] ?? 0) ?></h3>
                            </div>
                            <div class="file-icon documento">
                                <i class="bi bi-hdd"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Seção de Busca e Filtros -->
        <div class="search-section">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Buscar</label>
                    <input type="text" class="form-control" name="busca" value="<?= htmlspecialchars($busca) ?>" 
                           placeholder="Título, descrição ou tags...">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Categoria</label>
                    <select class="form-select" name="categoria">
                        <option value="">Todas</option>
                        <option value="Ofício" <?= $categoria === 'Ofício' ? 'selected' : '' ?>>Ofício</option>
                        <option value="Requerimento" <?= $categoria === 'Requerimento' ? 'selected' : '' ?>>Requerimento</option>
                        <option value="Projetos" <?= $categoria === 'Projetos' ? 'selected' : '' ?>>Projetos</option>
                        <option value="Instituto" <?= $categoria === 'Instituto' ? 'selected' : '' ?>>Instituto</option>
                        <option value="Prestação de Contas" <?= $categoria === 'Prestação de Contas' ? 'selected' : '' ?>>Prestação de Contas</option>
                        <option value="Diversos" <?= $categoria === 'Diversos' ? 'selected' : '' ?>>Diversos</option>
                        <option value="Foto Publicitária" <?= $categoria === 'Foto Publicitária' ? 'selected' : '' ?>>Foto Publicitária</option>
                        <option value="Vídeo Publicitário" <?= $categoria === 'Vídeo Publicitário' ? 'selected' : '' ?>>Vídeo Publicitário</option>
                        <option value="Material de Campanha" <?= $categoria === 'Material de Campanha' ? 'selected' : '' ?>>Material de Campanha</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Tipo de Mídia</label>
                    <select class="form-select" name="tipo_midia">
                        <option value="">Todos</option>
                        <option value="documento" <?= $tipo_midia === 'documento' ? 'selected' : '' ?>>Documento</option>
                        <option value="imagem" <?= $tipo_midia === 'imagem' ? 'selected' : '' ?>>Imagem</option>
                        <option value="video" <?= $tipo_midia === 'video' ? 'selected' : '' ?>>Vídeo</option>
                        <option value="audio" <?= $tipo_midia === 'audio' ? 'selected' : '' ?>>Áudio</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Data Início</label>
                    <input type="date" class="form-control" name="data_inicio" value="<?= htmlspecialchars($data_inicio) ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Data Fim</label>
                    <input type="date" class="form-control" name="data_fim" value="<?= htmlspecialchars($data_fim) ?>">
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search me-1"></i>Buscar
                    </button>
                    <a href="?" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-clockwise me-1"></i>Limpar
                    </a>
                    <a href="upload.php" class="btn btn-success">
                        <i class="bi bi-cloud-upload me-1"></i>Novo Upload
                    </a>
                </div>
            </form>
        </div>

        <!-- Lista de Documentos -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-list-ul me-2"></i>
                    Documentos (<?= number_format($total) ?> encontrados)
                </h5>
            </div>
            <div class="card-body p-0">
                <?php if (!empty($erro)): ?>
                    <div class="alert alert-danger m-3"><?= htmlspecialchars($erro) ?></div>
                <?php elseif (empty($documentos)): ?>
                    <div class="text-center py-5">
                        <i class="bi bi-folder2-open display-1 text-muted"></i>
                        <h4 class="text-muted mt-3">Nenhum documento encontrado</h4>
                        <p class="text-muted">Tente ajustar os filtros ou faça o upload de novos arquivos.</p>
                        <a href="upload.php" class="btn btn-primary">
                            <i class="bi bi-cloud-upload me-1"></i>Fazer Upload
                        </a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th width="60">Tipo</th>
                                    <th>Título</th>
                                    <th>Categoria</th>
                                    <th>Tamanho</th>
                                    <th>Data Upload</th>
                                    <th width="120">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($documentos as $doc): ?>
                                    <tr>
                                        <td>
                                            <div class="file-icon <?= $doc['tipo_midia'] ?? 'documento' ?>">
                                                <?php
                                                $icon = match($doc['tipo_midia'] ?? 'documento') {
                                                    'imagem' => 'bi-image',
                                                    'video' => 'bi-camera-video',
                                                    'audio' => 'bi-music-note',
                                                    default => 'bi-file-earmark-text'
                                                };
                                                ?>
                                                <i class="bi <?= $icon ?>"></i>
                                            </div>
                                        </td>
                                        <td>
                                            <div>
                                                <strong><?= htmlspecialchars($doc['titulo']) ?></strong>
                                                <?php if (!empty($doc['descricao'])): ?>
                                                    <br><small class="text-muted"><?= htmlspecialchars(substr($doc['descricao'], 0, 100)) ?>...</small>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary badge-categoria">
                                                <?= htmlspecialchars($doc['categoria']) ?>
                                            </span>
                                        </td>
                                        <td><?= formatBytes($doc['tamanho_arquivo']) ?></td>
                                        <td><?= date('d/m/Y H:i', strtotime($doc['data_upload'])) ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="detalhes.php?id=<?= $doc['id'] ?>" class="btn btn-outline-primary" title="Ver detalhes">
                                                    <i class="bi bi-eye"></i>
                                                </a>
                                                <a href="<?= BASE_URL ?>/<?= $doc['caminho_arquivo'] ?>" target="_blank" class="btn btn-outline-success" title="Download">
                                                    <i class="bi bi-download"></i>
                                                </a>
                                                <a href="upload.php?id=<?= $doc['id'] ?>" class="btn btn-outline-warning" title="Editar">
                                                    <i class="bi bi-pencil"></i>
                                                </a>
                                                <button type="button" class="btn btn-outline-danger" onclick="confirmarExclusao(<?= $doc['id'] ?>)" title="Excluir">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Paginação -->
        <?php if ($totalPaginas > 1): ?>
            <nav class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">Anterior</a>
                        </li>
                    <?php endif; ?>
                    
                    <?php for ($i = max(1, $page - 2); $i <= min($totalPaginas, $page + 2); $i++): ?>
                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $totalPaginas): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">Próxima</a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function confirmarExclusao(id) {
            if (confirm('Tem certeza que deseja excluir este documento? Esta ação não pode ser desfeita.')) {
                // Criar formulário para enviar requisição POST
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = 'excluir.php';
                
                // Adicionar campo hidden com o ID do documento
                const idField = document.createElement('input');
                idField.type = 'hidden';
                idField.name = 'id';
                idField.value = id;
                form.appendChild(idField);
                
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>

<?php
function formatBytes($size, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
        $size /= 1024;
    }
    return round($size, $precision) . ' ' . $units[$i];
}
?>