@php
  $selectedHalls = isset($package) ? $package->halls->pluck('id')->all() : [];
  $allItems   = isset($package) ? $package->items : collect();
  $inclusions = $allItems->where('is_addon', false)->values();
  $addonItems = $allItems->where('is_addon', true)->values();
  $totalHalls = count($halls);
  $allHalls   = isset($package) ? ($totalHalls > 0 && count($selectedHalls) >= $totalHalls) : true;
@endphp
<div class="bms-package-form">
<div class="row">
  <div class="col-md-6">
    <div class="form-group">
      {!! Form::label('name', __('bms::lang.package') . ':*') !!}
      {!! Form::text('name', null, ['class' => 'form-control', 'required']) !!}
    </div>
  </div>
  <div class="col-md-6">
    <div class="form-group">
      {!! Form::label('name_ar', __('bms::lang.package') . ' (AR):') !!}
      {!! Form::text('name_ar', null, ['class' => 'form-control', 'dir' => 'rtl']) !!}
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-6">
    <div class="form-group">
      {!! Form::label('hall_ids', __('bms::lang.halls') . ':') !!}
      <label class="tw-font-normal" style="display:block;margin-bottom:6px">
        <input type="checkbox" name="all_halls" value="1" class="bms-all-halls" {{ $allHalls ? 'checked' : '' }}>
        @lang('bms::lang.all_halls_label')
      </label>
      <div class="bms-hall-pick" style="{{ $allHalls ? 'display:none' : '' }}">
        {!! Form::select('hall_ids[]', $halls, $selectedHalls, ['class' => 'form-control bms-select2', 'multiple', 'placeholder' => __('bms::lang.halls')]) !!}
        <p class="help-block">@lang('bms::lang.package_halls_help')</p>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="form-group">
      {!! Form::label('fnb_level', __('bms::lang.fnb_level') . ':') !!}
      {!! Form::select('fnb_level', $fnbLevels, null, ['class' => 'form-control', 'placeholder' => __('messages.please_select')]) !!}
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-4">
    <div class="form-group">
      {!! Form::label('price', __('bms::lang.price') . ':*') !!}
      {!! Form::number('price', null, ['class' => 'form-control', 'required', 'min' => 0, 'step' => '0.01']) !!}
      <label class="tw-font-normal tw-mt-1">
        {!! Form::checkbox('price_per_person', 1, isset($package) ? null : false, ['class' => 'input-icheck']) !!}
        @lang('bms::lang.price') / @lang('bms::lang.attendees')
      </label>
    </div>
  </div>
  <div class="col-md-3">
    <div class="form-group">
      {!! Form::label('min_pax', __('bms::lang.attendees') . ' (min):') !!}
      {!! Form::number('min_pax', null, ['class' => 'form-control', 'min' => 0]) !!}
    </div>
  </div>
  <div class="col-md-3">
    <div class="form-group">
      {!! Form::label('max_pax', __('bms::lang.attendees') . ' (max):') !!}
      {!! Form::number('max_pax', null, ['class' => 'form-control', 'min' => 0]) !!}
    </div>
  </div>
  <div class="col-md-2">
    <div class="form-group">
      <label class="tw-mt-7">
        {!! Form::checkbox('is_active', 1, isset($package) ? null : true, ['class' => 'input-icheck']) !!}
        @lang('bms::lang.active')
      </label>
    </div>
  </div>
</div>

<hr>
<h5 class="tw-font-semibold"><i class="fa fas fa-list-ul"></i> @lang('bms::lang.package_items')</h5>
<p class="help-block">@lang('bms::lang.package_items_help')</p>
<table class="table table-condensed table-bordered">
  <thead>
    <tr>
      <th>@lang('bms::lang.item')</th>
      <th>@lang('bms::lang.quantity')</th>
      <th>@lang('bms::lang.qty_mode')</th>
      <th>@lang('bms::lang.unit_cost')</th>
      <th></th>
    </tr>
  </thead>
  <tbody id="bms-items">
    @foreach($inclusions as $i => $item)
      @include('bms::packages._item_row', ['idx' => $i, 'item' => $item])
    @endforeach
  </tbody>
</table>
<button type="button" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-primary" id="bms-add-item">
  <i class="fa fas fa-plus"></i> @lang('bms::lang.add_item')
</button>

<div class="well well-sm" style="margin-top:12px">
  <div class="row">
    <div class="col-xs-6">
      <strong>@lang('bms::lang.estimated_cost')</strong>
      <span class="display_currency" data-currency_symbol="true" id="bms-cost-total">0</span>
      <small class="text-muted">(@lang('bms::lang.at') <span id="bms-cost-guests">—</span> @lang('bms::lang.attendees'))</small>
    </div>
    <div class="col-xs-6 text-right">
      <strong>@lang('bms::lang.est_margin')</strong>
      <i class="fa fas fa-info-circle text-muted" title="@lang('bms::lang.margin_help')"></i>
      <span class="display_currency" data-currency_symbol="true" id="bms-margin">0</span>
    </div>
  </div>
</div>

<hr>
<h5 class="tw-font-semibold"><i class="fa fas fa-plus-circle"></i> @lang('bms::lang.addons')</h5>
<p class="help-block">@lang('bms::lang.addons_help')</p>
<table class="table table-condensed table-bordered">
  <thead>
    <tr>
      <th>@lang('bms::lang.addon')</th>
      <th>@lang('bms::lang.qty_mode')</th>
      <th>@lang('bms::lang.quantity')</th>
      <th>@lang('bms::lang.addon_price')</th>
      <th></th>
    </tr>
  </thead>
  <tbody id="bms-addons">
    @foreach($addonItems as $i => $item)
      @include('bms::packages._addon_row', ['idx' => $i, 'item' => $item])
    @endforeach
  </tbody>
</table>
<button type="button" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-primary" id="bms-add-addon">
  <i class="fa fas fa-plus"></i> @lang('bms::lang.add_addon')
</button>

<div class="row" style="margin-top:14px">
  <div class="col-md-6">
    <div class="form-group">
      {!! Form::label('description', __('bms::lang.description') . ' (EN):') !!}
      {!! Form::textarea('description', null, ['class' => 'form-control', 'rows' => 2]) !!}
    </div>
  </div>
  <div class="col-md-6">
    <div class="form-group">
      {!! Form::label('description_ar', __('bms::lang.description') . ' (AR):') !!}
      {!! Form::textarea('description_ar', null, ['class' => 'form-control', 'rows' => 2, 'dir' => 'rtl']) !!}
    </div>
  </div>
</div>

{{-- JS templates for new rows --}}
<template id="bms-item-tpl">
  @include('bms::packages._item_row', ['idx' => '__IDX__', 'item' => null])
</template>
<template id="bms-addon-tpl">
  @include('bms::packages._addon_row', ['idx' => '__IDX__', 'item' => null])
</template>
</div>

<script>
(function () {
  var $form = $('.bms-package-form').last();
  if (!$form.length) return;
  var $modal = $form.closest('.modal');
  var searchUrl = @json($productSearchUrl);
  var previewUrl = @json($productPreviewUrl ?? '');
  var nextItem = {{ $inclusions->count() }};
  var nextAddon = {{ $addonItems->count() }};

  // Labels for the read-only "inherited from product" preview.
  var PVL = {
    name: @json(__('bms::lang.pv_name')), desc: @json(__('bms::lang.pv_description')),
    media: @json(__('bms::lang.pv_media')), variants: @json(__('bms::lang.pv_variants')),
    contents: @json(__('bms::lang.pv_contents')), none: @json(__('bms::lang.pv_none'))
  };

  function guests() { return parseFloat($form.find('[name=min_pax]').val()) || 100; }

  function pvEsc(s) { return $('<div>').text(s == null ? '' : s).html(); }
  function pvDelta(n) { n = parseFloat(n) || 0; return (n > 0 ? '+' : '') + n.toLocaleString(); }

  // Render the inherited-from-product summary into a row's materials panel.
  function renderPreview($panel, p) {
    var $wrap = $panel.find('.bms-inherit-preview'), $body = $panel.find('.bms-inherit-body');
    if (!$wrap.length) return;
    if (!p) { $wrap.hide(); $body.empty(); return; }
    var rows = [];
    var nm = [p.name, p.name_ar].filter(Boolean).map(pvEsc).join(' / ');
    if (nm) rows.push('<div><b>' + PVL.name + ':</b> ' + nm + '</div>');
    var d = [p.description, p.description_ar].filter(Boolean)
      .map(function (x) { return pvEsc(x.length > 90 ? x.slice(0, 90) + '…' : x); }).join(' / ');
    if (d) rows.push('<div><b>' + PVL.desc + ':</b> ' + d + '</div>');
    if (p.media && p.media.length) {
      var t = {}; p.media.forEach(function (m) { t[m.type] = (t[m.type] || 0) + 1; });
      var badges = Object.keys(t).map(function (k) { return pvEsc(k) + '×' + t[k]; }).join(', ');
      rows.push('<div><b>' + PVL.media + ':</b> ' + p.media.length + ' (' + badges + ')</div>');
    }
    if (p.variants && p.variants.length) {
      var vs = p.variants.map(function (v) {
        return pvEsc(v.label_ar || v.label || '') + (v.price_delta ? ' (' + pvDelta(v.price_delta) + ')' : '');
      }).join(', ');
      rows.push('<div><b>' + PVL.variants + ':</b> ' + vs + '</div>');
    }
    if (p.contents && p.contents.length) {
      var cs = p.contents.map(function (c) { return pvEsc(c.name_ar || c.name || '') + ' ×' + (c.quantity || 1); }).join(', ');
      rows.push('<div><b>' + PVL.contents + ':</b> ' + cs + '</div>');
    }
    $body.html(rows.length ? rows.join('') : ('<span class="text-muted">' + PVL.none + '</span>'));
    $wrap.show();
  }

  function loadPreview($row, productId) {
    var $panel = $row.next('.bms-row-details-panel');
    if (!$panel.length || !previewUrl) return;
    if (!productId) { renderPreview($panel, null); return; }
    $.get(previewUrl.replace('__ID__', productId), function (r) { renderPreview($panel, r && r.preview); })
      .fail(function () { renderPreview($panel, null); });
  }

  function initAjaxSelect($selects) {
    $selects.each(function () {
      if ($(this).data('select2')) return;
      try {
        $(this).select2({
          dropdownParent: $modal.length ? $modal : $(document.body),
          width: '100%',
          placeholder: $(this).data('placeholder') || '',
          allowClear: true,
          minimumInputLength: 1,
          ajax: {
            url: searchUrl, dataType: 'json', delay: 250,
            data: function (params) { return { q: params.term }; },
            processResults: function (data) { return { results: data.results || [] }; },
            cache: true
          }
        });
      } catch (e) {}
    });
  }

  // Show the per-guest effective quantity inline so "1 per guest" reads as the real total.
  function effLabel($row, qtySel, modeSel, effSel) {
    var qty = parseFloat($row.find(qtySel).val()) || 0;
    var perGuest = $row.find(modeSel).val() === 'per_guest';
    var txt = perGuest ? ('= ' + (qty * guests()) + ' (' + guests() + ' ' + @json(__('bms::lang.attendees')) + ')') : '';
    $row.find(effSel).text(txt);
  }

  function recalc() {
    var g = guests();
    $form.find('#bms-cost-guests').text(g);
    var total = 0;
    $form.find('.bms-item-row').each(function () {
      var $r = $(this);
      var qty = parseFloat($r.find('.bms-item-qty').val()) || 0;
      var cost = parseFloat($r.find('.bms-item-cost').val()) || 0;
      var perGuest = $r.find('.bms-item-mode').val() === 'per_guest';
      total += qty * cost * (perGuest ? g : 1);
      effLabel($r, '.bms-item-qty', '.bms-item-mode', '.bms-item-eff');
    });
    $form.find('.bms-addon-row').each(function () {
      effLabel($(this), '.bms-addon-qty', '.bms-addon-mode', '.bms-addon-eff');
    });
    $form.find('#bms-cost-total').text(total.toFixed(2));
    var price = parseFloat($form.find('[name=price]').val()) || 0;
    var revenue = $form.find('[name=price_per_person]').is(':checked') ? price * g : price;
    $form.find('#bms-margin').text((revenue - total).toFixed(2)).css('color', (revenue - total) < 0 ? '#c0392b' : '');
    if (typeof __currency_recalculate === 'function') { try { __currency_recalculate(); } catch (e) {} }
  }

  // "All halls" toggles the hall picker.
  $form.on('change', '.bms-all-halls', function () {
    $form.find('.bms-hall-pick').toggle(!this.checked);
  });

  // Add / remove inclusion rows.
  $form.on('click', '#bms-add-item', function () {
    var $row = $($('#bms-item-tpl').html().replace(/__IDX__/g, 'i' + (nextItem++)));
    $form.find('#bms-items').append($row);
    initAjaxSelect($row.find('.bms-item-product'));
    recalc();
  });
  $form.on('click', '.bms-item-del', function () { $(this).closest('.bms-item-row').remove(); recalc(); });

  // Add / remove add-on rows.
  $form.on('click', '#bms-add-addon', function () {
    var $row = $($('#bms-addon-tpl').html().replace(/__IDX__/g, 'a' + (nextAddon++)));
    $form.find('#bms-addons').append($row);
    initAjaxSelect($row.find('.bms-addon-product'));
    recalc();
  });
  $form.on('click', '.bms-addon-del', function () { $(this).closest('.bms-addon-row').remove(); recalc(); });

  // Toggle the per-row materials (description + media) editor.
  $form.on('click', '.bms-row-details', function () {
    $(this).closest('tr').next('.bms-row-details-panel').toggle();
  });

  // Inclusion product → fill unit cost + label + inherited preview.
  $form.on('select2:select', '.bms-item-product', function (e) {
    var d = (e.params && e.params.data) || {};
    var $row = $(this).closest('.bms-item-row');
    var $cost = $row.find('.bms-item-cost');
    if (d.cost !== undefined && !parseFloat($cost.val())) { $cost.val(d.cost); }
    var $name = $row.find('.bms-item-name');
    if (d.text && !$name.val()) { $name.val(d.text); }
    loadPreview($row, d.id);
    recalc();
  });

  // Add-on product → fill sale price + cost + label + inherited preview.
  $form.on('select2:select', '.bms-addon-product', function (e) {
    var d = (e.params && e.params.data) || {};
    var $row = $(this).closest('.bms-addon-row');
    var $price = $row.find('.bms-addon-price');
    if (d.sell !== undefined && d.sell > 0 && !parseFloat($price.val())) { $price.val(d.sell); }
    if (d.cost !== undefined) { $row.find('.bms-addon-cost').val(d.cost); }
    var $name = $row.find('.bms-addon-name');
    if (d.text && !$name.val()) { $name.val(d.text); }
    loadPreview($row, d.id);
    recalc();
  });

  // Clearing the product hides the inherited preview.
  $form.on('select2:clear select2:unselect', '.bms-item-product, .bms-addon-product', function () {
    loadPreview($(this).closest('tr'), null);
  });

  $form.on('input change',
    '.bms-item-qty, .bms-item-cost, .bms-item-mode, .bms-addon-qty, .bms-addon-mode, [name=min_pax], [name=price], [name=price_per_person]',
    recalc);

  initAjaxSelect($form.find('.bms-item-product, .bms-addon-product'));

  // Existing rows: show what each already-linked product contributes.
  $form.find('.bms-item-product, .bms-addon-product').each(function () {
    var pid = $(this).val();
    if (pid) { loadPreview($(this).closest('tr'), pid); }
  });

  recalc();
})();
</script>
