<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

// Verificar si el cliente está logueado
if (!isset($_SESSION['client_id'])) {
    header('Location: ' . module_url('client_portal/login.php'));
    exit();
}

$client_id = $_SESSION['client_id'];

// Obtener conexión a la base de datos
$db = Database::getInstance();
$pdo = $db->getConnection();

$docs = [];
try {
    $chk = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'client_documents'");
    $chk->execute();
    $exists = (bool)$chk->fetchColumn();
    if ($exists) {
        $stmt = $pdo->prepare("SELECT type, original_name, filename, status, uploaded_at FROM client_documents WHERE client_id = ? ORDER BY uploaded_at DESC");
        $stmt->execute([$client_id]);
        $docs = $stmt->fetchAll();
    }
} catch (Throwable $e) {
    $docs = [];
}

$labels = [ 'id' => 'Identidad', 'address' => 'Domicilio', 'selfie' => 'Selfie', 'other' => 'Otro' ];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mis Documentos - PR Trader Room</title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/client_portal.css'); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
    <!-- Botón de menú móvil -->
    <button class="mobile-menu-toggle" aria-label="Abrir menú" aria-controls="sidebar" aria-expanded="false">
        <i class="fas fa-bars"></i>
    </button>
    <div class="client-portal-layout">
        <!-- Sidebar (shared style) -->
        <?php include __DIR__ . '/sidebar.php'; ?>

        <!-- Main Content -->
        <div class="client-main-wrapper">
            <!-- Header -->
            <header class="client-header">
                <div class="client-header-content">
                    <div class="client-header-left">
                        <nav class="client-breadcrumb">
                            <span class="client-breadcrumb-item">
                                <a href="<?php echo module_url('client_portal/dashboard.php'); ?>">Dashboard</a>
                            </span>
                            <span class="client-breadcrumb-separator">›</span>
                            <span class="client-breadcrumb-item current">Documentos</span>
                        </nav>
                    </div>
                    <div class="client-header-right">
                        <div class="client-header-actions">
                            <a href="<?php echo module_url('client_portal/dashboard.php'); ?>#documents" class="client-header-btn">
                                <i class="fas fa-upload"></i>
                                Subir Documento
                            </a>
                        </div>
                        <div class="client-user-dropdown">
                            <div class="client-user-btn">
                                <div class="client-user-avatar">
                                    <?= strtoupper(substr($_SESSION['client_first_name'] ?? 'C', 0, 1)) ?>
                                </div>
                                <div class="client-user-info">
                                    <span class="client-user-name"><?= htmlspecialchars($_SESSION['client_first_name'] ?? 'Cliente') ?></span>
                                    <span class="client-user-status">Activo</span>
                                </div>
                                <i class="fas fa-chevron-down"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Main Content -->
            <main class="client-main-content">
                <section class="documents-section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <i class="fas fa-file-lines"></i>
                            Historial de Documentos
                        </h2>
                        <div class="section-actions">
                            <a class="client-action-btn secondary" href="<?php echo module_url('client_portal/dashboard.php'); ?>#documents">
                                <i class="fas fa-upload"></i> 
                                Subir Nuevos
                            </a>
                            <button class="client-action-btn secondary">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="documents-table-container">
                        <table class="documents-table">
                            <thead>
                                <tr>
                                    <th><i class="fas fa-file"></i> Tipo</th>
                                    <th><i class="fas fa-signature"></i> Nombre</th>
                                    <th><i class="fas fa-calendar"></i> Fecha</th>
                                    <th><i class="fas fa-shield-alt"></i> Estado</th>
                                    <th><i class="fas fa-cog"></i> Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($docs): foreach ($docs as $d): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($labels[$d['type']] ?? ucfirst($d['type'])) ?></td>
                                        <td><?= htmlspecialchars($d['original_name']) ?></td>
                                        <td><?= htmlspecialchars(date('Y-m-d', strtotime($d['uploaded_at']))) ?></td>
                                        <td>
                                            <?php
                                                $status = $d['status'];
                                                $class = $status === 'approved' ? 'approved' : ($status === 'rejected' ? 'rejected' : 'pending');
                                            ?>
                                            <span class="doc-badge <?= $class ?>">
                                                <?php if ($status === 'approved'): ?><i class="fas fa-check"></i> Aprobado
                                                <?php elseif ($status === 'rejected'): ?><i class="fas fa-times"></i> Rechazado
                                                <?php else: ?><i class="fas fa-hourglass-half"></i> En revisión<?php endif; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <a class="action-btn-small view" href="<?= htmlspecialchars($d['filename']) ?>" target="_blank" title="Ver documento">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <button class="action-btn-small" title="Descargar">
                                                    <i class="fas fa-download"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="5" style="text-align: center; padding: 2rem; color: var(--text-muted);">
                                            <i class="fas fa-file-plus" style="font-size: 2rem; margin-bottom: 1rem; display: block;"></i>
                                            Aún no has subido documentos. 
                                            <a href="<?php echo module_url('client_portal/dashboard.php'); ?>#documents" style="color: var(--primary-color);">Sube tu primer documento</a>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            </main>
        </div>
        <!-- Overlay para móvil -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
    </div>

    <script src="<?php echo asset('public/script.js'); ?>"></script>
    <script src="https://kit.fontawesome.com/a2e0a6ad53.js" crossorigin="anonymous"></script>
</body>
</html>
