{include file="_partials/head.tpl"}

<div class="page-head">
  <div>
    <h1>{lang key="shop.order_create.title"}</h1>
    <p class="muted"><a href="/admin/shop/orders">{lang key="shop.order.back_to_list"}</a></p>
  </div>
</div>

<form method="post" action="/admin/shop/orders/create" class="form" data-order-form>
  {csrf}

  <div class="order-create-grid">
    <div class="oc-col-main">
      <div class="card">
        <div class="card-h"><h3>{lang key="shop.order_create.customer_section"}</h3></div>

        <div class="form-group">
          <label>{lang key="shop.order_create.search_customer"}</label>
          <div class="autocomplete" data-cust-ac>
            <input type="text" placeholder="{lang key="shop.order_create.search_customer_placeholder"}" data-cust-input autocomplete="off">
            <div class="autocomplete-list" data-cust-list hidden></div>
          </div>
          <small class="help">{lang key="shop.order_create.customer_help"}</small>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label>{lang key="shop.order.name"} <span class="req">*</span></label>
            <input type="text" name="customer_name" required data-cust-name>
          </div>
          <div class="form-group">
            <label>{lang key="shop.order.email"} <span class="req">*</span></label>
            <input type="email" name="customer_email" required data-cust-email>
          </div>
          <div class="form-group">
            <label>{lang key="shop.order.phone"}</label>
            <input type="text" name="customer_phone" data-cust-phone>
          </div>
        </div>
        <div class="form-group">
          <label>{lang key="shop.order.address"}</label>
          <textarea name="customer_address" rows="2" data-cust-addr></textarea>
        </div>
      </div>

      <div class="card">
        <div class="card-h"><h3>{lang key="shop.order_create.items_section"}</h3></div>

        <div class="form-group">
          <label>{lang key="shop.order_create.search_product"}</label>
          <div class="autocomplete" data-prod-ac>
            <input type="text" placeholder="{lang key="shop.order_create.search_product_placeholder"}" data-prod-input autocomplete="off">
            <div class="autocomplete-list" data-prod-list hidden></div>
          </div>
        </div>

        <table class="table table-order-items" data-items-table>
          <thead>
            <tr>
              <th>{lang key="shop.order.col.product"}</th>
              <th>SKU</th>
              <th>{lang key="shop.order.col.price"}</th>
              <th>{lang key="shop.order.col.quantity"}</th>
              <th>{lang key="shop.order.col.subtotal"}</th>
              <th></th>
            </tr>
          </thead>
          <tbody data-items-body>
            <tr data-empty-row><td colspan="6" class="muted text-center">{lang key="shop.order_create.empty_items"}</td></tr>
          </tbody>
        </table>

        <button type="button" class="btn btn-secondary btn-sm" data-add-blank>
          {icon name="plus" size="14"} {lang key="shop.order_create.add_blank"}
        </button>
      </div>
    </div>

    <aside class="oc-col-side">
      <div class="card">
        <div class="card-h"><h3>{lang key="shop.order_create.summary"}</h3></div>
        <div class="order-totals">
          <div class="ot-row"><span>{lang key="shop.order.totals.subtotal"}</span><span data-sum-subtotal>0</span></div>
          <div class="form-group">
            <label>{lang key="shop.order_create.shipping"}</label>
            <select name="shipping_method_id" data-ship-select>
              <option value="0">{lang key="shop.common.not_set"}</option>
              [foreach var="shipping_methods" as="m"]
                <option value="{m.id}" data-cost="{m.cost}">{m.title}</option>
              [/foreach]
            </select>
            <input type="number" step="0.01" name="shipping_cost" value="0" data-ship-cost class="mt-4">
          </div>
          <div class="form-group">
            <label>{lang key="shop.order_create.discount"}</label>
            <input type="number" step="0.01" name="discount" value="0" data-discount>
          </div>
          <div class="form-group">
            <label>{lang key="shop.order_create.tax"}</label>
            <input type="number" step="0.01" name="tax" value="0" data-tax>
          </div>
          <div class="ot-row ot-total"><span>{lang key="shop.order.totals.total"}</span><span data-sum-total>0</span></div>
        </div>
      </div>

      <div class="card">
        <div class="card-h"><h3>{lang key="shop.order_create.payment"}</h3></div>
        <div class="form-group">
          <label>{lang key="shop.order.payment_method"}</label>
          <select name="payment_method_id">
            <option value="0">{lang key="shop.common.not_set"}</option>
            [foreach var="payment_methods" as="m"]
              <option value="{m.id}">{m.title}</option>
            [/foreach]
          </select>
        </div>
        <div class="form-group">
          <label>{lang key="shop.order_create.payment_status_label"}</label>
          <select name="payment_status">
            [foreach var="payment_options" as="ps"]
              <option value="{ps.code}">{ps.label}</option>
            [/foreach]
          </select>
        </div>
      </div>

      <div class="card">
        <div class="card-h"><h3>{lang key="shop.order_create.order_status_label"}</h3></div>
        <div class="form-group">
          <select name="status">
            [foreach var="status_options" as="s"]
              <option value="{s.code}" [if {s.code}="new"]selected[/if]>{s.label}</option>
            [/foreach]
          </select>
        </div>
        <div class="form-group">
          <label>{lang key="shop.order_create.client_comment"}</label>
          <textarea name="comment" rows="2"></textarea>
        </div>
        <div class="form-group">
          <label>{lang key="shop.order.admin_note"}</label>
          <textarea name="admin_note" rows="2"></textarea>
        </div>
      </div>

      <div class="form-actions">
        <button type="submit" class="btn btn-primary btn-block">{icon name="check" size="14"} {lang key="shop.order_create.submit"}</button>
        <a href="/admin/shop/orders" class="btn btn-secondary btn-block">{lang key="shop.common.cancel"}</a>
      </div>
    </aside>
  </div>
</form>

<script>
(function () {
  var form = document.querySelector('[data-order-form]');
  if (!form) return;

  var itemsBody  = form.querySelector('[data-items-body]');
  var emptyRow   = form.querySelector('[data-empty-row]');
  var prodInput  = form.querySelector('[data-prod-input]');
  var prodList   = form.querySelector('[data-prod-list]');
  var custInput  = form.querySelector('[data-cust-input]');
  var custList   = form.querySelector('[data-cust-list]');
  var shipSel    = form.querySelector('[data-ship-select]');
  var shipCost   = form.querySelector('[data-ship-cost]');
  var discount   = form.querySelector('[data-discount]');
  var tax        = form.querySelector('[data-tax]');
  var sumSub     = form.querySelector('[data-sum-subtotal]');
  var sumTotal   = form.querySelector('[data-sum-total]');
  var addBlank   = form.querySelector('[data-add-blank]');

  function fmt(n) { return (Math.round(n * 100) / 100).toLocaleString('ru-RU', { maximumFractionDigits: 2 }); }

  function recalc() {
    var sub = 0;
    itemsBody.querySelectorAll('tr[data-row]').forEach(function (tr) {
      var price = parseFloat(tr.querySelector('[data-i-price]').value) || 0;
      var qty   = parseInt(tr.querySelector('[data-i-qty]').value, 10) || 0;
      var s = price * qty;
      tr.querySelector('[data-i-sum]').textContent = fmt(s);
      sub += s;
    });
    sumSub.textContent = fmt(sub);
    var sc = parseFloat(shipCost.value) || 0;
    var dc = parseFloat(discount.value) || 0;
    var tx = parseFloat(tax.value) || 0;
    sumTotal.textContent = fmt(Math.max(0, sub + sc + tx - dc));
    if (emptyRow) emptyRow.style.display = itemsBody.querySelectorAll('tr[data-row]').length === 0 ? '' : 'none';
  }

  function addItem(p) {
    var pid = p && p.id ? p.id : 0;
    var title = p && p.title ? p.title : '';
    var sku = p && p.sku ? p.sku : '';
    var price = p && p.price ? p.price : 0;

    var tr = document.createElement('tr');
    tr.setAttribute('data-row', '');
    tr.innerHTML =
      '<td><input type="hidden" name="item[product_id][]" value="' + pid + '">' +
        '<input type="text" name="item[title][]" value="' + escapeAttr(title) + '" required></td>' +
      '<td><input type="text" name="item[sku][]" value="' + escapeAttr(sku) + '" style="width:100px"></td>' +
      '<td><input type="number" step="0.01" name="item[price][]" value="' + price + '" data-i-price required style="width:100px"></td>' +
      '<td><input type="number" name="item[quantity][]" value="1" min="1" data-i-qty style="width:70px"></td>' +
      '<td><b data-i-sum>0</b></td>' +
      '<td><button type="button" class="btn btn-link btn-sm" data-i-del aria-label="Удалить">' +
        '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>' +
      '</button></td>';
    tr.querySelector('[data-i-del]').addEventListener('click', function () { tr.remove(); recalc(); });
    tr.querySelector('[data-i-price]').addEventListener('input', recalc);
    tr.querySelector('[data-i-qty]').addEventListener('input', recalc);
    itemsBody.appendChild(tr);
    recalc();
  }
  function escapeAttr(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;'); }

  addBlank.addEventListener('click', function () { addItem({}); });

  shipSel.addEventListener('change', function () {
    var opt = shipSel.options[shipSel.selectedIndex];
    var cost = opt ? parseFloat(opt.getAttribute('data-cost')) : 0;
    if (!isNaN(cost)) shipCost.value = cost;
    recalc();
  });
  shipCost.addEventListener('input', recalc);
  discount.addEventListener('input', recalc);
  tax.addEventListener('input', recalc);

  // Автокомплит товаров
  setupAutocomplete(prodInput, prodList, '/admin/shop/orders/search-products', function (item) {
    return '<div class="ac-item-title">' + escapeHtml(item.title) + '</div>' +
           '<div class="ac-item-meta muted">' +
            (item.sku ? 'SKU ' + escapeHtml(item.sku) + ' · ' : '') +
            'Остаток: ' + item.stock + ' · ' + fmt(item.price) +
           '</div>';
  }, function (item) {
    addItem(item);
    prodInput.value = '';
  });

  // Автокомплит клиентов
  setupAutocomplete(custInput, custList, '/admin/shop/orders/search-customers', function (item) {
    return '<div class="ac-item-title">' + escapeHtml(item.name || item.email) + '</div>' +
           '<div class="ac-item-meta muted">' + escapeHtml(item.email) +
            (item.phone ? ' · ' + escapeHtml(item.phone) : '') +
            ' · заказов: ' + item.orders_count + '</div>';
  }, function (item) {
    form.querySelector('[data-cust-name]').value  = item.name || '';
    form.querySelector('[data-cust-email]').value = item.email || '';
    form.querySelector('[data-cust-phone]').value = item.phone || '';
    form.querySelector('[data-cust-addr]').value  = item.address || '';
    custInput.value = item.name + ' (' + item.email + ')';
  });

  function setupAutocomplete(input, list, url, render, onPick) {
    var timer = null;
    input.addEventListener('input', function () {
      clearTimeout(timer);
      var q = input.value.trim();
      if (q.length < 2) { list.hidden = true; list.innerHTML = ''; return; }
      timer = setTimeout(function () {
        fetch(url + '?q=' + encodeURIComponent(q), { credentials: 'same-origin' })
          .then(function (r) { return r.json(); })
          .then(function (data) {
            list.innerHTML = '';
            (data.items || []).forEach(function (it) {
              var div = document.createElement('div');
              div.className = 'autocomplete-item';
              div.innerHTML = render(it);
              div.addEventListener('click', function () { onPick(it); list.hidden = true; });
              list.appendChild(div);
            });
            list.hidden = list.children.length === 0;
          })
          .catch(function () { list.hidden = true; });
      }, 200);
    });
    document.addEventListener('click', function (e) {
      if (!input.parentElement.contains(e.target)) list.hidden = true;
    });
  }
  function escapeHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  }

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

{include file="_partials/foot.tpl"}
