@php
    $title = 'Бронь '.$booking->booking_number.' — Hotel Pineta';
    $heading = 'Карточка брони';
    $statuses = \App\Models\Booking::statusOptions();
    $bookingIsConfirmed = $booking->status === 'confirmed';
    $subheading = $bookingIsConfirmed ? 'Просмотр подтверждённой брони' : 'Просмотр своей брони и загрузка квитанции';
    $subheadingI18n = $bookingIsConfirmed ? 'subheadingConfirmed' : 'subheading';
@endphp

@extends('layouts.guest')
@section('i18n_page', 'guest_booking_show')

@section('content')
    <div class="grid">
        @unless ($bookingIsConfirmed)
        <div class="card">
            <div class="actions-row" style="justify-content:space-between; margin-bottom:12px;">
                <div>
                    <h3 style="margin:0;">{{ $booking->booking_number }}</h3>
                    <div class="help" style="margin-top:6px;" data-i18n="cardHelp">Статус показывает итоговое состояние брони и оплаты.</div>
                </div>
                <div class="actions-row">
                    <span class="badge {{ $booking->status }} js-status" data-status="{{ $booking->status }}">{{ $statuses[$booking->status] ?? $booking->status }}</span>
                    <a href="{{ route('guest.bookings.index') }}" class="secondary" data-i18n="back">К списку</a>
                </div>
            </div>
            <div class="meta-grid">
                <div class="meta-row"><div class="k" data-i18n="roomField">Комната</div><div class="v"><span class="js-booking-room" data-room-code="{{ $booking->room?->code }}">№ {{ $booking->room?->code }} — {{ $booking->room?->title }}</span></div></div>
                <div class="meta-row"><div class="k" data-i18n="datesField">Даты</div><div class="v">{{ $booking->arrival_date?->format('d.m.Y') }} — {{ $booking->departure_date?->format('d.m.Y') }}</div></div>
                <div class="meta-row"><div class="k" data-i18n="nightsField">Ночей</div><div class="v">{{ $booking->nights }}</div></div>
                <div class="meta-row"><div class="k" data-i18n="guestsField">Гости</div><div class="v">{{ $booking->adults }} взр. · <span class="js-booking-bool" data-kind="children" data-value="{{ $booking->children_under_2 ? 1 : 0 }}">дети до 2: {{ $booking->children_under_2 ? 'Да' : 'Нет' }}</span></div></div>
                <div class="meta-row"><div class="k" data-i18n="breakfastLabel">Завтрак</div><div class="v js-booking-bool" data-kind="breakfast" data-value="{{ $booking->breakfast ? 1 : 0 }}">Завтрак: {{ $booking->breakfast ? 'Да' : 'Нет' }}</div></div>
                <div class="meta-row"><div class="k" data-i18n="variantField">Вариант</div><div class="v js-booking-variant" data-value="{{ $booking->booking_variant }}">{{ $booking->booking_variant === 'discount' ? 'Со скидкой' : 'Обычная' }}</div></div>
                <div class="meta-row"><div class="k" data-i18n="totalField">Итого</div><div class="v">{{ number_format((float) $booking->full_amount, 2, '.', ' ') }} €</div></div>
                <div class="meta-row"><div class="k" data-i18n="prepaymentField">Предоплата</div><div class="v">{{ number_format((float) $booking->prepayment_amount, 2, '.', ' ') }} €</div></div>
                <div class="meta-row"><div class="k" data-i18n="remainingField">Остаток</div><div class="v">{{ number_format((float) $booking->remaining_amount, 2, '.', ' ') }} €</div></div>
            </div>
        </div>

        <div class="card">
            <h3 style="margin-top:0;" data-i18n="paymentTitle">Квитанция и оплата</h3>
            <div class="help" style="margin-bottom:12px;" data-i18n="paymentHelp">После загрузки квитанции администратор проверит оплату и подтвердит бронь.</div>
            <div class="meta-grid" style="grid-template-columns:1fr 1fr;">
                <div class="meta-row"><div class="k" data-i18n="deadlineField">Срок предоплаты</div><div class="v">{{ $booking->payment_deadline?->format('d.m.Y H:i') ?: '—' }}</div></div>
                <div class="meta-row"><div class="k" data-i18n="checkinField">Заезд</div><div class="v">{{ $booking->check_in_time_from ?: '12:00' }} — {{ $booking->check_in_time_to ?: '23:00' }}</div></div>
            </div>

            @if (in_array($booking->status, ['awaiting_prepayment', 'payment_rejected'], true))
                <form method="post" action="{{ route('guest.bookings.receipt.store', $booking) }}" enctype="multipart/form-data" style="margin-top:16px;">
                    @csrf
                    <div class="form-grid">
                        <div class="field">
                            <label for="receipt" data-i18n="receiptFile">Файл квитанции</label>
                            <input id="receipt" type="file" name="receipt" accept=".jpg,.jpeg,.png,.pdf,.webp" required>
                        </div>
                        <div class="field">
                            <label for="note" data-i18n="receiptNote">Комментарий к квитанции</label>
                            <input id="note" type="text" name="note" value="{{ old('note') }}" placeholder="Например: предоплата за 2 ночи" data-i18n-placeholder="receiptPlaceholder">
                        </div>
                    </div>
                    <div class="actions-row" style="margin-top:14px;">
                        <button type="submit" class="primary" data-i18n="upload">Загрузить квитанцию</button>
                    </div>
                </form>
            @else
                <div class="help" style="margin-top:14px;" data-i18n="receiptNotNeeded">Для этой брони новая квитанция сейчас не требуется.</div>
            @endif
        </div>
        @endunless


        @if ($bookingIsConfirmed)
            <div class="card">
                <h3 style="margin-top:0;" data-i18n="confirmationTitle">Подтверждение бронирования</h3>
                <div class="help" data-i18n="confirmationHelp">Бронь подтверждена администратором. Сообщение можно прочитать, скопировать или скачать.</div>

                <div class="confirmation-card-preview" id="bookingConfirmationPreview"></div>

                <div class="actions-row confirmation-actions" style="margin-top:12px;">
                    <button type="button" class="primary" id="copyBookingConfirmation" data-i18n="copyConfirmation">Скопировать подтверждение</button>
                    <label class="confirmation-format-label" for="bookingConfirmationFormat" data-i18n="downloadAs">Формат</label>
                    <select id="bookingConfirmationFormat" class="confirmation-format-select">
                        <option value="txt">TXT</option>
                        <option value="jpg">JPG</option>
                        <option value="pdf">PDF</option>
                    </select>
                    <button type="button" class="secondary" id="downloadBookingConfirmation" data-i18n="downloadConfirmation">Скачать подтверждение</button>
                </div>
            </div>
        @endif

        <div class="card">
            <h3 style="margin-top:0;" data-i18n="paymentsTitle">История оплаты</h3>
            @if ($booking->payments->isEmpty())
                <div class="help" data-i18n="paymentsEmpty">Подтверждённых платёжных операций пока нет.</div>
            @else
                <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th data-i18n="payType">Тип</th>
                            <th data-i18n="payAmount">Сумма</th>
                            <th data-i18n="payStatus">Статус</th>
                            <th data-i18n="payDate">Дата</th>
                            <th data-i18n="payComment">Комментарий</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($booking->payments as $payment)
                            <tr>
                                <td>{{ $payment->type }}</td>
                                <td>{{ number_format((float) $payment->amount, 2, '.', ' ') }} €</td>
                                <td>{{ $payment->status }}</td>
                                <td>{{ $payment->paid_at?->format('d.m.Y H:i') ?: '—' }}</td>
                                <td>{{ $payment->note ?: '—' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                </div>
            @endif
        </div>
    </div>

@push('scripts')
<script>
window.PinetaConfirmationData = {
    emblemUrl: @json(asset('images/home_page/emblem.jpg')),
    hotelName: 'Hotel Pineta',
    bookingNumber: @json($booking->booking_number),
    guestName: @json($booking->guest_name),
    discountCode: @json(($booking->discount_applied && strtolower((string) $booking->source) !== 'booking') ? ($booking->discount_code ?: null) : null),
    nights: @json((int) $booking->nights),
    guests: @json((int) $booking->adults),
    childrenUnder2: @json((int) $booking->children_under_2),
    breakfast: @json((bool) $booking->breakfast),
    arrivalDate: @json($booking->arrival_date?->format('Y-m-d')),
    source: @json($booking->source),
    fullAmount: @json((float) $booking->full_amount),
    prepaymentAmount: @json((float) $booking->prepayment_amount),
    remainingAmount: @json((float) $booking->remaining_amount),
    phone: @json($booking->phone),
    confirmedAt: @json($booking->confirmed_at?->format('Y-m-d')),
};
</script>
<script src="{{ asset('assets/js/booking-confirmation.js') }}"></script>
@endpush

@endsection
