<?php
// bolsa_trabajo.php
// Bolsa de Trabajo Choferes usando la MISMA tabla de usuarios del Marketplace,
// pero con login propio de Bolsa (login_bolsa/logout_bolsa).

require __DIR__ . '/bolsa_auth.php';

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

if ($is_logged && !$U) {
    // Algo raro con la sesión -> forzamos logout de Bolsa
    header('Location: logout_bolsa.php');
    exit;
}

$errores = [];
$ok      = '';

// Prefill con datos del usuario (si está logueado)
$nombre   = '';
$apellido = '';
$email    = '';
$telefono = '';
$avatar   = '';

if ($is_logged && $U) {
    $nombre   = $U['nombre']   ?? '';
    $apellido = $U['apellido'] ?? '';
    $email    = $U['email']    ?? '';
    $telefono = $U['telefono'] ?? '';
    $avatar   = $U['avatar']   ?? '';
}

// Manejo del POST (solo si está logueado)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!$is_logged || !$U) {
        $errores[] = 'Tenés que iniciar sesión en la Bolsa de Trabajo para postularte.';
    } else {
        $nombre   = trim($_POST['nombre']   ?? '');
        $apellido = trim($_POST['apellido'] ?? '');
        $email    = trim($_POST['email']    ?? '');
        $telefono = trim($_POST['telefono'] ?? '');

        // Validaciones básicas
        if ($nombre === '' || $apellido === '' || $email === '') {
            $errores[] = 'Nombre, Apellido y Email son obligatorios.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errores[] = 'El email no es válido.';
        }

        // Validación de archivo CV
        if (empty($_FILES['cv_file']) || $_FILES['cv_file']['error'] === UPLOAD_ERR_NO_FILE) {
            $errores[] = 'Subí un archivo de CV (PDF, Word, etc.).';
        } elseif ($_FILES['cv_file']['error'] !== UPLOAD_ERR_OK) {
            $errores[] = 'Hubo un error al subir el archivo de CV.';
        } else {
            $cvSize = $_FILES['cv_file']['size'] ?? 0;
            if ($cvSize <= 0) {
                $errores[] = 'El archivo de CV está vacío.';
            }
            // SIN límite manual de tamaño acá: lo controla PHP (upload_max_filesize / post_max_size).
        }

        // Si todo está ok hasta ahora, procesamos el archivo
        $cv_relative_path = null;

        if (!$errores) {
            $allowed_ext   = ['pdf', 'doc', 'docx', 'odt', 'rtf'];
            $originalName  = $_FILES['cv_file']['name'] ?? '';
            $tmpPath       = $_FILES['cv_file']['tmp_name'] ?? '';
            $ext           = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

            if (!in_array($ext, $allowed_ext, true)) {
                $errores[] = 'Formato de archivo no permitido. Usá PDF, DOC, DOCX, ODT o RTF.';
            } elseif (!is_uploaded_file($tmpPath)) {
                $errores[] = 'Error de subida de archivo. Volvé a intentarlo.';
            } else {
                // Carpeta donde se guardan los CV
                $uploadDir = __DIR__ . '/uploads_cv';
                if (!is_dir($uploadDir)) {
                    @mkdir($uploadDir, 0775, true);
                }

                try {
                    $unique = bin2hex(random_bytes(4));
                } catch (Throwable $e) {
                    $unique = uniqid();
                }

                $filename = 'cv_' . (int)$U['id'] . '_' . date('YmdHis') . '_' . $unique . '.' . $ext;
                $destPath = $uploadDir . '/' . $filename;

                if (!move_uploaded_file($tmpPath, $destPath)) {
                    $errores[] = 'No se pudo guardar el archivo de CV en el servidor.';
                } else {
                    // Ruta relativa para guardar en BD
                    $cv_relative_path = 'uploads_cv/' . $filename;
                }
            }
        }

        // Insert en BD (tabla de postulaciones, NO otra tabla de login)
        if (!$errores && $cv_relative_path !== null) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO market_bolsa_trabajo
                      (user_id, nombre, apellido, email, telefono, cv_path, created_at)
                    VALUES
                      (:user_id, :nombre, :apellido, :email, :telefono, :cv_path, NOW())
                ");
                $stmt->execute([
                    ':user_id'  => (int)$U['id'],
                    ':nombre'   => $nombre,
                    ':apellido' => $apellido,
                    ':email'    => $email,
                    ':telefono' => $telefono,
                    ':cv_path'  => $cv_relative_path,
                ]);

                $ok = '¡Tu postulación como chofer fue enviada correctamente!';
            } catch (Throwable $e) {
                $errores[] = 'No se pudo guardar la postulación en la base de datos.';
            }
        }
    }
}

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

// Para la 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>Bolsa de Trabajo - Choferes</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-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: 2rem;
        }

        /* ===== BARRA SUPERIOR ===== */
        .mk-top-bar {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            border-radius: var(--mk-radius-sm);
            padding: 0.8rem 1.2rem;
            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;
        }

        /* ===== FORM CONTROLS ===== */
        .mk-form-group {
            margin-bottom: 1.5rem;
        }

        .mk-label {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--mk-dark);
            margin-bottom: 0.5rem;
            display: block;
        }

        .mk-label-required::after {
            content: ' *';
            color: var(--mk-danger);
        }

        .mk-form-control {
            border: 1.5px solid #e0e4f0;
            border-radius: var(--mk-radius-sm);
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: #fff;
            width: 100%;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        .mk-form-control:focus {
            outline: none;
            border-color: var(--mk-primary);
            box-shadow: 0 0 0 3px rgba(11, 50, 84, 0.1);
            background: #fff;
        }

        .mk-form-control::placeholder {
            color: #9ca3af;
            font-size: 0.9rem;
        }

        .mk-help {
            font-size: 0.8rem;
            color: var(--mk-secondary);
            margin-top: 0.4rem;
            line-height: 1.4;
        }

        /* ===== UPLOAD CV MEJORADO ===== */
        .mk-upload-zone {
            border: 2px dashed #d1d9e6;
            border-radius: var(--mk-radius-sm);
            padding: 2rem;
            background: var(--mk-light);
            transition: all 0.3s ease;
            text-align: center;
            cursor: pointer;
            position: relative;
        }

        .mk-upload-zone:hover {
            border-color: var(--mk-primary);
            background: rgba(11, 50, 84, 0.02);
            transform: translateY(-1px);
        }

        .mk-upload-zone.dragover {
            border-color: var(--mk-primary);
            background: rgba(11, 50, 84, 0.05);
            transform: scale(1.02);
        }

        .mk-upload-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
            opacity: 0.7;
        }

        .mk-upload-zone:hover .mk-upload-icon {
            opacity: 1;
            transform: scale(1.1);
        }

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

        .mk-upload-subtitle {
            font-size: 0.9rem;
            color: var(--mk-secondary);
            margin-bottom: 1rem;
        }

        .mk-file-input {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            opacity: 0;
            cursor: pointer;
        }

        .mk-file-preview {
            margin-top: 1rem;
            display: none;
        }

        .mk-file-item {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            padding: 0.8rem 1rem;
            background: #fff;
            border: 1px solid var(--mk-border);
            border-radius: var(--mk-radius-sm);
            margin-bottom: 0.5rem;
            font-size: 0.85rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .mk-file-icon {
            width: 20px;
            opacity: 0.7;
        }

        /* ===== BOTONES MEJORADOS ===== */
        .mk-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 0.8rem;
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--mk-border);
        }

        .mk-btn {
            border: none;
            border-radius: var(--mk-radius-sm);
            font-weight: 600;
            padding: 0.8rem 1.8rem;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            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 15px rgba(11, 50, 84, 0.3);
        }

        .mk-btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(11, 50, 84, 0.4);
            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-sm {
            padding: 0.5rem 1rem;
            font-size: 0.85rem;
        }

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

        /* ===== ALERTS MEJORADOS ===== */
        .mk-alert {
            border-radius: var(--mk-radius-sm);
            padding: 1rem 1.2rem;
            margin-bottom: 1.5rem;
            border: 1px solid transparent;
            font-size: 0.9rem;
        }

        .mk-alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            border-color: #f1aeb5;
            color: #721c24;
        }

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

        /* ===== HEADER CON AVATAR ===== */
        .mk-user-header {
            display: flex;
            align-items: center;
            gap: 1.2rem;
            margin-bottom: 2rem;
            padding: 1.5rem;
            background: linear-gradient(135deg, #f8f9fc, #ffffff);
            border-radius: var(--mk-radius-sm);
            border: 1px solid var(--mk-border);
        }

        .mk-user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            overflow: hidden;
            border: 3px solid var(--mk-primary);
            flex-shrink: 0;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

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

        .mk-user-avatar-initials {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--mk-primary), var(--mk-primary-light));
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.5rem;
            flex-shrink: 0;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .mk-user-info h1 {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--mk-dark);
            margin: 0 0 0.3rem 0;
        }

        .mk-user-info p {
            color: var(--mk-secondary);
            margin: 0;
            font-size: 0.95rem;
        }

        /* ===== ESTADO NO LOGUEADO ===== */
        .mk-welcome-card {
            text-align: center;
            padding: 3rem 2rem;
        }

        .mk-welcome-icon {
            font-size: 4rem;
            margin-bottom: 1.5rem;
            opacity: 0.7;
        }

        .mk-welcome-title {
            font-size: 1.4rem;
            font-weight: 700;
            color: var(--mk-dark);
            margin-bottom: 1rem;
        }

        .mk-welcome-text {
            color: var(--mk-secondary);
            font-size: 1rem;
            line-height: 1.6;
            margin-bottom: 2rem;
            max-width: 500px;
            margin-left: auto;
            margin-right: auto;
        }

        /* ===== 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: 767.98px) {
            .mk-card-body {
                padding: 1.5rem;
            }
            
            .mk-card-header {
                padding: 1.5rem 1.5rem;
            }
            
            .mk-user-header {
                flex-direction: column;
                text-align: center;
                gap: 1rem;
            }
            
            .mk-top-bar {
                flex-direction: column;
                gap: 0.8rem;
                text-align: center;
            }
            
            .mk-user-info {
                justify-content: center;
            }
            
            .mk-actions {
                flex-direction: column;
            }
            
            .mk-actions .mk-btn {
                width: 100%;
                justify-content: center;
            }
            
            .mk-upload-zone {
                padding: 1.5rem;
            }
        }

        @media (max-width: 575.98px) {
            .mk-card-body {
                padding: 1.2rem;
            }
            
            .mk-upload-zone {
                padding: 1rem;
            }
            
            .mk-welcome-card {
                padding: 2rem 1rem;
            }
        }
    </style>
</head>
<body>
<?php require __DIR__ . '/_navbar.php'; ?>

<!-- DATE BAR -->
<div class="datebar">
  <div class="container inner"><span id="fecha-hoy">—</span></div>
</div>
<style>
/* Fecha */
.datebar{background:var(--navy);color:#fff;font-weight:600}
.datebar .inner{height:40px;display:flex;align-items:center}
</style>

<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 class="mk-user-info">
                <?php if ($is_logged && $U): ?>
                    <div class="d-flex align-items-center gap-2">
                        <?php if (!empty($avatar)): ?>
                            <div class="mk-avatar">
                                <img src="<?= m_s($avatar) ?>" alt="Avatar">
                            </div>
                        <?php else: ?>
                            <div class="mk-avatar-initials">
                                <?= m_s(mb_substr($nombre,0,1) . mb_substr($apellido,0,1)) ?>
                            </div>
                        <?php endif; ?>
                        <span>Conectado como <strong><?= m_s($nombre . ' ' . $apellido) ?></strong></span>
                    </div>
                <?php else: ?>
                    <span class="text-muted">Bolsa de Trabajo - Choferes</span>
                <?php endif; ?>
            </div>
            
            <div class="d-flex gap-2 flex-wrap">
                <?php if ($is_logged && $U): ?>
                    <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>

        <div class="row justify-content-center">
            <div class="col-lg-9">
                <!-- Cabecera con avatar + texto (solo si está logueado) -->
                <?php if ($is_logged && $U): ?>
                    <div class="mk-user-header">
                        <?php if (!empty($avatar)): ?>
                            <div class="mk-user-avatar">
                                <img src="<?= m_s($avatar) ?>" alt="Avatar">
                            </div>
                        <?php else: ?>
                            <div class="mk-user-avatar-initials">
                                <?= m_s(mb_substr($nombre,0,1) . mb_substr($apellido,0,1)) ?>
                            </div>
                        <?php endif; ?>

                        <div class="mk-user-info">
                            <h1>Bolsa de Trabajo - Choferes</h1>
                            <p>Postulación de: <strong><?= m_s($nombre . ' ' . $apellido) ?></strong></p>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="mk-main-card">
                        <div class="mk-card-body mk-welcome-card">
                            <div class="mk-welcome-icon">🚛</div>
                            <h2 class="mk-welcome-title">Bolsa de Trabajo - Choferes</h2>
                            <p class="mk-welcome-text">
                                Para postularte necesitás tener una cuenta del Marketplace Fe.Tr.A.
                                Podés iniciar sesión o crear tu cuenta desde los botones de arriba.
                            </p>
                            <div class="d-flex justify-content-center gap-2 flex-wrap">
                                <a href="login_bolsa.php" class="mk-btn mk-btn-outline">
                                    <span class="mk-btn-icon">🔑</span>
                                    Iniciar sesión en Bolsa
                                </a>
                                <a href="register_market.php" class="mk-btn mk-btn-primary">
                                    <span class="mk-btn-icon">👤</span>
                                    Crear cuenta en el Marketplace
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($errores): ?>
                    <div class="mk-alert mk-alert-danger">
                        <ul class="mb-0">
                            <?php foreach ($errores as $err): ?>
                                <li><?= m_s($err) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if ($ok): ?>
                    <div class="mk-alert mk-alert-success">
                        <?= m_s($ok) ?>
                    </div>
                <?php endif; ?>

                <?php if ($is_logged && $U): ?>
                    <div class="mk-main-card">
                        <div class="mk-card-body">
                            <form method="post" enctype="multipart/form-data" novalidate id="mkForm">
                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <div class="mk-form-group">
                                            <label class="mk-label mk-label-required">Nombre</label>
                                            <input type="text" name="nombre" class="mk-form-control"
                                                   value="<?= m_s($nombre) ?>" 
                                                   placeholder="Tu nombre"
                                                   required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mk-form-group">
                                            <label class="mk-label mk-label-required">Apellido</label>
                                            <input type="text" name="apellido" class="mk-form-control"
                                                   value="<?= m_s($apellido) ?>" 
                                                   placeholder="Tu apellido"
                                                   required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mk-form-group">
                                            <label class="mk-label mk-label-required">Email</label>
                                            <input type="email" name="email" class="mk-form-control"
                                                   value="<?= m_s($email) ?>" 
                                                   placeholder="tu.email@ejemplo.com"
                                                   required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mk-form-group">
                                            <label class="mk-label">Teléfono</label>
                                            <input type="text" name="telefono" class="mk-form-control"
                                                   value="<?= m_s($telefono) ?>"
                                                   placeholder="+54 9 11 1234-5678">
                                            <div class="mk-help">Opcional, pero recomendado para contactarte</div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="mk-form-group">
                                            <label class="mk-label mk-label-required">Curriculum Vitae</label>
                                            <div class="mk-upload-zone" id="uploadZone">
                                                <div class="mk-upload-icon">📄</div>
                                                <div class="mk-upload-title">Subí tu CV</div>
                                                <div class="mk-upload-subtitle">Arrastrá tu archivo aquí o hacé click para seleccionar</div>
                                                <input type="file" name="cv_file" class="mk-file-input"
                                                       accept=".pdf,.doc,.docx,.odt,.rtf" required id="fileInput">
                                                <div class="text-muted" style="font-size: 0.8rem;">
                                                    Formatos permitidos: PDF, DOC, DOCX, ODT, RTF
                                                </div>
                                            </div>
                                            <div class="mk-file-preview" id="filePreview"></div>
                                            <div class="mk-help">
                                                El tamaño máximo del archivo lo define la configuración del servidor (PHP).
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="mk-actions">
                                            <a href="login_bolsa.php" class="mk-btn mk-btn-outline">
                                                <span class="mk-btn-icon">←</span>
                                                Volver al login de Bolsa
                                            </a>
                                            <button type="submit" class="mk-btn mk-btn-primary">
                                                <span class="mk-btn-icon">🚀</span>
                                                Postularme como chofer
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <p class="text-muted small mt-3 text-center">
                        Tus datos serán utilizados únicamente para la gestión de la Bolsa de Trabajo de choferes.
                    </p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('fileInput');
    const filePreview = document.getElementById('filePreview');
    const form = document.getElementById('mkForm');

    // Solo ejecutar si estamos en el formulario de postulación
    if (uploadZone && fileInput) {
        // Manejar drag & drop
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadZone.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadZone.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadZone.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            uploadZone.classList.add('dragover');
        }

        function unhighlight() {
            uploadZone.classList.remove('dragover');
        }

        uploadZone.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFile(files[0]); // Solo tomamos el primer archivo
        }

        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                handleFile(this.files[0]);
            }
        });

        function handleFile(file) {
            if (file && file.type) {
                const validTypes = [
                    'application/pdf',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/vnd.oasis.opendocument.text',
                    'application/rtf',
                    'text/rtf'
                ];
                
                if (validTypes.some(type => file.type.includes(type.replace('application/', '').replace('text/', '')))) {
                    showFilePreview(file);
                    fileInput.files = createFileList(file);
                } else {
                    alert('Formato de archivo no permitido. Usá PDF, DOC, DOCX, ODT o RTF.');
                }
            }
        }

        function showFilePreview(file) {
            const fileSize = (file.size / 1024 / 1024).toFixed(2);
            const fileExtension = file.name.split('.').pop().toUpperCase();
            
            filePreview.innerHTML = `
                <div class="mk-file-item">
                    <span class="mk-file-icon">📄</span>
                    <span style="flex: 1">
                        <strong>${file.name}</strong>
                        <div class="text-muted small">${fileExtension} • ${fileSize} MB</div>
                    </span>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearFile()">
                        ×
                    </button>
                </div>
            `;
            filePreview.style.display = 'block';
        }

        function createFileList(file) {
            const dt = new DataTransfer();
            dt.items.add(file);
            return dt.files;
        }

        window.clearFile = function() {
            fileInput.value = '';
            filePreview.style.display = 'none';
            filePreview.innerHTML = '';
        };
    }

    // Validación del formulario
    if (form) {
        form.addEventListener('submit', function(e) {
            const requiredFields = form.querySelectorAll('[required]');
            let valid = true;

            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    valid = false;
                    field.style.borderColor = '#dc3545';
                } else {
                    field.style.borderColor = '';
                }
            });

            if (!valid) {
                e.preventDefault();
                alert('Completá todos los campos obligatorios marcados con *.');
            }
        });
    }
});
</script>
</body>
</html>