<?php
require_once 'auth.php';
require_once __DIR__ . '/app/app_header.php';

$auth = getAuth();
$auth->requireAuth();

$currentUser = $auth->getCurrentUser();
$db = getDatabaseConnection();

// Filters 
$search = isset($_GET['q']) ? trim((string)$_GET['q']) : '';
$estado = isset($_GET['estado']) ? trim((string)$_GET['estado']) : '';
$desde = isset($_GET['desde']) ? trim((string)$_GET['desde']) : '';
$hasta = isset($_GET['hasta']) ? trim((string)$_GET['hasta']) : '';

// Build dynamic WHERE for the logged user + filters
$where = ['id_de_usuario = ?'];
$types = 'i';
$params = [$currentUser['id']];

if ($search !== '') {
    $where[] = "(nombre_del_firmante LIKE ? OR nombre_original_de_archivo LIKE ? OR nombre_de_archivo LIKE ? OR id_de_documento LIKE ?)";
    $types .= 'ssss';
    $like = '%' . $search . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if (in_array($estado, ['valido', 'revocado'], true)) {
    $where[] = "estado_de_documento = ?";
    $types .= 's';
    $params[] = $estado;
}

if ($desde !== '' && preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $desde)) {
    $where[] = "firmado_el >= ?";
    $types .= 's';
    $params[] = $desde . ' 00:00:00';
}

if ($hasta !== '' && preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $hasta)) {
    $where[] = "firmado_el <= ?";
    $types .= 's';
    $params[] = $hasta . ' 23:59:59';
}

$sql = "
    SELECT  
        id_de_documento, 
        nombre_del_firmante, 
        firmado_el, 
        nombre_de_archivo, 
        nombre_original_de_archivo, 
        estado_de_documento, tamano_de_archivo
    FROM 
        firmas
    WHERE " . implode(' AND ', $where) . "
    ORDER BY firmado_el DESC	
";

$stmt = $db->prepare($sql);

// bind_param needs references
$bindParams = [];
$bindParams[] = &$types;
foreach ($params as $key => $param) {
    $bindParams[] = &$params[$key];
}
call_user_func_array([$stmt, 'bind_param'], $bindParams);
$stmt->execute();
$documents = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get statistics 
$statsStmt = $db->prepare("
    SELECT 
        COUNT(*) as total_de_documents,
        SUM(CASE WHEN estado_de_documento = 'valido' THEN 1 ELSE 0 END) as documentos_validos,
        SUM(CASE WHEN estado_de_documento = 'revocado' THEN 1 ELSE 0 END) as documentos_revocados
    FROM firmas
    WHERE id_de_usuario = ?	
");
$statsStmt->bind_param('i', $currentUser['id']);
$statsStmt->execute();
$stats = $statsStmt->get_result()->fetch_assoc();
$statsStmt->close();

$db->close();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <title>Mi Panel - Documentos Firmados</title>
    <style>
        <?php echo renderAppHeaderStyles(); ?>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #29648D 0%, #29648D 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .navbar {
            background: linear-gradient(135deg,  #29648D 0%, #29648D 100%);
            color: white;
            padding: 20px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
 
        .navbar h1 {
            font-size: 1.5rem;
        }

        .navbar-actions {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .navbar .btn {
            border-radius: 20px;
            font-weight: 500;
            font-size: 0.9rem;
            padding: 10px 20px;
            box-shadow: none;
        }

        .navbar .btn-primary {
            background: #fff;
            color: #29648D;
        }

        .navbar .btn-outline {
            background: transparent;
            color: #fff;
            border: 2px solid #fff;
        }

        .user-info {
            background: rgba(255,255,255,0.2);
            padding: 8px 14px;
            border-radius: 20px;
            font-size: 0.9rem;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .btn {
            padding: 10px 20px;
            border-radius: 20px;
            border: none;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: white;
            color: #29648D;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255,255,255,0.3);
        }

        .btn-outline {
            background: transparent;
            border: 2px solid white;
            color: white;
        }

        .btn-outline:hover {
            background: white;
            color: #29648D;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto 40px;
            padding: 20px;
            background: #fff;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.25);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
            color: #29648D;
            margin-bottom: 10px;
        }

        .stat-label {
            color: #5f5f5fff;
            font-size: 0.9rem;
        }

        .documents-section {
            background: white;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .section-header {
            padding: 25px;
            background: linear-gradient(135deg, #29648D 0%, #29648D 100%);
            color: white;
        }

        .section-header h2 {
            font-size: 1.5rem;
        }

        .filters-bar {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 12px;
            padding: 18px 25px 10px 25px;
            background: #f8f9ff;
            border-bottom: 1px solid #e5e7eb;
        }

        .filter-field {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .filter-field label {
            font-size: 0.85rem;
            color: #444;
            font-weight: 600;
        }

        .filter-field input,
        .filter-field select {
            padding: 10px 12px;
            border: 1px solid #d9dce3;
            border-radius: 10px;
            background: white;
            font-size: 0.95rem;
            transition: border-color 0.2s, box-shadow 0.2s;
        }

        .filter-field input:focus,
        .filter-field select:focus {
            outline: none;
            border-color: #29648D;
            box-shadow: 0 0 0 3px rgba(41, 100, 141, 0.1);
        }

        .filters-actions {
            display: flex;
            gap: 10px;
            align-items: flex-end;
            justify-content: flex-end;
        }

        .filter-reset {
            background: #eef2f7;
            color: #314157;
        }

        .filter-reset:hover {
            background: #e2e8f0;
        }

        .documents-table {
            width: 100%;
            border-collapse: collapse;
        }

        .documents-table th,
        .documents-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .documents-table th {
            background: #f8f9ff;
            font-weight: 600;
            color: #333;
        }

        .documents-table tbody tr:hover {
            background: #f8f9ff;
        }

        .status-badge {
            padding: 5px 12px;
            border-radius: 15px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .status-valid {
            background: #d4edda;
            color: #155724;
        }

        .status-revoked {
            background: #f8d7da;
            color: #721c24;
        }

        .action-btn {
            padding: 6px 12px;
            border-radius: 5px;
            border: none;
            cursor: pointer;
            font-size: 0.85rem;
            margin-right: 5px;
            transition: all 0.3s;
        }

        .btn-download {
            background: #29648D;
            color: white;
        }

        .btn-download:hover {
            background: #207fa1ff;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state-icon {
            font-size: 4rem;
            margin-bottom: 20px;
        }

        .user-info {
            background: rgba(255,255,255,0.2);
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <?php renderAppHeader($currentUser, 'panel'); ?>

    <div class="container">
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total_de_documents']; ?></div>
                <div class="stat-label">Total de Documentos</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['documentos_validos']; ?></div>
                <div class="stat-label">Documentos Válidos</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['documentos_revocados']; ?></div>
                <div class="stat-label">Documentos Revocados</div>
            </div>
        </div>

        <div class="documents-section">
            <div class="section-header">
                <h2>📄 Mis Documentos Firmados</h2>
            </div>

            <form class="filters-bar" method="get">
                <div class="filter-field">
                    <label for="q">Buscar</label>
                    <input
                        type="text"
                        id="q"
                        name="q"
                        value="<?php echo htmlspecialchars($search); ?>"
                        placeholder="Nombre, ID o firmante">
                </div>
                <div class="filter-field">
                    <label for="estado">Estado</label>
                    <select id="estado" name="estado">
                        <option value="">Todos</option>
                        <option value="valido" <?php echo $estado === 'valido' ? 'selected' : ''; ?>>Válido</option>
                        <option value="revocado" <?php echo $estado === 'revocado' ? 'selected' : ''; ?>>Revocado</option>
                    </select>
                </div>
                <div class="filter-field">
                    <label for="desde">Desde</label>
                    <input type="date" id="desde" name="desde" value="<?php echo htmlspecialchars($desde); ?>">
                </div>
                <div class="filter-field">
                    <label for="hasta">Hasta</label>
                    <input type="date" id="hasta" name="hasta" value="<?php echo htmlspecialchars($hasta); ?>">
                </div>
                <div class="filters-actions">
                    <button class="btn btn-primary" type="submit">Aplicar filtros</button>
                    <a class="btn btn-outline filter-reset" href="dashboard">Limpiar</a>
                </div>
            </form>

            <?php if (count($documents) > 0): ?>
                <table class="documents-table">
                    <thead>
                        <tr>
                            <th>Documento</th>
                            <th>Firmante</th>
                            <th>Fecha</th>
                            <th>Tamaño</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($documents as $doc): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($doc['nombre_original_de_archivo'] ?: $doc['nombre_de_archivo']); ?></strong><br>
                                    <small style="color: #999;">ID: <?php echo htmlspecialchars($doc['id_de_documento']); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($doc['nombre_del_firmante']); ?></td>
                                <td><?php echo date('d/m/Y H:i', strtotime($doc['firmado_el'])); ?></td>
                                <td><?php echo number_format($doc['tamano_de_archivo'] / 1024, 2); ?> KB</td>
                                <td>
                                    <span class="status-badge status-<?php echo $doc['estado_de_documento']; ?>">
                                        <?php echo $doc['estado_de_documento'] === 'valido' ? '✓ Válido' : '✗ Revocado'; ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="action-btn btn-download" onclick="downloadDocument('<?php echo $doc['id_de_documento']; ?>')">
                                        📥 Descargar
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">
                    <div class="empty-state-icon">📭</div>
                    <h3>No hay documentos firmados</h3>
                    <p>Comienza firmando tu primer documento</p>
                    <a href="./" class="btn btn-primary" style="margin-top: 20px;">📝 Firmar Documento</a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function downloadDocument(documentId) {
            window.location.href = 'download?doc=' + documentId;
        }
    </script>
</body>
</html>


