<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/SimpleCaptcha.php';
require_once __DIR__ . '/includes/MailQueue.php';
require_once __DIR__ . '/includes/moderation.php';

$pdo = getPDO();

// --- Contrôle d'accès : seul un compte Annonceur connecté peut publier ---
if (!isUserLoggedIn()) {
    redirect('register.php?as=announcer');
}
if (isClient()) {
    redirect('?notice=client_no_publish');
}
// Une Indépendante n'a droit qu'à une seule annonce : si elle en a déjà une, on l'envoie directement l'éditer
if (isIndependent()) {
    $stmtExisting = $pdo->prepare("SELECT id FROM listings WHERE user_id = ? LIMIT 1");
    $stmtExisting->execute([currentUserId()]);
    $existingListingId = $stmtExisting->fetchColumn();
    if ($existingListingId) {
        redirect('editar-anuncio.php?id=' . $existingListingId);
    }
}

// Load all services for step 2
$langField = 'name_' . CURRENT_LANG;
$allServices = $pdo->query("SELECT id, service_key, {$langField} AS name FROM services ORDER BY name ASC")->fetchAll();

$successMsg = null;
$errorMsg = null;

// --- Traitement du formulaire de soumission (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitations & validations de base
    $firstName = trim($_POST['first_name'] ?? '');
    $age = (int)($_POST['age'] ?? 0);
    $gender = in_array($_POST['gender'] ?? '', ['female', 'male'], true) ? $_POST['gender'] : null;
    $city = trim($_POST['city'] ?? '');
    $nationality = trim($_POST['nationality'] ?? '');
    $height = (int)($_POST['height'] ?? 0);
    $weight = (int)($_POST['weight'] ?? 0);
    $breast = !empty($_POST['breast']) ? (int)$_POST['breast'] : null;
    $waist = !empty($_POST['waist']) ? (int)$_POST['waist'] : null;
    $hips = !empty($_POST['hips']) ? (int)$_POST['hips'] : null;
    $hairColor = !empty($_POST['hair_color']) ? trim($_POST['hair_color']) : null;
    $hasTattoos = isset($_POST['has_tattoos']) && $_POST['has_tattoos'] === '1' ? 1 : 0;

    // Champs profil Influencer / redes sociales (optionnels)
    $allowedNiches = ['fashion', 'lifestyle', 'nightlife', 'luxury', 'fitness', 'travel'];
    $allowedCollab = ['reels_tiktok', 'story', 'post', 'event_presence', 'ugc'];
    $niches = implode(',', array_values(array_intersect((array)($_POST['niches'] ?? []), $allowedNiches))) ?: null;
    $collabTypes = implode(',', array_values(array_intersect((array)($_POST['collab_types'] ?? []), $allowedCollab))) ?: null;
    $audienceTotal = !empty($_POST['audience_total']) ? (int)$_POST['audience_total'] : null;

    // Champs spectacle (catégorie Striptease Artístico y Cabaret)
    $allowedEvents = ['despedidas', 'cumpleanos', 'fiestas_privadas', 'clubes_cabaret'];
    $allowedFormat = ['escenario', 'tematico'];
    $eventTypes = implode(',', array_values(array_intersect((array)($_POST['event_types'] ?? []), $allowedEvents))) ?: null;
    $showFormat = implode(',', array_values(array_intersect((array)($_POST['show_format'] ?? []), $allowedFormat))) ?: null;

    $termsAccepted = isset($_POST['accept_terms']);

    $description = trim($_POST['description'] ?? '');
    $primaryService = (int)($_POST['primary_service'] ?? 0);
    $servicesSelected = $_POST['services'] ?? [];
    // Le service principal est toujours inclus dans la liste des services enregistrés
    if ($primaryService > 0 && !in_array((string)$primaryService, $servicesSelected, true)) {
        $servicesSelected[] = (string)$primaryService;
    }
    $languagesSelected = $_POST['languages'] ?? [];
    
    $prices = [
        'incall' => [
            '30min' => !empty($_POST['price_incall_30min']) ? (float)$_POST['price_incall_30min'] : null,
            '1h' => !empty($_POST['price_incall_1h']) ? (float)$_POST['price_incall_1h'] : null,
            'night' => !empty($_POST['price_incall_night']) ? (float)$_POST['price_incall_night'] : null,
        ],
        'outcall' => [
            '30min' => !empty($_POST['price_outcall_30min']) ? (float)$_POST['price_outcall_30min'] : null,
            '1h' => !empty($_POST['price_outcall_1h']) ? (float)$_POST['price_outcall_1h'] : null,
            'night' => !empty($_POST['price_outcall_night']) ? (float)$_POST['price_outcall_night'] : null,
        ],
    ];
    $hasAtLeastOnePrice = false;
    foreach ($prices as $typePrices) {
        foreach ($typePrices as $p) {
            if ($p !== null && $p > 0) {
                $hasAtLeastOnePrice = true;
            }
        }
    }
    
    $phone = trim($_POST['phone'] ?? '');
    $whatsapp = isset($_POST['whatsapp']) ? 1 : 0;
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);

    // Validation stricte
    if (!SimpleCaptcha::verify($_POST['captcha'] ?? '')) {
        $errorMsg = __('err_captcha');
    } elseif (empty($firstName) || $age < 18 || empty($gender) || empty($city) || empty($email) || empty($description) || !$hasAtLeastOnePrice || $primaryService <= 0) {
        $errorMsg = __('msg_error_submit');
    } elseif (!$termsAccepted) {
        $errorMsg = __('err_terms_required');
    } elseif (($mod = moderateContent($description, $firstName)) && $mod['level'] === 'hard') {
        // Terme explicitement interdit -> rejet. (Un terme ambigu laisse l'annonce en 'pending' pour revue admin.)
        $errorMsg = __('err_content_prohibited');
    } else {
        // La photo principale est traitée AVANT toute écriture en base : une annonce sans photo
        // principale n'a pas de sens, donc un échec d'upload doit bloquer la soumission avec une
        // raison claire plutôt que de créer silencieusement une annonce sans photo.
        $stmtSeoSvc = $pdo->prepare("SELECT service_key FROM services WHERE id = ?");
        $stmtSeoSvc->execute([$primaryService]);
        $seoBase = getPhotoSeoBase($stmtSeoSvc->fetchColumn() ?: 'azafatas', $gender, $city, $firstName);

        $mainFilename = uploadImage($_FILES['main_photo'] ?? [], UPLOADS_PATH, 800, 85, 1200, $uploadErrorCode, $seoBase);
        if (!$mainFilename) {
            $errorMsg = describeUploadErrorI18n($uploadErrorCode, $_FILES['main_photo']['name'] ?? '');
        }
    }

    if (!$errorMsg && isset($mainFilename)) {
        try {
            $pdo->beginTransaction();

            // Dictionnaire des coordonnées des villes espagnoles pour la carte Leaflet
            $cityCoordinates = [
                'Madrid' => [40.416775, -3.703790],
                'Barcelona' => [41.385063, 2.173403],
                'Valencia' => [39.469907, -0.376288],
                'Sevilla' => [37.389092, -5.984459],
                'Zaragoza' => [41.648823, -0.889085],
                'Málaga' => [36.721261, -4.421266],
                'Murcia' => [37.992240, -1.130654],
                'Palma de Mallorca' => [39.569600, 2.650160],
                'Las Palmas' => [28.123546, -15.436257],
                'Bilbao' => [43.263013, -2.934989],
                'Alicante' => [38.345170, -0.481490],
                'Ibiza' => [38.906734, 1.420598],
                'Marbella' => [36.507309, -4.885836]
            ];

            // Coordonnées par défaut (Madrid) si ville inconnue
            $lat = 40.416775;
            $lng = -3.703790;
            if (isset($cityCoordinates[$city])) {
                $lat = $cityCoordinates[$city][0];
                $lng = $cityCoordinates[$city][1];
            }

            // Empreinte anti-fraude (comparée avec celle des avis pour détecter les auto-avis)
            $fingerprint = getClientFingerprint();

            // Insertion dans listings, rattachée au compte Annonceur connecté.
            // Le compte étant déjà vérifié par e-mail, on ne redemande pas de validation par annonce :
            // seule l'approbation de l'admin (status) conditionne désormais la mise en ligne.
            $sqlList = "INSERT INTO listings
                (user_id, status, first_name, age, gender, city, nationality, height, weight, breast_size, waist_size, hip_size, hair_color, has_tattoos, description, niches, collab_types, audience_total, event_types, show_format, phone, whatsapp, email, email_verified, lat, lng, ip_address, user_agent, fingerprint_hash, terms_accepted_at)
                VALUES (:user_id, 'pending', :first_name, :age, :gender, :city, :nationality, :height, :weight, :breast, :waist, :hips, :hair_color, :has_tattoos, :description, :niches, :collab_types, :audience_total, :event_types, :show_format, :phone, :whatsapp, :email, 1, :lat, :lng, :ip_address, :user_agent, :fingerprint_hash, NOW())";

            $stmtList = $pdo->prepare($sqlList);
            $stmtList->execute([
                'user_id' => currentUserId(),
                'first_name' => $firstName,
                'age' => $age,
                'gender' => $gender,
                'city' => $city,
                'nationality' => $nationality,
                'height' => $height,
                'weight' => $weight,
                'breast' => $breast,
                'waist' => $waist,
                'hips' => $hips,
                'hair_color' => $hairColor,
                'has_tattoos' => $hasTattoos,
                'description' => $description,
                'niches' => $niches,
                'collab_types' => $collabTypes,
                'audience_total' => $audienceTotal,
                'event_types' => $eventTypes,
                'show_format' => $showFormat,
                'phone' => $phone,
                'whatsapp' => $whatsapp,
                'email' => $email,
                'lat' => $lat,
                'lng' => $lng,
                'ip_address' => $fingerprint['ip'],
                'user_agent' => $fingerprint['user_agent'],
                'fingerprint_hash' => $fingerprint['hash']
            ]);

            $listingId = $pdo->lastInsertId();

            assignListingSlug($pdo, (int)$listingId, $firstName, $age, $gender, $city, $primaryService);

            // Gestion des Uploads Photos
            $uploadTarget = UPLOADS_PATH;

            // Photo Principale (Profil) : déjà uploadée et validée avant le début de la transaction (voir $mainFilename)
            $stmtPhoto = $pdo->prepare("INSERT INTO listing_photos (listing_id, photo_path, is_main) VALUES (?, ?, 1)");
            $stmtPhoto->execute([$listingId, $mainFilename]);

            // Photos de Galerie (Múltiple) : optionnelles, un échec ne bloque pas la soumission
            // mais est signalé à l'utilisateur pour qu'il puisse les rajouter depuis "Editar anuncio".
            $galleryUploadErrors = [];
            if (isset($_FILES['gallery'])) {
                $files = $_FILES['gallery'];
                $fileCount = count($files['name']);
                for ($i = 0; $i < $fileCount; $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) {
                        continue;
                    }
                    $singleFile = [
                        'name' => $files['name'][$i],
                        'type' => $files['type'][$i],
                        'tmp_name' => $files['tmp_name'][$i],
                        'error' => $files['error'][$i],
                        'size' => $files['size'][$i],
                    ];
                    $galleryFilename = uploadImage($singleFile, $uploadTarget, 1200, 80, 1600, $galleryUploadErrorCode, $seoBase);
                    if ($galleryFilename) {
                        $stmtPhoto = $pdo->prepare("INSERT INTO listing_photos (listing_id, photo_path, is_main) VALUES (?, ?, 0)");
                        $stmtPhoto->execute([$listingId, $galleryFilename]);
                    } else {
                        $galleryUploadErrors[] = describeUploadErrorI18n($galleryUploadErrorCode, $files['name'][$i] ?: '');
                    }
                }
            }

            // Insertion des services (le service principal est marqué via is_primary)
            if (!empty($servicesSelected)) {
                $stmtSrv = $pdo->prepare("INSERT INTO listing_services (listing_id, service_id, is_primary) VALUES (?, ?, ?)");
                foreach ($servicesSelected as $sId) {
                    $stmtSrv->execute([$listingId, (int)$sId, (int)$sId === $primaryService ? 1 : 0]);
                }
            }

            // Insertion des langues
            if (!empty($languagesSelected)) {
                $stmtLang = $pdo->prepare("INSERT INTO listing_languages (listing_id, language_code) VALUES (?, ?)");
                foreach ($languagesSelected as $lCode) {
                    if (in_array($lCode, SUPPORTED_LANGS)) {
                        $stmtLang->execute([$listingId, $lCode]);
                    }
                }
            }

            // Réseaux sociaux (profil influencer) : une ligne par réseau renseigné
            $socialNetworks = ['instagram', 'tiktok', 'youtube', 'twitter'];
            $stmtSocial = $pdo->prepare("INSERT INTO listing_social (listing_id, network, handle, followers) VALUES (?, ?, ?, ?)");
            foreach ($socialNetworks as $net) {
                $handle = trim($_POST['social_' . $net . '_handle'] ?? '');
                if ($handle === '') {
                    continue;
                }
                $followers = !empty($_POST['social_' . $net . '_followers']) ? (int)$_POST['social_' . $net . '_followers'] : null;
                $stmtSocial->execute([$listingId, $net, $handle, $followers]);
            }

            // Insertion des tarifs (pricing) : un tarif par type et par durée renseignée
            $stmtPrice = $pdo->prepare("INSERT INTO pricing (listing_id, duration, type, price, currency) VALUES (?, ?, ?, ?, 'EUR')");
            foreach ($prices as $priceType => $typePrices) {
                foreach ($typePrices as $duration => $price) {
                    if ($price !== null && $price > 0) {
                        $stmtPrice->execute([$listingId, $duration, $priceType, $price]);
                    }
                }
            }

            // Notifie tous les administrateurs qu'une annonce attend leur validation
            $adminEditLink = BASE_URL . '/admin007/listings.php?action=edit&id=' . $listingId;
            foreach (getAdminEmails() as $adminEmail) {
                queueAutoresponderEmail(
                    $pdo,
                    'admin_new_listing_pending',
                    'admin',
                    $adminEmail,
                    ['name' => $firstName, 'link' => $adminEditLink]
                );
            }

            $pdo->commit();
            $successMsg = __('msg_listing_pending_approval');
            if (!empty($galleryUploadErrors)) {
                $errorMsg = __('msg_photos_partial_error', ['details' => implode(' | ', $galleryUploadErrors)]);
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $errorMsg = __('msg_error_submit') . ' (' . $e->getMessage() . ')';
        }
    }
}

$pageTitle = __('form_title');
require_once ROOT_PATH . '/templates/partials/header.php';
?>

<!-- Multi-step Form Page Layout -->
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
    <div class="bg-luxury-card border border-luxury-rose/10 rounded-2xl p-8 border-rose-glow">
        
        <h1 class="font-playfair text-3xl font-bold tracking-wide text-luxury-rose mb-2 text-center">
            <?= __('form_title') ?>
        </h1>
        <p class="text-luxury-muted text-xs font-light text-center mb-8 uppercase tracking-widest">
<?= __('form_subtitle') ?>
        </p>

        <?php if ($successMsg): ?>
            <!-- Success screen -->
            <div class="p-6 bg-emerald-950/30 border border-emerald-500/20 text-center rounded-xl space-y-4">
                <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-emerald-900/30 text-emerald-400">
                    <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
                    </svg>
                </div>
                <h3 class="font-playfair text-xl font-bold text-luxury-platinum">¡Anuncio Enviado!</h3>
                <p class="text-sm font-light text-luxury-muted leading-relaxed">
                    <?= e($successMsg) ?>
                </p>
                <?php if ($errorMsg): ?>
                    <div class="p-3 bg-amber-950/20 border border-amber-500/20 text-amber-400 text-xs font-light rounded-lg text-left">
                        ⚠️ <?= e($errorMsg) ?>
                    </div>
                <?php endif; ?>
                <div class="pt-6">
                    <a href="<?= BASE_URL ?>/mis-anuncios.php" class="inline-flex items-center px-6 py-2.5 bg-gradient-to-r from-luxury-rose to-luxury-rosehover text-luxury-dark text-xs font-bold uppercase tracking-widest rounded-lg transition duration-300">
                        <?= (isClub() || isAgency()) ? __('nav_my_listings_plural') : __('nav_my_listing_singular') ?>
                    </a>
                </div>
            </div>
        <?php else: ?>
            
            <?php if ($errorMsg): ?>
                <div class="mb-6 p-4 bg-red-950/30 border border-red-500/20 text-red-400 text-sm font-light rounded-lg">
                    ⚠️ <?= e($errorMsg) ?>
                </div>
            <?php endif; ?>

            <!-- Steps indicators -->
            <div class="flex items-center justify-between mb-12 select-none relative">
                <!-- Progress Line background -->
                <div class="absolute left-0 top-1/2 -translate-y-1/2 w-full h-[1px] bg-luxury-rose/10 z-0"></div>
                <div id="progress-bar-fill" class="absolute left-0 top-1/2 -translate-y-1/2 h-[2px] bg-luxury-rose z-0 transition-all duration-300" style="width: 0%;"></div>

                <?php for ($i = 1; $i <= 5; $i++): ?>
                    <div class="step-indicator-node z-10 flex flex-col items-center">
                        <div id="indicator-circle-<?= $i ?>" class="h-10 w-10 rounded-full flex items-center justify-center border font-semibold text-sm transition duration-300 <?= $i === 1 ? 'bg-luxury-rose text-luxury-dark border-luxury-rose' : 'bg-luxury-card border-luxury-rose/20 text-luxury-muted' ?>">
                            <?= $i ?>
                        </div>
                        <span id="indicator-label-<?= $i ?>" class="text-[10px] uppercase font-bold tracking-wider mt-2 transition duration-300 <?= $i === 1 ? 'text-luxury-rose' : 'text-luxury-muted' ?>">
                            Paso <?= $i ?>
                        </span>
                    </div>
                <?php endfor; ?>
            </div>

            <!-- Multi-step form -->
            <form id="multi-step-form" action="" method="POST" enctype="multipart/form-data" class="space-y-8">
                
                <!-- STEP 1: Profile & Physical -->
                <div id="step-content-1" class="step-content block space-y-6">
                    <h2 class="font-playfair text-xl font-semibold text-luxury-rose border-b border-luxury-rose/5 pb-2">
                        <?= __('step_1') ?>
                    </h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- First Name -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_first_name') ?> *</label>
                            <input type="text" name="first_name" required placeholder="Sofia"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                        
                        <!-- Age -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_age') ?> *</label>
                            <input type="number" name="age" required min="18" max="99" placeholder="22"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>

                        <!-- Gender -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_gender') ?> *</label>
                            <select name="gender" required class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm cursor-pointer">
                                <option value=""></option>
                                <option value="female"><?= __('gender_female') ?></option>
                                <option value="male"><?= __('gender_male') ?></option>
                            </select>
                        </div>

                        <!-- City -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_city') ?> *</label>
                            <select name="city" required class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm cursor-pointer">
                                <option value="">Selecciona una ciudad</option>
                                <?php foreach (getPopularCities() as $popCity): ?>
                                    <option value="<?= e($popCity) ?>"><?= e($popCity) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Nationality -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_nationality') ?> *</label>
                            <select name="nationality" required class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm cursor-pointer">
                                <option value="">Selecciona nacionalidad</option>
                                <?php 
                                $nats = getNationalitiesList()[CURRENT_LANG] ?? getNationalitiesList()['es'];
                                foreach ($nats as $nat): 
                                ?>
                                    <option value="<?= e($nat) ?>"><?= e($nat) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Height -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_height') ?> *</label>
                            <input type="number" name="height" required min="100" max="250" placeholder="172"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                        
                        <!-- Weight -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_weight') ?> *</label>
                            <input type="number" name="weight" required min="30" max="150" placeholder="52"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                    </div>

                    <!-- Medidas (book) -->
                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted"><?= __('measures_book_title') ?></label>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_breast') ?></label>
                            <input type="number" name="breast" min="50" max="150" placeholder="90"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_waist') ?></label>
                            <input type="number" name="waist" min="40" max="120" placeholder="60"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_hips') ?></label>
                            <input type="number" name="hips" min="50" max="150" placeholder="90"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                    </div>

                    <!-- Hair Color & Tattoos -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_hair_color') ?></label>
                            <select name="hair_color" class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm cursor-pointer">
                                <option value="">N/A</option>
                                <?php foreach (getHairColors() as $hc): ?>
                                    <option value="<?= e($hc['key']) ?>"><?= e($hc[CURRENT_LANG] ?? $hc['es']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_tattoos') ?></label>
                            <select name="has_tattoos" class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm cursor-pointer">
                                <option value="0"><?= __('tattoos_no') ?></option>
                                <option value="1"><?= __('tattoos_yes') ?></option>
                            </select>
                        </div>
                    </div>

                    <!-- Images -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_main_photo') ?> *</label>
                            <input type="file" name="main_photo" required accept="image/*" id="main-photo-input"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2 outline-none focus:border-luxury-rose text-sm file:bg-luxury-rose file:text-luxury-dark file:border-none file:px-3 file:py-1 file:rounded file:text-xs file:font-semibold file:uppercase file:cursor-pointer hover:file:bg-luxury-rosehover">
                            <div id="main-photo-preview" class="hidden mt-3 w-28">
                                <img class="w-full aspect-[3/4] object-cover rounded-lg border border-luxury-rose/20">
                            </div>
                        </div>
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_gallery') ?></label>
                            <input type="file" name="gallery[]" multiple accept="image/*" id="gallery-photos-input"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2 outline-none focus:border-luxury-rose text-sm file:bg-luxury-rose file:text-luxury-dark file:border-none file:px-3 file:py-1 file:rounded file:text-xs file:font-semibold file:uppercase file:cursor-pointer hover:file:bg-luxury-rosehover">
                            <div id="gallery-photos-preview" class="mt-3 grid grid-cols-4 gap-2"></div>
                        </div>
                    </div>
                    <p class="text-[11px] text-luxury-muted font-light leading-relaxed"><?= __('field_photo_format_hint') ?></p>
                </div>

                <!-- STEP 2: Description, Services & Languages -->
                <div id="step-content-2" class="step-content hidden space-y-6">
                    <h2 class="font-playfair text-xl font-semibold text-luxury-rose border-b border-luxury-rose/5 pb-2">
                        <?= __('step_2') ?>
                    </h2>
                    
                    <!-- Description -->
                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_description') ?> *</label>
                        <textarea name="description" required rows="6" placeholder="<?= e(__('desc_placeholder')) ?>"
                                  class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-3 outline-none focus:border-luxury-rose text-sm resize-none"></textarea>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <!-- Services selection -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-3"><?= __('field_primary_service') ?> *</label>
                            <select name="primary_service" id="primary-service-select" required
                                    class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm cursor-pointer mb-5">
                                <option value=""><?= __('select_primary_service_placeholder') ?></option>
                                <?php foreach ($allServices as $serv): ?>
                                    <option value="<?= $serv['id'] ?>" data-key="<?= e($serv['service_key']) ?>"><?= e($serv['name']) ?></option>
                                <?php endforeach; ?>
                            </select>

                            <!-- Bloc spécifique Striptease Artístico y Cabaret (affiché selon la catégorie) -->
                            <div id="striptease-block" class="hidden mb-5 space-y-4">
                                <div class="p-4 rounded-lg bg-amber-950/20 border border-amber-500/30 text-amber-300 text-xs leading-relaxed">
                                    ⚠️ <?= __('striptease_warning') ?>
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_event_types') ?></label>
                                    <div class="space-y-2">
                                        <?php foreach (['despedidas', 'cumpleanos', 'fiestas_privadas', 'clubes_cabaret'] as $ev): ?>
                                            <label class="flex items-center text-sm font-light text-luxury-gray cursor-pointer">
                                                <input type="checkbox" name="event_types[]" value="<?= $ev ?>"
                                                       class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4 w-4">
                                                <?= __('event_' . $ev) ?>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_show_format') ?></label>
                                    <div class="space-y-2">
                                        <?php foreach (['escenario', 'tematico'] as $fmt): ?>
                                            <label class="flex items-center text-sm font-light text-luxury-gray cursor-pointer">
                                                <input type="checkbox" name="show_format[]" value="<?= $fmt ?>"
                                                       class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4 w-4">
                                                <?= __('format_' . $fmt) ?>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <p class="text-[11px] text-luxury-muted font-light leading-relaxed"><?= __('striptease_photo_note') ?></p>
                            </div>

                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-3"><?= __('field_additional_services') ?></label>
                            <div class="space-y-2.5 max-h-56 overflow-y-auto pr-1" id="additional-services-list">
                                <?php foreach ($allServices as $serv): ?>
                                    <label class="additional-service-option flex items-center text-sm font-light text-luxury-gray cursor-pointer" data-service-id="<?= $serv['id'] ?>">
                                        <input type="checkbox" name="services[]" value="<?= $serv['id'] ?>"
                                               class="services-checkbox rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4 w-4">
                                        <?= e($serv['name']) ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Languages selection -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-3"><?= __('field_languages') ?> *</label>
                            <div class="space-y-3">
                                <?php 
                                $langFlags = [
                                    'es' => '🇪🇸 Español',
                                    'fr' => '🇫🇷 Français',
                                    'en' => '🇬🇧 English',
                                    'de' => '🇩🇪 Deutsch',
                                    'it' => '🇮🇹 Italiano'
                                ];
                                foreach (SUPPORTED_LANGS as $lCode): 
                                ?>
                                    <label class="flex items-center text-sm font-light text-luxury-gray cursor-pointer">
                                        <input type="checkbox" name="languages[]" value="<?= $lCode ?>"
                                               class="languages-checkbox rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4.5 w-4.5">
                                        <?= $langFlags[$lCode] ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Perfil Influencer / Redes sociales (opcional) -->
                    <div class="border-t border-luxury-rose/10 pt-6 space-y-5">
                        <h3 class="text-xs font-bold uppercase tracking-wider text-luxury-rose"><?= __('influencer_section_title') ?></h3>
                        <p class="text-[11px] text-luxury-muted font-light -mt-2"><?= __('influencer_section_hint') ?></p>

                        <!-- Réseaux sociaux -->
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <?php
                            $socialFields = [
                                'instagram' => 'Instagram',
                                'tiktok' => 'TikTok',
                                'youtube' => 'YouTube',
                                'twitter' => 'X / Twitter',
                            ];
                            foreach ($socialFields as $netKey => $netLabel): ?>
                                <div class="flex gap-2">
                                    <div class="flex-1">
                                        <label class="block text-[11px] font-semibold uppercase tracking-wider text-luxury-muted mb-1"><?= e($netLabel) ?></label>
                                        <input type="text" name="social_<?= $netKey ?>_handle" placeholder="@usuario"
                                               class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2 outline-none focus:border-luxury-rose text-sm">
                                    </div>
                                    <div class="w-28">
                                        <label class="block text-[11px] font-semibold uppercase tracking-wider text-luxury-muted mb-1"><?= __('field_followers') ?></label>
                                        <input type="number" name="social_<?= $netKey ?>_followers" min="0" placeholder="10000"
                                               class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2 outline-none focus:border-luxury-rose text-sm">
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Audience totale -->
                        <div class="max-w-xs">
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_audience_total') ?></label>
                            <input type="number" name="audience_total" min="0" placeholder="50000"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Niche / Thématique -->
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-3"><?= __('field_niche') ?></label>
                                <div class="space-y-2">
                                    <?php foreach (['fashion', 'lifestyle', 'nightlife', 'luxury', 'fitness', 'travel'] as $nk): ?>
                                        <label class="flex items-center text-sm font-light text-luxury-gray cursor-pointer">
                                            <input type="checkbox" name="niches[]" value="<?= $nk ?>"
                                                   class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4 w-4">
                                            <?= __('niche_' . $nk) ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <!-- Types de collaboration -->
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-3"><?= __('field_collab_types') ?></label>
                                <div class="space-y-2">
                                    <?php foreach (['reels_tiktok', 'story', 'post', 'event_presence', 'ugc'] as $ck): ?>
                                        <label class="flex items-center text-sm font-light text-luxury-gray cursor-pointer">
                                            <input type="checkbox" name="collab_types[]" value="<?= $ck ?>"
                                                   class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4 w-4">
                                            <?= __('collab_' . $ck) ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- STEP 3: Pricing & Schedule -->
                <div id="step-content-3" class="step-content hidden space-y-6">
                    <h2 class="font-playfair text-xl font-semibold text-luxury-rose border-b border-luxury-rose/5 pb-2">
                        <?= __('step_3') ?>
                    </h2>
                    
                    <p class="text-xs font-light text-luxury-muted -mt-2">
<?= __('pricing_hint') ?>
                    </p>

                    <!-- Incall pricing -->
                    <div>
                        <h4 class="text-xs font-bold uppercase tracking-wider text-luxury-rose mb-3"><?= __('incall') ?></h4>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_price_30min') ?></label>
                                <input type="number" name="price_incall_30min" min="0" placeholder="100 (Opcional)"
                                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_price_1h') ?></label>
                                <input type="number" name="price_incall_1h" min="0" placeholder="150 (Opcional)"
                                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_price_night') ?></label>
                                <input type="number" name="price_incall_night" min="0" placeholder="1000 (Opcional)"
                                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            </div>
                        </div>
                    </div>

                    <!-- Outcall pricing -->
                    <div>
                        <h4 class="text-xs font-bold uppercase tracking-wider text-luxury-rose mb-3"><?= __('outcall') ?></h4>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_price_30min') ?></label>
                                <input type="number" name="price_outcall_30min" min="0" placeholder="120 (Opcional)"
                                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_price_1h') ?></label>
                                <input type="number" name="price_outcall_1h" min="0" placeholder="200 (Opcional)"
                                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_price_night') ?></label>
                                <input type="number" name="price_outcall_night" min="0" placeholder="1200 (Opcional)"
                                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- STEP 4: Contact -->
                <div id="step-content-4" class="step-content hidden space-y-6">
                    <h2 class="font-playfair text-xl font-semibold text-luxury-rose border-b border-luxury-rose/5 pb-2">
                        <?= __('step_4') ?>
                    </h2>
                    
                    <div class="space-y-6 max-w-lg">
                        <!-- Phone -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_phone') ?> *</label>
                            <input type="text" name="phone" required placeholder="+34 600 000 000"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        </div>
                        
                        <!-- WhatsApp boolean -->
                        <div class="pt-2">
                            <label class="flex items-center text-sm font-light text-luxury-gray cursor-pointer">
                                <input type="checkbox" name="whatsapp" value="1" checked
                                       class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 h-4.5 w-4.5">
                                <?= __('field_whatsapp') ?>
                            </label>
                        </div>
                        
                        <!-- Email -->
                        <div>
                            <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_email') ?> *</label>
                            <input type="email" name="email" required placeholder="tuemail@privado.com"
                                   class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                            <p class="text-[10px] text-luxury-muted mt-1.5 font-light">
                                🔒 Su correo electrónico es confidencial. Solo se usará para confirmar la publicación y enviarle alertas de seguridad.
                            </p>
                        </div>
                    </div>
                </div>

                <!-- STEP 5: Confirmation & Summary -->
                <div id="step-content-5" class="step-content hidden space-y-6">
                    <h2 class="font-playfair text-xl font-semibold text-luxury-rose border-b border-luxury-rose/5 pb-2">
                        <?= __('step_5') ?>
                    </h2>
                    
                    <div class="bg-luxury-darker/60 rounded-xl p-6 border border-luxury-rose/5 space-y-4 text-sm font-light text-luxury-gray">
                        <p class="text-xs text-luxury-muted uppercase tracking-widest font-bold mb-4">Resumen del anuncio</p>
                        
                        <div class="grid grid-cols-2 gap-y-3">
                            <span class="text-luxury-muted">Nombre:</span>
                            <span id="sum-name" class="font-semibold text-luxury-platinum"></span>
                            
                            <span class="text-luxury-muted">Edad:</span>
                            <span id="sum-age" class="text-luxury-platinum"></span>
                            
                            <span class="text-luxury-muted">Ubicación:</span>
                            <span id="sum-city" class="text-luxury-platinum"></span>
                            
                            <span class="text-luxury-muted">Nacionalidad:</span>
                            <span id="sum-nat" class="text-luxury-platinum"></span>
                            
                            <span class="text-luxury-muted">Físico:</span>
                            <span id="sum-physical" class="text-luxury-platinum"></span>
                            
                            <span class="text-luxury-muted"><?= CURRENT_LANG === 'es' ? 'Tarifa desde' : (CURRENT_LANG === 'fr' ? 'Tarif à partir de' : 'Rate from') ?>:</span>
                            <span id="sum-price" class="font-bold text-luxury-rose"></span>
                            
                            <span class="text-luxury-muted">Contacto:</span>
                            <span id="sum-contact" class="text-luxury-platinum"></span>
                        </div>
                        
                        <div class="border-t border-luxury-rose/5 pt-4 mt-4 text-xs leading-relaxed text-luxury-muted">
                            ⚠️ <?= __('publish_legal_notice') ?>
                        </div>
                    </div>

                    <!-- Aceptación obligatoria de CGU -->
                    <div class="bg-luxury-darker/60 rounded-xl p-4 border border-luxury-rose/5">
                        <label class="flex items-start text-sm font-light text-luxury-gray cursor-pointer">
                            <input type="checkbox" name="accept_terms" value="1" required
                                   class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 mt-0.5 h-4 w-4 shrink-0">
                            <span><?= __('terms_checkbox_label') ?>
                                <a href="<?= BASE_URL ?>/terminos" target="_blank" class="text-luxury-rose underline hover:text-luxury-rosehover"><?= __('terms_link_text') ?></a>.
                            </span>
                        </label>
                    </div>

                    <!-- Captcha -->
                    <div class="bg-luxury-darker/60 rounded-xl p-4 border border-luxury-rose/5 space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="text-xs font-semibold uppercase tracking-wider text-luxury-muted"><?= __('admin_captcha') ?></span>
                            <div class="flex items-center gap-2">
                                <img id="captcha-img" src="<?= BASE_URL ?>/captcha-image.php" alt="captcha" class="rounded border border-luxury-rose/15">
                                <button type="button" onclick="reloadCaptcha()" class="text-luxury-rose hover:text-luxury-rosehover text-xs" title="<?= __('captcha_reload') ?>">↻</button>
                            </div>
                        </div>
                        <input type="text" name="captcha" required autocomplete="off" placeholder="<?= __('captcha_placeholder') ?>"
                               class="bg-luxury-card text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                    </div>
                </div>

                <!-- Action Button Controls -->
                <div class="flex items-center justify-between border-t border-luxury-rose/10 pt-6 mt-8">
                    <!-- Previous Button -->
                    <button type="button" id="btn-prev" onclick="changeStep(-1)" disabled
                            class="px-5 py-2.5 border border-luxury-rose/15 hover:border-luxury-rose/30 text-luxury-muted disabled:opacity-40 disabled:cursor-not-allowed hover:text-luxury-rose text-xs font-semibold uppercase tracking-widest rounded-lg transition duration-300">
                        &larr; <?= __('btn_prev') ?>
                    </button>
                    
                    <!-- Next Button -->
                    <button type="button" id="btn-next" onclick="changeStep(1)"
                            class="px-6 py-2.5 bg-gradient-to-r from-luxury-rose to-luxury-rosehover hover:from-luxury-rosehover hover:to-luxury-rose text-luxury-dark text-xs font-bold uppercase tracking-widest rounded-lg transition duration-300 shadow">
                        <?= __('btn_next') ?> &rarr;
                    </button>
                    
                    <!-- Submit Button -->
                    <button type="submit" id="btn-submit" class="hidden px-6 py-2.5 bg-gradient-to-r from-luxury-rose to-luxury-rosehover hover:from-luxury-rosehover hover:to-luxury-rose text-luxury-dark text-xs font-bold uppercase tracking-widest rounded-lg transition duration-300 shadow">
                        <?= __('btn_submit') ?>
                    </button>
                </div>

            </form>
        <?php endif; ?>
        
    </div>
</div>

<!-- Vanilla JS Wizard Form Logic -->
<script>
    function reloadCaptcha() {
        document.getElementById('captcha-img').src = '<?= BASE_URL ?>/captcha-image.php?t=' + Date.now();
    }

    // Aperçu des photos sélectionnées avant envoi : mêmes proportions (recadrage object-cover)
    // que la grille de photos déjà uploadées, pour une cohérence visuelle immédiate.
    const mainPhotoInput = document.getElementById('main-photo-input');
    const mainPhotoPreview = document.getElementById('main-photo-preview');
    mainPhotoInput.addEventListener('change', function () {
        const file = mainPhotoInput.files[0];
        if (!file) {
            mainPhotoPreview.classList.add('hidden');
            return;
        }
        const reader = new FileReader();
        reader.onload = function (e) {
            mainPhotoPreview.querySelector('img').src = e.target.result;
            mainPhotoPreview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
    });

    const galleryPhotosInput = document.getElementById('gallery-photos-input');
    const galleryPhotosPreview = document.getElementById('gallery-photos-preview');
    galleryPhotosInput.addEventListener('change', function () {
        galleryPhotosPreview.innerHTML = '';
        Array.from(galleryPhotosInput.files).forEach(function (file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'w-full aspect-[3/4] object-cover rounded-lg border border-luxury-rose/20';
                galleryPhotosPreview.appendChild(img);
            };
            reader.readAsDataURL(file);
        });
    });

    // Le service choisi comme "principal" disparaît de la liste des services additionnels
    // (il ne peut pas être sélectionné deux fois).
    const primaryServiceSelect = document.getElementById('primary-service-select');
    function updateAdditionalServicesVisibility() {
        const primaryId = primaryServiceSelect.value;
        document.querySelectorAll('.additional-service-option').forEach(function (opt) {
            const isPrimary = opt.dataset.serviceId === primaryId;
            opt.classList.toggle('hidden', isPrimary);
            if (isPrimary) {
                opt.querySelector('.services-checkbox').checked = false;
            }
        });
    }
    primaryServiceSelect.addEventListener('change', updateAdditionalServicesVisibility);
    updateAdditionalServicesVisibility();

    // Affiche l'encadré légal + champs spectacle uniquement pour la catégorie Striptease Artístico
    const stripteaseBlock = document.getElementById('striptease-block');
    function updateStripteaseVisibility() {
        const opt = primaryServiceSelect.options[primaryServiceSelect.selectedIndex];
        const isStriptease = opt && opt.dataset.key === 'striptease_artistico';
        stripteaseBlock.classList.toggle('hidden', !isStriptease);
        if (!isStriptease) {
            stripteaseBlock.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
        }
    }
    primaryServiceSelect.addEventListener('change', updateStripteaseVisibility);
    updateStripteaseVisibility();

    let currentStep = 1;
    const totalSteps = 5;

    function changeStep(dir) {
        // Validation check before moving forward
        if (dir === 1 && !validateCurrentStep()) {
            return;
        }

        // Hide current step
        document.getElementById(`step-content-${currentStep}`).classList.add('hidden');
        document.getElementById(`step-content-${currentStep}`).classList.remove('block');

        // Update step index
        currentStep += dir;

        // Show new step
        document.getElementById(`step-content-${currentStep}`).classList.remove('hidden');
        document.getElementById(`step-content-${currentStep}`).classList.add('block');

        // Update UI components
        updateIndicators();
        updateButtons();
        
        if (currentStep === 5) {
            buildSummary();
        }
    }

    // Client-side validations per step
    function validateCurrentStep() {
        const form = document.getElementById('multi-step-form');
        
        if (currentStep === 1) {
            const firstName = form.elements['first_name'].value.trim();
            const age = parseInt(form.elements['age'].value);
            const gender = form.elements['gender'].value;
            const city = form.elements['city'].value;
            const nat = form.elements['nationality'].value;
            const height = parseInt(form.elements['height'].value);
            const weight = parseInt(form.elements['weight'].value);
            const photo = form.elements['main_photo'].files[0];

            if (!firstName || isNaN(age) || age < 18 || !gender || !city || !nat || isNaN(height) || isNaN(weight) || !photo) {
                alert("Por favor, rellene todos los campos obligatorios del Paso 1 e incluya su foto de perfil.");
                return false;
            }
        } else if (currentStep === 2) {
            const desc = form.elements['description'].value.trim();
            const primaryService = form.elements['primary_service'].value;
            const langChecked = document.querySelectorAll('.languages-checkbox:checked').length;

            if (!desc || !primaryService || langChecked === 0) {
                alert("Por favor, escriba su descripción, seleccione su servicio principal y al menos un idioma hablado.");
                return false;
            }
        } else if (currentStep === 3) {
            const priceFields = ['price_incall_30min', 'price_incall_1h', 'price_incall_night', 'price_outcall_30min', 'price_outcall_1h', 'price_outcall_night'];
            const hasPrice = priceFields.some(name => parseFloat(form.elements[name].value) > 0);
            if (!hasPrice) {
                alert("Por favor, ingrese al menos una tarifa orientativa.");
                return false;
            }
        } else if (currentStep === 4) {
            const phone = form.elements['phone'].value.trim();
            const email = form.elements['email'].value.trim();
            
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

            if (!phone || !email || !emailRegex.test(email)) {
                alert("Por favor, ingrese un número de teléfono y una dirección de correo válida.");
                return false;
            }
        }
        
        return true;
    }

    function updateIndicators() {
        // Update circles
        for (let i = 1; i <= totalSteps; i++) {
            const circle = document.getElementById(`indicator-circle-${i}`);
            const label = document.getElementById(`indicator-label-${i}`);
            
            if (i < currentStep) {
                // Done steps
                circle.className = "h-10 w-10 rounded-full flex items-center justify-center border font-semibold text-sm transition duration-300 bg-luxury-rose/25 text-luxury-rose border-luxury-rose/50";
                label.className = "text-[10px] uppercase font-bold tracking-wider mt-2 text-luxury-rose/75";
            } else if (i === currentStep) {
                // Active step
                circle.className = "h-10 w-10 rounded-full flex items-center justify-center border font-semibold text-sm transition duration-300 bg-luxury-rose text-luxury-dark border-luxury-rose";
                label.className = "text-[10px] uppercase font-bold tracking-wider mt-2 text-luxury-rose";
            } else {
                // Future steps
                circle.className = "h-10 w-10 rounded-full flex items-center justify-center border font-semibold text-sm transition duration-300 bg-luxury-card border-luxury-rose/10 text-luxury-muted";
                label.className = "text-[10px] uppercase font-bold tracking-wider mt-2 text-luxury-muted";
            }
        }

        // Fill bar percent
        const fillPercent = ((currentStep - 1) / (totalSteps - 1)) * 100;
        document.getElementById('progress-bar-fill').style.width = `${fillPercent}%`;
    }

    function updateButtons() {
        const btnPrev = document.getElementById('btn-prev');
        const btnNext = document.getElementById('btn-next');
        const btnSubmit = document.getElementById('btn-submit');

        btnPrev.disabled = currentStep === 1;

        if (currentStep === totalSteps) {
            btnNext.classList.add('hidden');
            btnSubmit.classList.remove('hidden');
            btnSubmit.classList.add('block');
        } else {
            btnNext.classList.remove('hidden');
            btnNext.classList.add('block');
            btnSubmit.classList.add('hidden');
        }
    }

    // Build the Step 5 preview summary
    function buildSummary() {
        const form = document.getElementById('multi-step-form');
        
        document.getElementById('sum-name').innerText = form.elements['first_name'].value;
        document.getElementById('sum-age').innerText = `${form.elements['age'].value} años`;
        document.getElementById('sum-city').innerText = form.elements['city'].value;
        document.getElementById('sum-nat').innerText = form.elements['nationality'].value;
        
        const h = form.elements['height'].value;
        const w = form.elements['weight'].value;
        document.getElementById('sum-physical').innerText = `${h} cm, ${w} kg`;
        
        const priceFields = ['price_incall_30min', 'price_incall_1h', 'price_incall_night', 'price_outcall_30min', 'price_outcall_1h', 'price_outcall_night'];
        const filledPrices = priceFields.map(name => parseFloat(form.elements[name].value)).filter(v => v > 0);
        const minPrice = filledPrices.length > 0 ? Math.min(...filledPrices) : 0;
        document.getElementById('sum-price').innerText = minPrice > 0 ? `${minPrice} €` : '-';
        
        const p = form.elements['phone'].value;
        const e = form.elements['email'].value;
        document.getElementById('sum-contact').innerText = `${p} / ${e}`;
    }
</script>

<?php
require_once ROOT_PATH . '/templates/partials/footer.php';
?>
