@php
    $isDiscount = $variant === 'discount';
    $roomNames = $rooms->mapWithKeys(fn($room) => [$room->code => '№ '.$room->code.' — '.$room->title])->all();
    $roomIds = $rooms->mapWithKeys(fn($room) => [$room->code => $room->id])->all();
    $roomPhotos = $rooms->mapWithKeys(function ($room) {
        $folder = str_replace('А', 'A', $room->code);
        return [
            $room->code => collect(range(1,4))->map(fn($i) => asset('images/room/'.$folder.'/'.$i.'.jpg'))->all(),
        ];
    })->all();
    $selectedCode = array_search((int) old('room_id', 0), $roomIds, true);
    $selectedCode = $selectedCode === false ? '' : $selectedCode;
@endphp
<!doctype html>
<html lang="ru">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ $isDiscount ? 'Бронирование со скидкой' : 'Гостевое бронирование' }} — Hotel Pineta</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{ asset('assets/css/registration.css') }}">
    @include('partials.legacy-booking-extra-styles')
</head>
<body data-i18n-page="guest_booking_form">
<div class="page">
    <div class="container booking-shell">
        <div class="top-actions">
            <a class="button-outline" href="{{ route('home') }}">← На главную</a>
            @if($isDiscount)
                <a class="button-outline" href="{{ route('guest.bookings.index') }}">Мои брони</a>
                <form action="{{ route('guest.logout') }}" method="post" style="display:inline">@csrf<button class="button-outline" type="submit">Выйти</button></form>
            @else
                <a class="button-outline" href="{{ route('guest.login') }}">Вход со скидкой</a>
                <a class="button-outline" href="{{ route('guest.register') }}">Регистрация со скидкой</a>
                <a class="button-outline" href="{{ route('public.rooms') }}">Номера</a>
            @endif
        </div>

        @if(session('success'))
            <div class="alert alert-success">{{ session('success') }}</div>
        @endif

        @if($errors->any())
            <div class="alert alert-danger">
                @foreach($errors->all() as $error)
                    <div>{{ $error }}</div>
                @endforeach
            </div>
        @endif

        <div class="page-grid">
            <div>
                <div class="card layout-block">
                    <div class="eyebrow">{{ $isDiscount ? 'Гостевое бронирование со скидкой' : 'Гостевое бронирование без скидки' }}</div>
                    <h1>{{ $isDiscount ? 'Бронирование со скидкой' : 'Бронирование с сайта' }}</h1>
                    <div class="source-pill">Источник: Site</div>
                    @if($isDiscount && $guest)
                        <div class="discount-box">
                            <div><strong>Гость</strong>{{ $guest->full_name }}</div>
                            <div><strong>Скидка</strong><span class="discount-percent-value">До 25%</span></div>
                            <div><strong>Код</strong>{{ $defaults['discount_code'] ?: ($guest->discount_code ?: 'PINETA'.max(10, (int) $guest->discount_percent).'-VIP') }}</div>
                        </div>
                    @endif
                    <div class="legend">
                        <span class="legend-item"><span class="dot dot-free"></span>Свободно</span>
                        <span class="legend-item"><span class="dot dot-held"></span>Ждём оплату</span>
                        <span class="legend-item"><span class="dot dot-occupied"></span>Подтверждено</span>
                        <span class="legend-item"><span class="dot dot-selected"></span>Выбрано</span>
                    </div>
                </div>

                <div class="layout-block guest-room-selection-block">
                    <h3 class="layout-title">Выберите номер</h3>
                    <div class="guest-room-scroll">
                        <div class="floors-wrap">
                            <div class="floor-card">
                                <div class="floor-title">Третий этаж</div>
                                <div class="rooms-grid" id="gridFloor3"></div>
                            </div>
                            <div class="floor-card">
                                <div class="floor-title">Второй этаж</div>
                                <div class="rooms-grid" id="gridFloor2"></div>
                            </div>
                        </div>
                    </div>
                    <div class="note-line">Жёлтый цвет означает, что номер уже удержан до получения оплаты.</div>
                </div>

                <div class="room-gallery-modal" id="roomGalleryModal" hidden>
                    <div class="room-gallery-dialog" role="dialog" aria-modal="true" aria-labelledby="roomGalleryTitle">
                        <div class="room-gallery-header">
                            <h3 class="room-gallery-title" id="roomGalleryTitle">Фотографии комнаты</h3>
                            <button type="button" class="room-gallery-close" id="roomGalleryClose">Закрыть</button>
                        </div>
                        <div class="room-gallery-grid" id="roomGalleryGrid"></div>
                    </div>
                </div>

                <div class="card">
                    <form action="{{ route('guest.bookings.store') }}" method="post" class="grid" id="{{ $isDiscount ? 'guestBookingDiscountForm' : 'guestBookingForm' }}">
                        @csrf
                        <input type="hidden" name="booking_variant" value="{{ $isDiscount ? 'discount' : 'regular' }}">
                        <input type="hidden" name="departure_date" id="departureDateHidden" value="{{ old('departure_date', $defaults['departure_date']) }}">
                        <input type="hidden" name="discount_code" id="discountInput" value="{{ old('discount_code', $defaults['discount_code']) }}">
                        <input type="hidden" id="guestLang" value="ru">
                        <input type="hidden" name="lang" id="bookingLangInput" value="ru">

                        @if($isDiscount)
                            <div class="col-6">
                                <label>Имя и фамилия</label>
                                <input type="text" value="{{ $guest?->full_name }}" readonly>
                            </div>
                            <div class="col-6">
                                <label>Телефон</label>
                                <input class="pineta-phone-input" data-pineta-phone="1" type="tel" value="{{ $guest?->phone }}" readonly>
                            </div>
                            <div class="col-6">
                                <label>Email</label>
                                <input type="email" value="{{ $guest?->email }}" readonly>
                            </div>
                        @else
                            <div class="col-6">
                                <label>Имя и фамилия *</label>
                                <input type="text" name="full_name" id="guestNameInput" data-pineta-name="1" value="{{ old('full_name', $defaults['full_name']) }}" required>
                            </div>
                            <div class="col-6">
                                <label>Телефон *</label>
                                <input class="pineta-phone-input" data-pineta-phone="1" type="tel" name="phone" value="{{ old('phone', $defaults['phone']) }}" placeholder="39 000 000 0000" required>
                            </div>
                            <div class="col-6">
                                <label>Email</label>
                                <input type="email" name="email" value="{{ old('email', $defaults['email']) }}">
                            </div>
                        @endif

                        <div class="col-6">
                            <label>Дата заезда *</label>
                            <input type="date" name="arrival_date" id="arrivalDate" min="{{ now()->format('Y-m-d') }}" required value="{{ old('arrival_date', $defaults['arrival_date']) }}">
                        </div>
                        <div class="col-12 min-nights-form-block" id="minNightsFormBlock">
                            <div class="price-line min-nights-line"><strong id="minNightsLabelText">Минимум дней на эту дату</strong><span id="minNightsValue">—</span></div>
                            <div class="status-line" id="restrictionStatus"></div>
                        </div>
                        <div class="col-6">
                            <label>Выбранный номер *</label>
                            <select name="room_id" id="roomSelect" required><option value="">Сначала выберите дату</option></select>
                        </div>
                        <div class="col-3">
                            <label>Ночей *</label>
                            <input type="number" id="nightsInput" min="1" max="30" required value="{{ old('nights', 1) }}">
                        </div>
                        <div class="col-3">
                            <label>Гостей *</label>
                            <select name="adults" id="guestsCount" required>
                                <option value="1" @selected(old('adults', $defaults['adults']) == 1)>1</option>
                                <option value="2" @selected(old('adults', $defaults['adults']) == 2)>2</option>
                                <option value="3" @selected(old('adults', $defaults['adults']) == 3)>3</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="toggle-line"><input type="checkbox" name="children_under_2" id="childrenSelect" value="1" @checked(old('children_under_2', $defaults['children_under_2']))><span>Дети до 2 лет</span></label>
                        </div>
                        <div class="col-6">
                            <label class="toggle-line"><input type="checkbox" name="breakfast" id="breakfastInput" value="1" @checked(old('breakfast', $defaults['breakfast']))><span>Нужен завтрак</span></label>
                        </div>
                        <div class="col-12">
                            <label>Комментарий гостя</label>
                            <textarea name="comment_guest" maxlength="1000" placeholder="Пожелания по номеру, времени прибытия и т.п.">{{ old('comment_guest') }}</textarea>
                        </div>
                        <div class="col-12">
                            <div class="form-actions">
                                <button type="submit" class="button" id="submitBtn">Создать предварительное бронирование</button><div class="loading-indicator submit-loading" id="submitLoadingIndicator" hidden><span class="loading-spinner" aria-hidden="true"></span><span class="loading-text">Сохраняем бронирование…</span></div>
                                @if(!$isDiscount)
                                    <a href="{{ route('guest.register') }}" class="button-outline">Зарегистрироваться и получить скидку</a>
                                @else
                                    <a href="{{ route('guest.bookings.index') }}" class="button-outline">Мои брони</a>
                                @endif
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div>
                <div class="loading-indicator" id="formLoadingIndicator" hidden><span class="loading-spinner" aria-hidden="true"></span><span class="loading-text">Загружаем цены, итог и занятые номера…</span></div>
                <div class="layout-block">
                    <h3 class="layout-title">Стоимость и ограничения за день</h3>
                    <div class="price-lines">
                        <div class="price-section-label other-sites-label" id="externalRatesTitle">Стоимость на других сайтах</div>
                        <div class="price-line external-rate-line" id="priceLineWB"><strong>Цена с завтраком</strong><span id="priceWB">—</span></div>
                        <div class="price-line external-rate-line" id="priceLineNB"><strong>Цена без завтрака</strong><span id="priceNB">—</span></div>
                        <div class="price-line external-rate-line" id="priceLineWB3"><strong>Цена с завтраком &gt; 3 дней</strong><span id="priceWB3">—</span></div>
                        <div class="price-line external-rate-line" id="priceLineNB3"><strong>Цена без завтрака &gt; 3 дней</strong><span id="priceNB3">—</span></div>
                        <div class="price-section-label discount-sites-label" id="discountRatesTitle">Стоимость со скидкой Hotel Pineta</div>
                        <div class="price-line" id="priceLineWBD"><strong>Цена с завтраком со скидкой</strong><span id="priceWBD">—</span></div>
                        <div class="price-line" id="priceLineNBD"><strong>Цена без завтрака со скидкой</strong><span id="priceNBD">—</span></div>
                        <div class="price-line" id="priceLineWBD3"><strong>Цена с завтраком со скидкой &gt; 3 дней</strong><span id="priceWBD3">—</span></div>
                        <div class="price-line" id="priceLineNBD3"><strong>Цена без завтрака со скидкой &gt; 3 дней</strong><span id="priceNBD3">—</span></div>
                    </div>
                </div>
                <div class="quote-box">
                    <div class="quote-label">Итог по бронированию</div>
                    <div class="quote-main" id="totalMain">—</div>
                    <div class="quote-list">
                        <div>Ночей: <strong id="summaryNights">—</strong></div>
                        <div>Предоплата: <strong id="prepaymentLine">—</strong></div>
                        <div>Остаток: <strong id="remainingLine">—</strong></div>
                    </div>
                    <div class="warning-box" id="quoteWarning">Заполните дату, номер и количество ночей, чтобы увидеть расчёт и ограничения.</div>
                </div>

                <div class="layout-block" style="margin-top:18px;">
                    <h3 class="layout-title">Первое гостевое сообщение</h3>
                    <textarea class="readonly-message guest-offer-message" id="offerMessage" readonly>{{ $createdBookingData['offer_message'] ?? '' }}</textarea>
                    <div class="copy-row">
                        <button type="button" class="button-outline" id="copyOfferBtn">Скопировать сообщение</button>
                    </div>
                </div>

                <div class="layout-block" id="paymentDetailsBlock" style="margin-top:18px;" @if(!$createdBookingData) hidden @endif>
                    <h3 class="layout-title">Реквизиты для оплаты</h3>
                    <textarea class="readonly-message payment-message" id="paymentDetailsMessage" readonly>{{ $createdBookingData['payment_message'] ?? '' }}</textarea>
                    <div class="copy-row">
                        <button type="button" class="button-outline" id="copyPaymentBtn">Скопировать реквизиты</button>
                    </div>
                </div>

                <div class="layout-block receipt-upload-block" id="receiptUploadBlock" style="margin-top:18px;" @if(!$createdBookingData) hidden @endif>
                    <div class="receipt-upload-head">
                        <div>
                            <h3 class="layout-title">Загрузка квитанции о предоплате</h3>
                            <div class="receipt-upload-note">После оплаты Вы можете загрузить фото или PDF квитанции прямо на сайт. Файл сразу попадёт в Laravel-проект и будет доступен администратору.</div>
                            <div class="receipt-upload-meta">Номер бронирования: <span id="receiptReservationId">{{ $createdBookingData['reservation_id'] ?? '—' }}</span></div>
                        </div>
                    </div>
                    <form id="receiptUploadForm" action="{{ $receiptUploadUrl }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <input type="hidden" name="reservation_id" id="receiptReservationIdInput" value="{{ $createdBookingData['reservation_id'] ?? '' }}">
                        <input type="hidden" name="token" id="receiptTokenInput" value="{{ $createdBookingData['secure_token'] ?? '' }}">
                        <input type="hidden" name="lang" id="receiptLangInput" value="ru">
                        <div class="receipt-upload-actions">
                            <input class="receipt-native-file" type="file" name="receipt" id="receiptFileInput" accept=".jpg,.jpeg,.png,.webp,.pdf,application/pdf,image/jpeg,image/png,image/webp">
                            <label for="receiptFileInput" class="receipt-file-button" id="receiptFileButton">Выберите файл</label>
                            <span class="receipt-file-name" id="receiptFileName">Файл не выбран</span>
                            <button type="button" class="button-outline" id="receiptUploadBtn" disabled>Загрузить квитанцию</button>
                        </div>
                        <div class="receipt-upload-help">Допустимые файлы: JPG, PNG, WEBP или PDF до 5 МБ.</div>
                        <div class="loading-indicator receipt-upload-loading" id="receiptUploadLoading" hidden><span class="loading-spinner" aria-hidden="true"></span><span class="loading-text" id="receiptUploadLoadingText">Загружаем квитанцию…</span></div>
                        <div class="receipt-upload-status" id="receiptUploadStatus"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
window.GUEST_PAGE_VARIANT = @json($variant);
window.guestName = @json($guest?->full_name);
window.PinetaBookingFormConfig = {
    mode: 'guest',
    variant: @json($variant),
    availabilityUrl: @json($availabilityUrl),
    quoteUrl: @json($quoteUrl),
    receiptUploadUrl: @json($receiptUploadUrl),
    roomNames: @json($roomNames, JSON_UNESCAPED_UNICODE),
    roomIds: @json($roomIds, JSON_UNESCAPED_UNICODE),
    roomPhotos: @json($roomPhotos, JSON_UNESCAPED_UNICODE),
    selectedCode: @json($selectedCode),
    hasSuccessFlash: @json($hasSuccessFlash),
    createdBookingData: @json($createdBookingData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
};
</script>
<script src="{{ asset('assets/js/phone-fields.js') }}"></script>
<script src="{{ asset('assets/js/name-fields.js') }}"></script>
<script src="{{ asset('assets/js/legacy-booking-form.js') }}"></script>
<script src="{{ asset('assets/js/guest-multilang.js') }}"></script>
<script>
(function(){
    const T = {
        it:{home:'← Home',login:'Accesso con sconto',register:'Registrazione con sconto',rooms:'Camere',regular:'Modulo normale senza sconto',bookings:'Le mie prenotazioni',logout:'Esci'},
        en:{home:'← Home',login:'Discount login',register:'Discount registration',rooms:'Rooms',regular:'Regular form without discount',bookings:'My bookings',logout:'Log out'},
        ru:{home:'← На главную',login:'Вход со скидкой',register:'Регистрация со скидкой',rooms:'Номера',regular:'Обычная форма без скидки',bookings:'Мои брони',logout:'Выйти'},
        uk:{home:'← На головну',login:'Вхід зі знижкою',register:'Реєстрація зі знижкою',rooms:'Номери',regular:'Звичайна форма без знижки',bookings:'Мої бронювання',logout:'Вийти'},
        fr:{home:'← Accueil',login:'Connexion avec remise',register:'Inscription avec remise',rooms:'Chambres',regular:'Formulaire normal sans remise',bookings:'Mes réservations',logout:'Se déconnecter'},
        de:{home:'← Startseite',login:'Anmeldung mit Rabatt',register:'Registrierung mit Rabatt',rooms:'Zimmer',regular:'Normales Formular ohne Rabatt',bookings:'Meine Buchungen',logout:'Abmelden'}
    };
    function norm(v){v=(v||'it').toLowerCase().split('-')[0]; return ['it','en','ru','uk','fr','de'].includes(v)?v:'it';}
    function apply(){
        const lang = norm(localStorage.getItem('hotel-pineta-lang') || document.documentElement.lang);
        const m = T[lang] || T.it;
        const links = document.querySelectorAll('.top-actions a');
        const logoutBtn = document.querySelector('.top-actions form button');
        if (!links.length) return;
        links[0] && (links[0].textContent = m.home);
        if (@json($isDiscount)) {
            links[1] && (links[1].textContent = m.bookings);
            logoutBtn && (logoutBtn.textContent = m.logout);
        } else {
            links[1] && (links[1].textContent = m.login);
            links[2] && (links[2].textContent = m.register);
            links[3] && (links[3].textContent = m.rooms);
        }
    }
    apply();
})();
</script>
</body>
</html>
