@extends('layouts.app')

@section('title', __('bms::lang.booking') . ' ' . ($booking->booking_no ?: ('#' . $booking->id)))

@php
    $st = $booking->status;
    $stClass = ['tentative'=>'label-warning','confirmed'=>'label-primary','contracted'=>'label-info','completed'=>'label-success','cancelled'=>'label-default'][$st] ?? 'label-default';
    $money = fn($n) => '<span class="display_currency" data-currency_symbol="true">'.(float)$n.'</span>';
@endphp

@section('content')
<section class="content-header">
    <h1>
        <i class="fa fas fa-glass-cheers"></i> {{ $booking->booking_no ?: ('#' . $booking->id) }}
        <small>{{ optional($booking->contact)->name }} · {{ optional($booking->event_date)->format('Y-m-d') }}</small>
        <span class="label {{ $stClass }}">{{ __('bms::lang.st_' . $st) !== 'bms::lang.st_' . $st ? __('bms::lang.st_' . $st) : ucfirst($st) }}</span>
    </h1>
    <a href="{{ route('bms.bookings.index') }}" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline" style="margin-top:6px;"><i class="fa fa-arrow-left"></i> @lang('bms::lang.bookings')</a>
</section>

<section class="content">
    @if (session('status'))<div class="alert alert-success">{{ session('status') }}</div>@endif
    @if (session('error'))<div class="alert alert-danger">{{ session('error') }}</div>@endif

    {{-- Lifecycle actions --}}
    @if ($canManage && $st !== 'cancelled' && $st !== 'completed')
    <div class="box box-solid"><div class="box-body">
        @if ($st === 'tentative')
            <form method="POST" action="{{ route('bms.bookings.confirm', $booking->id) }}" style="display:inline">@csrf
                <button class="tw-dw-btn tw-dw-btn-primary tw-text-white"><i class="fa fa-check"></i> @lang('bms::lang.confirm_booking')</button>
            </form>
        @elseif ($st === 'confirmed')
            <form method="POST" action="{{ route('bms.bookings.contract', $booking->id) }}" style="display:inline">@csrf
                <button class="tw-dw-btn tw-dw-btn-primary tw-text-white"><i class="fa fa-file-signature"></i> @lang('bms::lang.contract_booking')</button>
            </form>
        @elseif ($st === 'contracted')
            <form method="POST" action="{{ route('bms.bookings.complete', $booking->id) }}" style="display:inline">@csrf
                <button class="tw-dw-btn tw-dw-btn-primary tw-text-white"><i class="fa fa-flag-checkered"></i> @lang('bms::lang.complete_booking')</button>
            </form>
        @endif
        <button type="button" class="tw-dw-btn tw-dw-btn-outline" data-toggle="collapse" data-target="#resched"><i class="fa fa-calendar"></i> @lang('bms::lang.reschedule_booking')</button>
        @can('bms.qc.view')
            <a href="{{ route('bms.qc.run', $booking->id) }}" class="tw-dw-btn tw-dw-btn-outline"><i class="fa fa-clipboard-check"></i> @lang('bms::lang.qc_inspection')</a>
        @endcan
        @if ($canCancel)
            <button type="button" class="tw-dw-btn tw-dw-btn-outline tw-dw-btn-error" data-toggle="collapse" data-target="#cancelbox"><i class="fa fa-ban"></i> @lang('bms::lang.cancel_booking')</button>
        @endif

        <div id="resched" class="collapse" style="margin-top:12px;">
            {!! Form::open(['route' => ['bms.bookings.reschedule', $booking->id]]) !!}
            <div class="row">
                <div class="col-sm-3 form-group"><label>@lang('bms::lang.new_event_date')</label>{!! Form::date('event_date', null, ['class'=>'form-control','required']) !!}</div>
                @can('bms.bookings.override_penalty')<div class="col-sm-3 form-group"><label>@lang('bms::lang.override_penalty')</label>{!! Form::number('override_penalty_percent', null, ['class'=>'form-control','min'=>0,'max'=>100,'step'=>'0.5']) !!}</div>@endcan
                <div class="col-sm-3" style="margin-top:25px;"><button class="tw-dw-btn tw-dw-btn-primary tw-text-white">@lang('bms::lang.reschedule_booking')</button></div>
            </div>
            {!! Form::close() !!}
        </div>
        @if ($canCancel)
        <div id="cancelbox" class="collapse" style="margin-top:12px;">
            {!! Form::open(['route' => ['bms.bookings.cancel', $booking->id]]) !!}
            @php $loc = app()->getLocale() === 'ar' ? 'ar' : 'en'; @endphp
            <div class="row">
                <div class="col-sm-4 form-group"><label>@lang('bms::lang.cancellation_reason')</label>
                    <select name="reason_code" class="form-control">
                        <option value="">—</option>
                        @foreach (($reasons ?? []) as $r)<option value="{{ $r['code'] }}">{{ $r[$loc] ?? $r['en'] ?? $r['code'] }}</option>@endforeach
                    </select>
                </div>
                <div class="col-sm-4 form-group"><label>@lang('bms::lang.notes')</label>{!! Form::text('reason', null, ['class'=>'form-control']) !!}</div>
                @can('bms.bookings.override_penalty')<div class="col-sm-3 form-group"><label>@lang('bms::lang.override_penalty')</label>{!! Form::number('override_penalty_percent', null, ['class'=>'form-control','min'=>0,'max'=>100,'step'=>'0.5']) !!}</div>@endcan
                <div class="col-sm-3" style="margin-top:25px;"><button class="tw-dw-btn tw-dw-btn-error tw-text-white" onclick="return confirm('{{ __('bms::lang.are_you_sure') }}')">@lang('bms::lang.cancel_booking')</button></div>
            </div>
            {!! Form::close() !!}
        </div>
        @endif
    </div></div>
    @endif

    <div class="row">
        {{-- Client + halls --}}
        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('bms::lang.client')])
                <p><strong>{{ optional($booking->contact)->name ?: '—' }}</strong></p>
                @if (optional($booking->contact)->mobile)<p><i class="fa fa-phone"></i> {{ $booking->contact->mobile }}</p>@endif
                @if (optional($booking->contact)->email)<p><i class="fa fa-envelope"></i> {{ $booking->contact->email }}</p>@endif
                <hr>
                <p class="text-muted" style="margin:0 0 4px;">@lang('bms::lang.halls')</p>
                @forelse ($booking->halls as $bh)
                    <span class="label label-default">{{ $hallNames[$bh->hall_id] ?? ('#' . $bh->hall_id) }}</span>
                @empty <span class="text-muted">—</span> @endforelse
                @if ($booking->reschedule_count)<p class="text-muted" style="margin-top:8px;"><i class="fa fa-history"></i> @lang('bms::lang.reschedule_booking') × {{ $booking->reschedule_count }}</p>@endif
                @if ($st === 'cancelled')<hr><p class="text-danger">@lang('bms::lang.penalty_amount'): {!! $money($booking->penalty_amount) !!} · @lang('bms::lang.refund_amount'): {!! $money($booking->refund_amount) !!}</p>@endif
            @endcomponent
        </div>

        {{-- Invoice + payments --}}
        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('bms::lang.invoice')])
                @if ($st === 'tentative')
                    <p class="text-muted">@lang('bms::lang.confirm_to_invoice')</p>
                @else
                    <table class="table table-condensed">
                        <tr><td>@lang('bms::lang.invoice_no')</td><td class="text-right">{{ $invoice['invoice_no'] ?? '—' }}</td></tr>
                        <tr><td>@lang('bms::lang.total')</td><td class="text-right">{!! $money($invoice['total'] ?? 0) !!}</td></tr>
                        <tr><td>@lang('bms::lang.paid')</td><td class="text-right text-success">{!! $money($invoice['paid'] ?? 0) !!}</td></tr>
                        <tr><td>@lang('bms::lang.due')</td><td class="text-right">{!! $money($invoice['due'] ?? 0) !!}</td></tr>
                    </table>
                    @if ($canManage && ($invoice['due'] ?? 0) > 0 && $st !== 'cancelled')
                        {!! Form::open(['route' => ['bms.bookings.pay', $booking->id]]) !!}
                        <div class="row">
                            <div class="col-sm-5 form-group">{!! Form::number('amount', null, ['class'=>'form-control','placeholder'=>__('bms::lang.amount'),'min'=>1,'step'=>'0.01','required']) !!}</div>
                            <div class="col-sm-4 form-group">{!! Form::select('method', ['cash'=>__('bms::lang.deposit'),'bank_transfer'=>'Bank','card'=>'Card'], 'cash', ['class'=>'form-control']) !!}</div>
                            <div class="col-sm-3"><button class="tw-dw-btn tw-dw-btn-primary tw-text-white">@lang('bms::lang.record_payment')</button></div>
                        </div>
                        {!! Form::close() !!}
                    @endif
                @endif
            @endcomponent

            @if (!empty($schedule))
            @component('components.widget', ['class' => 'box-default', 'title' => __('bms::lang.payment_schedule')])
                <table class="table table-condensed">
                    @foreach ($schedule as $s)
                        <tr><td>{{ $s['label'] }}<br><small class="text-muted">{{ $s['due_date'] }} · {{ rtrim(rtrim(number_format($s['percent'],1),'0'),'.') }}%</small></td>
                            <td class="text-right">{!! $money($s['amount']) !!}<br><span class="label label-{{ $s['status']==='paid'?'success':($s['status']==='overdue'?'danger':'default') }}">{{ __('bms::lang.ps_'.$s['status']) }}</span></td></tr>
                    @endforeach
                </table>
            @endcomponent
            @endif
        </div>

        {{-- Documents + tasks --}}
        <div class="col-md-4">
            @if ($canManage && $st !== 'tentative')
            @component('components.widget', ['class' => 'box-primary', 'title' => __('bms::lang.documents')])
                <div style="margin-bottom:10px;">
                    @foreach (['contract','beo','run_sheet'] as $dt)
                        <form method="POST" action="{{ route('bms.bookings.document', [$booking->id, $dt]) }}" style="display:inline">@csrf
                            <button class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline">+ @lang('bms::lang.doc_'.$dt)</button>
                        </form>
                    @endforeach
                </div>
                @forelse ($documents as $d)
                    <div style="padding:5px 0;border-bottom:1px dashed #eee;">
                        @lang('bms::lang.doc_'.$d->type) <small class="text-muted">v{{ $d->version }}</small>
                        <span class="pull-right">
                            <a href="{{ route('bms.documents.view', [$d->id, 'en']) }}" target="_blank" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline">EN</a>
                            <a href="{{ route('bms.documents.view', [$d->id, 'ar']) }}" target="_blank" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline">ع</a>
                        </span>
                    </div>
                @empty <p class="text-muted">@lang('bms::lang.no_documents')</p> @endforelse
            @endcomponent
            @endif

            @component('components.widget', ['class' => 'box-default', 'title' => __('bms::lang.tasks')])
                @forelse ($tasks as $t)
                    <div style="padding:5px 0;border-bottom:1px dashed #eee;">
                        <small class="text-muted text-uppercase">{{ $t->department }}</small><br>
                        {{ $t->title }}
                        <span class="pull-right label label-{{ $t->status==='done'?'success':($t->status==='cancelled'?'default':'warning') }}">{{ $t->status }}</span>
                    </div>
                @empty <p class="text-muted">@lang('bms::lang.no_tasks')</p> @endforelse
            @endcomponent
        </div>
    </div>

    {{-- Package customization (kept add-ons, variant swaps, buffet substitutions) --}}
    @if (!empty($customizations))
    @component('components.widget', ['class' => 'box-default', 'title' => __('bms::lang.customizations')])
        @foreach ($customizations as $cust)
            <h5 style="margin-top:0;"><i class="fa fa-building"></i> {{ $cust['hall'] }}</h5>
            @if (!empty($cust['extras']))
                <p style="margin-bottom:4px;"><strong>@lang('bms::lang.addons_label'):</strong></p>
                <ul style="margin-bottom:8px;">
                    @foreach ($cust['extras'] as $ex)
                        <li>{{ $ex['name'] }} @if($ex['qty']>1)<span class="text-muted">× {{ $ex['qty'] }}</span>@endif
                            @if($ex['price'])<span class="pull-right">+<span class="display_currency" data-currency_symbol="true">{{ $ex['price'] * $ex['qty'] }}</span></span>@endif</li>
                    @endforeach
                </ul>
            @endif
            @if (!empty($cust['swaps']))
                <p style="margin-bottom:4px;"><strong>@lang('bms::lang.swap_for'):</strong></p>
                <ul style="margin-bottom:8px;">
                    @foreach ($cust['swaps'] as $sw)
                        <li><span class="text-muted">{{ $sw['item'] }}:</span> {{ $sw['label'] }}
                            @if($sw['delta'])<span class="pull-right">{{ $sw['delta']>0?'+':'' }}<span class="display_currency" data-currency_symbol="true">{{ $sw['delta'] }}</span></span>@endif</li>
                    @endforeach
                </ul>
            @endif
        @endforeach
    @endcomponent
    @endif

    {{-- Light field edit --}}
    @if ($canManage && $st !== 'cancelled')
    @component('components.widget', ['class' => 'box-default', 'title' => __('bms::lang.booking_details')])
        {!! Form::open(['route' => ['bms.bookings.update', $booking->id], 'method' => 'PUT']) !!}
        <div class="row">
            <div class="col-sm-3 form-group">{!! Form::label('event_type', __('bms::lang.event_type')) !!}{!! Form::text('event_type', $booking->event_type, ['class'=>'form-control']) !!}</div>
            <div class="col-sm-2 form-group">{!! Form::label('attendees', __('bms::lang.attendees')) !!}{!! Form::number('attendees', $booking->attendees, ['class'=>'form-control','min'=>0]) !!}</div>
            <div class="col-sm-2 form-group">{!! Form::label('start_time', __('bms::lang.open_time')) !!}{!! Form::time('start_time', $booking->start_time, ['class'=>'form-control']) !!}</div>
            <div class="col-sm-2 form-group">{!! Form::label('end_time', __('bms::lang.close_time')) !!}{!! Form::time('end_time', $booking->end_time, ['class'=>'form-control']) !!}</div>
        </div>
        <div class="form-group">{!! Form::label('notes', __('bms::lang.notes')) !!}{!! Form::textarea('notes', $booking->notes, ['class'=>'form-control','rows'=>2]) !!}</div>
        <button type="submit" class="tw-dw-btn tw-dw-btn-default"><i class="fa fa-save"></i> @lang('messages.update')</button>
        {!! Form::close() !!}
    @endcomponent
    @endif
</section>
@endsection
