@extends('layouts.app')

@section('title', __('bms::lang.new_booking'))

@section('content')
<section class="content-header">
    <h1><i class="fa fas fa-glass-cheers"></i> @lang('bms::lang.new_booking')</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('error'))<div class="alert alert-danger">{{ session('error') }}</div>@endif
    @if ($errors->any())<div class="alert alert-danger"><ul style="margin:0;">@foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul></div>@endif

    {!! Form::open(['route' => 'bms.bookings.store', 'id' => 'bms-new-booking']) !!}
    @component('components.widget', ['class' => 'box-primary', 'title' => __('bms::lang.client')])
        <div class="row">
            <div class="col-sm-4 form-group">{!! Form::label('new_name', __('bms::lang.col_contact') . ':*') !!}{!! Form::text('new_name', null, ['class'=>'form-control','required']) !!}</div>
            <div class="col-sm-4 form-group">{!! Form::label('new_phone', __('bms::lang.f_phone') . ':*') !!}{!! Form::text('new_phone', null, ['class'=>'form-control','required']) !!}</div>
            <div class="col-sm-4 form-group">{!! Form::label('new_email', __('bms::lang.f_email') . ':') !!}{!! Form::email('new_email', null, ['class'=>'form-control']) !!}</div>
        </div>
        <p class="help-block">@lang('bms::lang.new_booking_contact_help')</p>
    @endcomponent

    @component('components.widget', ['class' => 'box-primary', 'title' => __('bms::lang.event_details')])
        <div class="row">
            <div class="col-sm-3 form-group">{!! Form::label('event_type', __('bms::lang.event_type')) !!}{!! Form::select('event_type', $eventTypes, 'wedding', ['class'=>'form-control']) !!}</div>
            <div class="col-sm-3 form-group">{!! Form::label('attendees', __('bms::lang.attendees')) !!}{!! Form::number('attendees', ($prefill['attendees'] ?? null) ?: 200, ['class'=>'form-control','min'=>0]) !!}</div>
            <div class="col-sm-3 form-group">{!! Form::label('event_date', __('bms::lang.event_date') . ':*') !!}{!! Form::date('event_date', $prefill['event_date'] ?? null, ['class'=>'form-control','required','min'=>now()->toDateString()]) !!}</div>
        </div>
        <div class="row">
            <div class="col-sm-6 form-group">
                {!! Form::label('hall_id', __('bms::lang.hall') . ':*') !!}
                <select name="hall_id" id="hall_id" class="form-control" required>
                    <option value="">— @lang('bms::lang.hall') —</option>
                    @foreach ($halls as $h)<option value="{{ $h->id }}" {{ ($prefill['hall_id'] ?? null) == $h->id ? 'selected' : '' }}>{{ $h->name }}</option>@endforeach
                </select>
            </div>
            <div class="col-sm-6 form-group">
                {!! Form::label('package_id', __('bms::lang.packages')) !!}
                <select name="package_id" id="package_id" class="form-control">
                    <option value="">— @lang('bms::lang.packages') —</option>
                    @foreach ($packages as $p)<option value="{{ $p['id'] }}" data-halls="{{ implode(',', $p['hall_ids']) }}" data-price="{{ $p['price'] }}">{{ $p['name'] }} ({{ number_format($p['price']) }})</option>@endforeach
                </select>
            </div>
        </div>
        @if (count($addons))
        <div class="form-group">
            <label>@lang('bms::lang.addons_label')</label>
            <div class="row">
                @foreach ($addons as $a)
                    <div class="col-sm-4"><label style="font-weight:normal;"><input type="checkbox" name="addons[]" value="{{ $a->id }}" data-price="{{ $a->price }}"> {{ $a->name }} <small class="text-muted">({{ number_format($a->price) }})</small></label></div>
                @endforeach
            </div>
        </div>
        @endif

        {{-- Package customization: keep / swap / substitute items (staff funnel parity) --}}
        <div id="bms-customize" class="form-group" style="display:none; border-top:1px dashed #ddd; padding-top:12px;">
            <label style="display:block;">@lang('bms::lang.customize_package')</label>
            <p class="help-block" style="margin-top:0;">@lang('bms::lang.customize_pkg_hint')</p>
            <div id="bms-items"></div>
        </div>
        <input type="hidden" name="package_items" id="bms-pkg-items" value="">

        <div class="bms-est" style="margin:12px 0; font-size:1.05rem;">
            <span class="text-muted">@lang('bms::lang.estimated_total'):</span>
            <strong id="bms-estimate" class="display_currency" data-currency_symbol="true">0</strong>
            <small id="bms-cust-total" class="text-muted" style="margin-inline-start:10px;"></small>
        </div>

        <button type="submit" class="tw-dw-btn tw-dw-btn-primary tw-text-white"><i class="fa fa-plus"></i> @lang('bms::lang.create_booking_btn')</button>
        <p class="help-block" style="margin-top:8px;">@lang('bms::lang.new_booking_help')</p>
    @endcomponent
    {!! Form::close() !!}
</section>

@push('scripts')
<script>
$(function () {
    // Show only packages available for the chosen hall.
    function filterPackages() {
        var hid = $('#hall_id').val();
        $('#package_id option').each(function () {
            var halls = ($(this).data('halls') || '').toString().split(',');
            var show = !$(this).val() || !hid || halls.indexOf(hid) !== -1;
            $(this).prop('disabled', !show).toggle(show);
        });
        if ($('#package_id option:selected').prop('disabled')) { $('#package_id').val(''); loadItems(); }
    }
    $('#hall_id').on('change', filterPackages);
    filterPackages();

    // ---- Package customization: keep / variant-swap / buffet-substitute ----
    var PKG_ITEMS_URL = "{{ url('bms/bookings/package-items') }}";
    var LOC = "{{ app()->getLocale() }}";
    var T = {
        swap: @json(__('bms::lang.swap_for')), keep: @json(__('bms::lang.keep_as_is')),
        replace: @json(__('bms::lang.replace_qty')), each: @json(__('bms::lang.each_unit')),
        optional: @json(__('bms::lang.optional')), cust: @json(__('bms::lang.customizations')),
    };
    var itemsData = [], cfg = {}, variant = {}, cswap = {}, cqty = {};

    function loc(en, ar) { return (LOC === 'ar' && ar) ? ar : (en || ''); }
    function money(n) { n = Math.round((n + Number.EPSILON) * 100) / 100; return (n < 0 ? '-' : '') + Math.abs(n).toLocaleString(); }

    function loadItems() {
        var pid = $('#package_id').val();
        if (!pid) { itemsData = []; $('#bms-customize').hide(); $('#bms-items').empty(); $('#bms-pkg-items').val(''); estimate(); return; }
        $.get(PKG_ITEMS_URL + '/' + pid, function (r) {
            itemsData = (r && r.items) || [];
            cfg = {}; variant = {}; cswap = {}; cqty = {};
            itemsData.forEach(function (it) { cfg[it.id] = { on: !it.is_addon, qty: it.quantity }; });
            renderItems();
            $('#bms-customize').toggle(itemsData.length > 0);
        });
    }

    function renderItems() {
        var $c = $('#bms-items').empty();
        itemsData.forEach(function (it) {
            var $li = $('<div style="padding:7px 0;border-bottom:1px dashed #eee;"></div>');
            var head = '<label style="font-weight:600;margin:0;">';
            if (it.is_addon) { head += '<input type="checkbox" class="bms-it-on" data-id="' + it.id + '"' + (cfg[it.id].on ? ' checked' : '') + '> '; }
            head += $('<span>').text(loc(it.name, it.name_ar)).html();
            if (it.is_addon && it.price) { head += ' <small class="text-muted">(+' + money(it.price) + ')</small>'; }
            else if (it.is_addon) { head += ' <small class="text-muted">' + T.optional + '</small>'; }
            head += '</label>';
            $li.append(head);

            if (it.options && it.options.length) {
                var v = '<div style="margin:4px 0;"><span class="text-muted">' + T.swap + ': </span><select class="bms-it-variant input-sm" data-id="' + it.id + '" style="width:auto;">';
                v += '<option value="0">' + $('<span>').text(loc(it.name, it.name_ar)).html() + '</option>';
                it.options.forEach(function (o, i) { v += '<option value="' + (i + 1) + '">' + $('<span>').text(loc(o.label, o.label_ar)).html() + ' (' + (o.price_delta > 0 ? '+' : '') + money(o.price_delta) + ')</option>'; });
                v += '</select></div>';
                $li.append(v);
            }

            if (it.contents && it.contents.length) {
                var $ul = $('<div style="margin-inline-start:14px;font-size:.92em;"></div>');
                it.contents.forEach(function (c, ci) {
                    var nm = $('<span>').text(loc(c.name, c.name_ar)).html();
                    if (!c.swap_options || !c.swap_options.length) {
                        $ul.append('<div class="text-muted" style="padding:2px 0;">• ' + nm + ' ×' + c.quantity + '</div>');
                        return;
                    }
                    var row = '<div style="padding:2px 0;">• ' + nm + ' ';
                    row += '<select class="bms-c-swap input-sm" data-id="' + it.id + '" data-ci="' + ci + '" style="width:auto;">';
                    row += '<option value="0">' + T.keep + '</option>';
                    c.swap_options.forEach(function (so, si) {
                        row += '<option value="' + (si + 1) + '">' + T.swap + ' ' + $('<span>').text(loc(so.name, so.name_ar)).html()
                            + (so.price_delta ? ' (' + (so.price_delta > 0 ? '+' : '') + money(so.price_delta) + (c.quantity > 1 ? ' ' + T.each : '') + ')' : '') + '</option>';
                    });
                    row += '</select> <span class="bms-c-qtywrap" data-id="' + it.id + '" data-ci="' + ci + '"></span></div>';
                    $ul.append(row);
                });
                $li.append($ul);
            }
            $c.append($li);
        });
        serialize();
    }

    $(document).on('change', '#package_id', loadItems);
    $(document).on('change', '.bms-it-on', function () { cfg[$(this).data('id')].on = this.checked; serialize(); });
    $(document).on('change', '.bms-it-variant', function () { variant[$(this).data('id')] = Number(this.value) || 0; serialize(); });
    $(document).on('change', '.bms-c-swap', function () {
        var id = $(this).data('id'), ci = $(this).data('ci'), v = Number(this.value) || 0;
        cswap[id] = cswap[id] || {}; cswap[id][ci] = v;
        var it = itemsData.filter(function (x) { return x.id == id; })[0];
        var c = it.contents[ci];
        var $wrap = $('.bms-c-qtywrap[data-id="' + id + '"][data-ci="' + ci + '"]');
        if (v > 0 && c.quantity > 1) {
            cqty[id] = cqty[id] || {}; cqty[id][ci] = c.quantity;
            $wrap.html(T.replace + ': <input type="number" class="bms-c-qty input-sm" data-id="' + id + '" data-ci="' + ci + '" min="1" max="' + c.quantity + '" value="' + c.quantity + '" style="width:60px;"> / ' + c.quantity);
        } else { if (cqty[id]) { delete cqty[id][ci]; } $wrap.empty(); }
        serialize();
    });
    $(document).on('input', '.bms-c-qty', function () {
        var id = $(this).data('id'), ci = $(this).data('ci');
        var max = Number($(this).attr('max')) || 1;
        var val = Math.max(1, Math.min(max, Number(this.value) || 1));
        cqty[id] = cqty[id] || {}; cqty[id][ci] = val; serialize();
    });
    $(document).on('change', '#attendees, input[name="addons[]"]', serialize);

    function serialize() {
        var out = [], delta = 0;
        var guests = Number($('#attendees').val()) || 0;
        itemsData.forEach(function (it) {
            var on = it.is_addon ? !!(cfg[it.id] && cfg[it.id].on) : true;
            var vi = variant[it.id] || 0;
            var vdelta = (vi > 0 && it.options && it.options[vi - 1]) ? (it.options[vi - 1].price_delta || 0) : 0;
            var swaps = [], cs = cswap[it.id] || {};
            Object.keys(cs).forEach(function (ci) {
                var ti = cs[ci]; if (!ti) { return; }
                var c = it.contents[ci], o = c.swap_options[ti - 1];
                var q = (cqty[it.id] && cqty[it.id][ci]) ? cqty[it.id][ci] : c.quantity;
                swaps.push({ index: Number(ci), to_index: ti, from: loc(c.name, c.name_ar), to: loc(o.name, o.name_ar), qty: q, of: c.quantity, delta: o.price_delta || 0 });
            });
            if (on) {
                if (it.is_addon && it.price) { delta += it.price * (it.qty_mode === 'per_guest' ? guests : ((cfg[it.id] && cfg[it.id].qty) || 1)); }
                delta += vdelta;
                swaps.forEach(function (s) { delta += (s.delta || 0) * (s.qty || 0); });
            }
            out.push({ item_id: it.id, qty: (cfg[it.id] && cfg[it.id].qty) || it.quantity, included: on, variant_index: vi, variant_delta: vdelta, content_swaps: swaps });
        });
        $('#bms-pkg-items').val(JSON.stringify(out));
        $('#bms-cust-total').text(itemsData.length ? (T.cust + ': ' + (delta >= 0 ? '+' : '') + money(delta)) : '');
        estimate(delta);
    }

    function estimate(custDelta) {
        if (custDelta === undefined) { custDelta = 0; }
        var base = Number($('#package_id option:selected').data('price')) || 0;
        var addons = 0;
        $('input[name="addons[]"]:checked').each(function () { addons += Number($(this).data('price')) || 0; });
        var total = base + addons + custDelta;
        var $e = $('#bms-estimate').text(money(total));
        if (window.__currency_v_general && typeof __currency_v_general === 'function') { __currency_v_general(); }
    }
    estimate();
});
</script>
@endpush
@endsection
