<?php
// ver_postulaciones.php
// Listado de postulaciones de la Bolsa de Trabajo (Choferes)
// Usa el login propio de Bolsa (bolsa_auth.php) pero la MISMA tabla de usuarios del Marketplace.

require __DIR__ . '/bolsa_auth.php';

$pdo       = bolsa_pdo();
$is_logged = bolsa_is_logged();
$U         = $is_logged ? bolsa_current_user() : null;

if ($is_logged && !$U) {
    header('Location: logout_bolsa.php');
    exit;
}

// Si más adelante querés restringir solo a admins, acá podés chequear un campo de rol.
// if (!$U || empty($U['es_admin'])) {
//     http_response_code(403);
//     echo "No tenés permiso para ver esta sección.";
//     exit;
// }

$postulaciones = [];
try {
    $stmt = $pdo->query("
        SELECT id, user_id, nombre, apellido, email, telefono, cv_path, created_at
        FROM market_bolsa_trabajo
        ORDER BY created_at DESC
    ");
    $postulaciones = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $postulaciones = [];
}

function m_s($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

// Franja de fecha
setlocale(LC_TIME, 'es_AR.UTF-8', 'es_AR', 'es_ES.UTF-8', 'es_ES');
$fecha_hoy = strftime('%A %d de %B de %Y');
$fecha_hoy = ucfirst($fecha_hoy);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <title>Postulaciones - Bolsa de Trabajo</title>
    <?php require __DIR__ . '/_head_assets.php'; ?>
    <style>
        :root {
            --mk-primary: #0b3254;
            --mk-primary-light: #1a4a7a;
            --mk-secondary: #6c757d;
            --mk-success: #198754;
            --mk-danger: #dc3545;
            --mk-warning: #ffc107;
            --mk-dark: #212529;
            --mk-light: #f8f9fc;
            --mk-border: #e0e4f0;
            --mk-shadow: 0 12px 30px rgba(0,0,0,0.08);
            --mk-shadow-hover: 0 18px 40px rgba(0,0,0,0.12);
            --mk-radius: 16px;
            --mk-radius-sm: 12px;
        }

        body {
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            background: linear-gradient(135deg, #f4f6fb 0%, #f0f4ff 100%);
            min-height: 100vh;
        }

        /* ===== COMPONENTES PRINCIPALES ===== */
        .mk-main-card {
            background: #fff;
            border-radius: var(--mk-radius);
            box-shadow: var(--mk-shadow);
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.2);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .mk-main-card:hover {
            transform: translateY(-3px);
            box-shadow: var(--mk-shadow-hover);
        }

        .mk-card-header {
            background: linear-gradient(135deg, var(--mk-primary), var(--mk-primary-light));
            color: #fff;
            padding: 1.8rem 2rem;
            position: relative;
            overflow: hidden;
        }

        .mk-card-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255,255,255,0.1), transparent);
            transform: rotate(45deg);
            animation: shine 3s infinite;
        }

        @keyframes shine {
            0% { transform: translateX(-100%) rotate(45deg); }
            100% { transform: translateX(100%) rotate(45deg); }
        }

        .mk-card-body {
            padding: 0;
        }

        /* ===== BARRA SUPERIOR ===== */
        .mk-top-bar {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            border-radius: var(--mk-radius-sm);
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.06);
            border: 1px solid var(--mk-border);
        }

        .mk-user-info {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            font-size: 0.9rem;
            color: var(--mk-dark);
        }

        .mk-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
            border: 2px solid var(--mk-primary);
            flex-shrink: 0;
        }

        .mk-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .mk-avatar-initials {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--mk-primary);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 0.9rem;
            flex-shrink: 0;
        }

        /* ===== BOTONES MEJORADOS ===== */
        .mk-btn {
            border: none;
            border-radius: var(--mk-radius-sm);
            font-weight: 600;
            padding: 0.6rem 1.2rem;
            font-size: 0.85rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.4rem;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .mk-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .mk-btn:hover::before {
            left: 100%;
        }

        .mk-btn-primary {
            background: linear-gradient(135deg, var(--mk-primary), var(--mk-primary-light));
            color: #fff;
            box-shadow: 0 4px 12px rgba(11, 50, 84, 0.25);
        }

        .mk-btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 18px rgba(11, 50, 84, 0.35);
            color: #fff;
        }

        .mk-btn-outline {
            background: transparent;
            border: 1.5px solid var(--mk-secondary);
            color: var(--mk-secondary);
        }

        .mk-btn-outline:hover {
            background: var(--mk-secondary);
            color: #fff;
            transform: translateY(-2px);
        }

        .mk-btn-danger {
            background: transparent;
            border: 1.5px solid var(--mk-danger);
            color: var(--mk-danger);
        }

        .mk-btn-danger:hover {
            background: var(--mk-danger);
            color: #fff;
            transform: translateY(-2px);
        }

        .mk-btn-success {
            background: linear-gradient(135deg, var(--mk-success), #20c997);
            color: #fff;
            box-shadow: 0 4px 12px rgba(25, 135, 84, 0.25);
        }

        .mk-btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 18px rgba(25, 135, 84, 0.35);
            color: #fff;
        }

        .mk-btn-sm {
            padding: 0.4rem 0.8rem;
            font-size: 0.8rem;
        }

        .mk-btn-icon {
            width: 14px;
            height: 14px;
        }

        /* ===== TABLA MEJORADA ===== */
        .mk-table-container {
            overflow: hidden;
        }

        .mk-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }

        .mk-table thead {
            background: linear-gradient(135deg, #f8f9fc, #f0f4ff);
            border-bottom: 2px solid var(--mk-border);
        }

        .mk-table th {
            padding: 1rem 1.2rem;
            font-weight: 600;
            font-size: 0.85rem;
            color: var(--mk-dark);
            text-transform: uppercase;
            letter-spacing: 0.3px;
            text-align: left;
            border: none;
        }

        .mk-table tbody tr {
            transition: all 0.3s ease;
            border-bottom: 1px solid var(--mk-border);
        }

        .mk-table tbody tr:last-child {
            border-bottom: none;
        }

        .mk-table tbody tr:hover {
            background: rgba(11, 50, 84, 0.03);
            transform: translateX(4px);
        }

        .mk-table td {
            padding: 1rem 1.2rem;
            font-size: 0.9rem;
            color: var(--mk-dark);
            border: none;
            vertical-align: middle;
        }

        .mk-table .mk-candidate-name {
            font-weight: 600;
            color: var(--mk-primary);
        }

        .mk-table .mk-candidate-email {
            color: var(--mk-secondary);
            font-size: 0.85rem;
        }

        .mk-table .mk-candidate-phone {
            font-family: monospace;
            font-size: 0.85rem;
        }

        .mk-table .mk-date {
            font-size: 0.8rem;
            color: var(--mk-secondary);
            white-space: nowrap;
        }

        /* ===== ESTADO VACÍO ===== */
        .mk-empty-state {
            padding: 3rem 2rem;
            text-align: center;
            color: var(--mk-secondary);
        }

        .mk-empty-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }

        .mk-empty-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--mk-dark);
        }

        .mk-empty-text {
            font-size: 0.9rem;
            max-width: 400px;
            margin: 0 auto;
            line-height: 1.5;
        }

        /* ===== BADGES ===== */
        .mk-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
            padding: 0.3rem 0.6rem;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .mk-badge-success {
            background: linear-gradient(135deg, #d1edff, #b6e0ff);
            color: #004085;
            border: 1px solid #66b3ff;
        }

        .mk-badge-secondary {
            background: linear-gradient(135deg, #e9ecef, #dee2e6);
            color: #495057;
            border: 1px solid #ced4da;
        }

        /* ===== ESTADÍSTICAS ===== */
        .mk-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .mk-stat-card {
            background: #fff;
            border-radius: var(--mk-radius-sm);
            padding: 1.2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid var(--mk-border);
            text-align: center;
        }

        .mk-stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--mk-primary);
            line-height: 1;
            margin-bottom: 0.3rem;
        }

        .mk-stat-label {
            font-size: 0.85rem;
            color: var(--mk-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 600;
        }

        /* ===== ANIMACIONES ===== */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .mk-main-card {
            animation: fadeInUp 0.6s ease-out;
        }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 991.98px) {
            .mk-table-container {
                overflow-x: auto;
            }
            
            .mk-table {
                min-width: 800px;
            }
        }

        @media (max-width: 767.98px) {
            .mk-top-bar {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            
            .mk-user-info {
                justify-content: center;
            }
            
            .mk-stats {
                grid-template-columns: 1fr;
            }
            
            .mk-table th,
            .mk-table td {
                padding: 0.8rem 1rem;
            }
        }

        @media (max-width: 575.98px) {
            .mk-card-header {
                padding: 1.5rem 1.5rem;
            }
            
            .mk-table th,
            .mk-table td {
                padding: 0.7rem 0.8rem;
                font-size: 0.85rem;
            }
            
            .mk-empty-state {
                padding: 2rem 1rem;
            }
        }
    </style>
</head>
<body>
<?php require __DIR__ . '/_navbar.php'; ?>

<!-- Franja azul con la fecha -->
<div style="background-color:#0b3254; color:#fff; padding:0.4rem 0; font-size:0.9rem;">
    <div class="container d-flex justify-content-between align-items-center flex-wrap">
        <span><?= m_s($fecha_hoy) ?></span>
        <span>Bolsa de Trabajo &mdash; Postulaciones</span>
    </div>
</div>

<main class="py-4 py-md-5">
    <div class="container">
        <!-- Barra superior de acciones -->
        <div class="mk-top-bar d-flex justify-content-between align-items-center flex-wrap">
            <div>
                <h1 class="h4 fw-bold mb-1">Postulaciones - Choferes</h1>
                <p class="text-muted small mb-0">
                    Listado de todos los choferes que se postularon a través de la Bolsa de Trabajo.
                </p>
            </div>
            
            <div class="d-flex align-items-center gap-2 flex-wrap">
                <a href="bolsa_trabajo.php" class="mk-btn mk-btn-outline">
                    <span class="mk-btn-icon">←</span>
                    Volver a Bolsa
                </a>

                <?php if ($is_logged && $U): ?>
                    <div class="mk-user-info">
                        <?php if (!empty($U['avatar'])): ?>
                            <div class="mk-avatar">
                                <img src="<?= m_s($U['avatar']) ?>" alt="Avatar">
                            </div>
                        <?php else: ?>
                            <div class="mk-avatar-initials">
                                <?= m_s(mb_substr($U['nombre'] ?? '', 0, 1) . mb_substr($U['apellido'] ?? '', 0, 1)) ?>
                            </div>
                        <?php endif; ?>
                        <span>Conectado como <strong><?= m_s(($U['nombre'] ?? '') . ' ' . ($U['apellido'] ?? '')) ?></strong></span>
                    </div>
                    <a href="logout_bolsa.php" class="mk-btn mk-btn-danger mk-btn-sm">
                        <span class="mk-btn-icon">🚪</span>
                        Cerrar sesión
                    </a>
                <?php else: ?>
                    <a href="login_bolsa.php" class="mk-btn mk-btn-outline mk-btn-sm">
                        <span class="mk-btn-icon">🔑</span>
                        Iniciar sesión
                    </a>
                    <a href="register_market.php" class="mk-btn mk-btn-primary mk-btn-sm">
                        <span class="mk-btn-icon">👤</span>
                        Crear cuenta
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <!-- Estadísticas -->
        <?php if ($postulaciones): ?>
            <div class="mk-stats">
                <div class="mk-stat-card">
                    <div class="mk-stat-number"><?= count($postulaciones) ?></div>
                    <div class="mk-stat-label">Total Postulaciones</div>
                </div>
                <div class="mk-stat-card">
                    <div class="mk-stat-number"><?= count(array_filter($postulaciones, function($p) { return !empty($p['cv_path']); })) ?></div>
                    <div class="mk-stat-label">Con CV</div>
                </div>
                <div class="mk-stat-card">
                    <div class="mk-stat-number"><?= count(array_filter($postulaciones, function($p) { return !empty($p['telefono']); })) ?></div>
                    <div class="mk-stat-label">Con Teléfono</div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Listado de postulaciones -->
        <div class="mk-main-card">
            <div class="mk-card-header">
                <h2 class="h5 mb-0 text-white">📋 Listado de Postulantes</h2>
            </div>
            
            <div class="mk-card-body">
                <?php if (!$postulaciones): ?>
                    <div class="mk-empty-state">
                        <div class="mk-empty-icon">📭</div>
                        <div class="mk-empty-title">No hay postulaciones</div>
                        <div class="mk-empty-text">
                            Aún no se han registrado postulaciones en la Bolsa de Trabajo.
                            Los choferes aparecerán aquí cuando completen el formulario de postulación.
                        </div>
                    </div>
                <?php else: ?>
                    <div class="mk-table-container">
                        <table class="mk-table">
                            <thead>
                                <tr>
                                    <th>Postulante</th>
                                    <th>Contacto</th>
                                    <th>Fecha</th>
                                    <th style="text-align: center;">CV</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($postulaciones as $P): ?>
                                <?php
                                $fecha = $P['created_at'] ?? '';
                                if ($fecha) {
                                    try {
                                        $dt = new DateTime($fecha);
                                        $fecha = $dt->format('d/m/Y H:i');
                                    } catch (Throwable $e) {
                                        // dejar tal cual
                                    }
                                }
                                ?>
                                <tr>
                                    <td>
                                        <div class="mk-candidate-name">
                                            <?= m_s(($P['nombre'] ?? '') . ' ' . ($P['apellido'] ?? '')) ?>
                                        </div>
                                        <div class="mk-candidate-email">
                                            ID: <?= m_s($P['user_id'] ?? '') ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="mk-candidate-email">
                                            <?= m_s($P['email'] ?? '') ?>
                                        </div>
                                        <?php if (!empty($P['telefono'])): ?>
                                            <div class="mk-candidate-phone">
                                                📱 <?= m_s($P['telefono'] ?? '') ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted small">Sin teléfono</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="mk-date"><?= m_s($fecha) ?></div>
                                    </td>
                                    <td style="text-align: center;">
                                        <?php if (!empty($P['cv_path'])): ?>
                                            <a href="<?= m_s($P['cv_path']) ?>" target="_blank"
                                               class="mk-btn mk-btn-success mk-btn-sm">
                                                <span class="mk-btn-icon">📄</span>
                                                Ver CV
                                            </a>
                                        <?php else: ?>
                                            <span class="mk-badge mk-badge-secondary">Sin CV</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Información adicional -->
        <p class="text-muted small mt-3">
            <strong>💡 Tip:</strong> Si necesitás exportar este listado, podemos agregar un botón para descargar en Excel o CSV.
        </p>
    </div>
</main>

<?php require __DIR__ . '/_footer.php'; ?>
<?php require __DIR__ . '/_navbar_script.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Efectos de hover en las filas de la tabla
    const tableRows = document.querySelectorAll('.mk-table tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(4px)';
        });
        
        row.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
        });
    });

    // Tooltip para botones de CV
    const cvButtons = document.querySelectorAll('.mk-btn-success');
    cvButtons.forEach(btn => {
        btn.setAttribute('title', 'Abrir CV en nueva pestaña');
    });

    // Contador de postulaciones en tiempo real
    const postulacionesCount = <?= count($postulaciones) ?>;
    if (postulacionesCount > 0) {
        console.log(`📊 ${postulacionesCount} postulaciones cargadas correctamente`);
    }
});
</script>
</body>
</html>