{{-- resources/views/sales/create.blade.php --}}
@extends('layouts.app')

@section('content')
<div class="container-fluid">
  <div class="page">

    {{-- Header --}}
    <div class="hd">
      <div class="hd-left"><i class="fas fa-cog me-2"></i>Create Sale</div>
      <a href="{{ route('sales.index') }}" class="hd-link"><i class="fas fa-list me-2"></i>Sale List</a>
    </div>

    <form id="saleForm" method="POST" action="{{ route('sales.store') }}" autocomplete="off">
      @csrf

      {{-- ===== Top paired fields ===== --}}
      <div class="top">
        <div class="grid2">
          <div class="pair">
            <div class="lab">Company</div>
            <select name="company_id" class="inp">
              <option>-Select Company-</option>
              @foreach($companies ?? [] as $c)
                <option value="{{ $c->id }}">{{ $c->name }}</option>
              @endforeach
            </select>
          </div>

          <div class="pair">
            <div class="lab">Customer</div>
            <select name="customer_id" class="inp">
              <option>-Select Customer-</option>
              @foreach($customers ?? [] as $c)
                <option value="{{ $c->id }}">{{ $c->name }}</option>
              @endforeach
            </select>
          </div>

          <div class="pair">
            <div class="lab">Employee</div>
            <select name="employee_id" class="inp">
              <option>-Employee Name-</option>
              @foreach($employees ?? [] as $e)
                <option value="{{ $e->id }}">{{ $e->name }}</option>
              @endforeach
            </select>
          </div>

          <div class="pair">
            <div class="lab">Date</div>
            <div class="ig">
              <input type="date" name="date" value="{{ date('Y-m-d') }}" class="inp ig-main">
              <span class="ig-ico"><i class="far fa-calendar"></i></span>
            </div>
          </div>

          <div class="pair">
            <div class="lab">Cus. Due</div>
            <input class="inp ro" readonly>
          </div>

          <div class="pair">
            <div class="lab">Reference</div>
            <input name="reference" class="inp" placeholder="Reference">
          </div>
        </div>
      </div>

      {{-- ===== Table (left) + Summary card (right) ===== --}}
      <div class="mid">
        <div class="row gx-2">

          {{-- LEFT: items --}}
          <div class="col-xl-8">
            <div class="table-responsive">
              <table class="table t" id="itemTable">
                <colgroup>
                  <col style="width:56px">
                  <col style="width:220px">
                  <col>
                  <col style="width:120px">
                  <col style="width:140px">
                  <col style="width:120px">
                  <col style="width:120px">
                  <col style="width:120px">
                  <col style="width:140px">
                  <col style="width:120px">
                  <col style="width:120px">
                  <col style="width:90px">
                </colgroup>

                <thead>
                  <tr>
                    <th>SL.</th>
                    <th>Warehouse</th>
                    <th>Product</th>
                    <th>Unit</th>
                    <th>Category</th>
                    <th>Avail. Qty</th>
                    <th>Qty</th>
                    <th>Adjust Kg</th>
                    <th>Total Kg</th>
                    <th>Unit Price</th>
                    <th>Subtotal</th>
                    <th></th>
                  </tr>
                </thead>

                <tbody id="rows">
                  <tr class="r">
                    <td class="tc sl">1</td>

                    <td>
                      <select name="items[0][warehouse_id]" class="inp">
                        <option>-Select Warehouse-</option>
                        @foreach($warehouses ?? [] as $w)
                          <option value="{{ $w->id }}">{{ $w->name }}</option>
                        @endforeach
                      </select>
                    </td>

                    <td>
                      <div class="prodwrap">
                        <select name="items[0][product_id]" class="inp prod">
                          <option>-select product-</option>
                          @foreach($products ?? [] as $p)
                            <option value="{{ $p->id }}"
                              data-unit="{{ $p->unit_name ?? '' }}"
                              data-cat="{{ $p->category->name ?? '' }}"
                              data-qty="{{ number_format($p->available_qty ?? 0, 2, '.', '') }}"
                              data-price="{{ number_format($p->price ?? 0, 2, '.', '') }}">
                              {{ $p->name }}
                            </option>
                          @endforeach
                        </select>
                        <button type="button" class="btn btn-sm info">i</button>
                      </div>
                    </td>

                    {{-- readonly placeholders --}}
                    <td><input class="inp ro unit ph"  name="items[0][unit]"       placeholder="Unit" readonly></td>
                    <td><input class="inp ro cat ph"   name="items[0][category]"   placeholder="Category" readonly></td>
                    <td><input class="inp ro avail ph" name="items[0][available]"  placeholder="Available Qty" readonly></td>

                    <td><input type="number" step="0.0" class="inp qty"  name="items[0][qty]"   placeholder="Qty"></td>
                    <td><input type="number" step="0.0" class="inp adj"  name="items[0][adjust]" value="0"></td>

                    <td><input class="inp ro tkg ph"  name="items[0][total_kg]" placeholder="Total Kg" readonly></td>
                    <td><input type="number" step="0.0" class="inp price ph" name="items[0][price]" placeholder="Unit Price"></td>
                    <td><input class="inp ro sub"  name="items[0][subtotal]" value="0.00" readonly></td>

                    <td class="te">
                      <div class="btnwrap">
                        <button type="button" class="btn minus"><i class="fas fa-minus"></i></button>
                        <button type="button" class="btn plus"><i class="fas fa-plus"></i></button>
                      </div>
                    </td>
                  </tr>

                  {{-- Total: label under Qty, value under Total Kg --}}
                  <tr class="trow">
                    <td colspan="6"></td>
                    <td class="tlabel">Total</td>
                    <td></td>
                    <td class="tval"><input id="tkgTotal" class="inp ro te" value="0.00" readonly></td>
                    <td></td><td></td><td></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {{-- RIGHT: summary card --}}
          <div class="col-xl-4 col-summary">
            <div class="sum" id="summaryCard">
              <div class="srow">
                <div class="slb">Sub Total:</div>
                <input id="subTotal" class="inp ro te" value="0.00" readonly>
              </div>

              <div class="srow">
                <div class="slb">Discount:</div>
                <input id="discount" name="discount" type="number" step="0.0" class="inp te" value="0.00">
              </div>

              <div class="srow">
                <div class="slb">Grand Total:</div>
                <input id="grandTotal" class="inp ro te" value="0.00" readonly>
              </div>

              {{-- Paid: method + received amount (RIGHT BOX = AMOUNT) --}}
              <div class="srow2">
                <div class="slb">Paid:</div>
                <select id="paidMethod" class="inp">
                  <option value="bank">Bank</option>
                  <option value="cash">Cash</option>
                  <option value="bkash">Bkash</option>
                  <option value="rocket">Rocket</option>
                  <option value="deposit">Cash Deposit</option>
                </select>
                <input id="paidAmount" type="number" step="0.0" class="inp te" placeholder="0.00">
              </div>

              <div class="srow">
                <div class="slb">Due:</div>
                <input id="due" class="inp ro te" value="0.00" readonly>
              </div>

              <div class="te pt-1">
                <button type="submit" class="save"><i class="fas fa-save me-2"></i>Save</button>
              </div>
            </div>
          </div>

        </div>
      </div>

    </form>
  </div>
</div>
@endsection

@push('styles')
<style>
:root{ --fs:14px; --h:36px; --bdr:#d7d7d7; --lab:#f2f5f9; --ro:#e7e9ec; --thead:#eef3f8; --text:#3e4a57; --ph:#8c98a5;}
*{box-sizing:border-box}
.page{border:1px solid var(--bdr);background:#fff}
.hd{display:flex;justify-content:space-between;align-items:center;background:#f3f5f7;border-bottom:1px solid var(--bdr);padding:10px 12px}
.hd-left{font-weight:600;color:#365a7d;font-size:18px}
.hd-link{background:#e9eff5;border:1px solid #cdd9e3;border-radius:2px;padding:6px 10px;color:#2c6fa2;text-decoration:none;font-weight:600}

.top{padding:10px 12px}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:10px 16px}
.pair{display:grid;grid-template-columns:140px 1fr;gap:8px;align-items:center}
.lab{background:var(--lab);border:1px solid #e3e9ef;border-radius:2px;padding:8px 10px;font-weight:600;color:#4a5867}
.inp{height:var(--h);border:1px solid #cfd8e3;border-radius:2px;background:#fff;width:100%;padding:6px 10px;font-size:var(--fs);color:#3e4a57}
.inp:focus{outline:none;border-color:#b7c3d2}
.ro{background:var(--ro)} .ph::placeholder{color:var(--ph)}
.ig{display:flex}.ig-main{border-right:0;border-radius:2px 0 0 2px}
.ig-ico{width:36px;display:flex;align-items:center;justify-content:center;border:1px solid #cfd8e3;border-left:0;border-radius:0 2px 2px 0;background:#e7e9ec;color:#6f7d8d}

.mid{padding:0 12px 12px}
.t{width:100%;border:1px solid var(--bdr);margin:0;border-collapse:separate;border-spacing:0;table-layout:fixed;font-size:var(--fs)}
.t thead th{background:var(--thead);border-bottom:1px solid var(--bdr);padding:8px 10px;color:var(--text);font-weight:700}
.t tbody td{border-top:1px solid #edf0f3;padding:6px 8px;vertical-align:middle}
.tc{text-align:center}.te{text-align:right}

.prodwrap{display:flex;gap:8px;align-items:center}
.prodwrap .inp{flex:1;min-width:0}
.btnwrap{display:flex;gap:8px;justify-content:flex-end}
.info{background:#56a6df;border:1px solid #4a98d0;color:#fff;height:28px;width:28px;padding:0}
.plus{background:#ffbd4f;border:1px solid #f0ad44;color:#fff;height:30px;width:30px}
.minus{background:#ef6b5a;border:1px solid #e35c4d;color:#fff;height:30px;width:30px}

.trow td{border-top:0}
.tlabel{background:#f0f1f3;border:1px solid var(--bdr);border-left:0;text-align:left;font-weight:600;padding:8px}
.tval input{background:var(--ro);border:1px solid #cfd8e3}

.col-summary{flex:0 0 auto;}
#summaryCard{background:#eef0f3;border:1px solid var(--bdr);padding:10px;margin-top:12px;}
.srow{display:grid;grid-template-columns:120px 1fr;gap:10px;margin-bottom:8px}
.srow2{display:grid;grid-template-columns:120px 1fr 1fr;gap:10px;margin-bottom:8px}
.slb{font-weight:700;color:var(--text)}
.save{background:#57b35f;border:1px solid #49a851;color:#fff;padding:7px 12px;border-radius:2px;font-weight:700;font-size:var(--fs)}

@media (min-width:1200px){
  #summaryCard{width:520px;max-width:520px;margin-left:auto;}
  #summaryCard .srow > :nth-child(2) .inp,
  #summaryCard .srow > :nth-child(2) input.inp,
  #summaryCard .srow > :nth-child(2) select.inp{max-width:360px}
}
@media (max-width:1199.98px){
  #summaryCard{width:100%;max-width:none;margin-left:0;}
}
@media (max-width:992px){ .grid2{grid-template-columns:1fr} }
</style>
@endpush

@push('scripts')
<script>
(function(){
  const tbody      = document.getElementById('rows');
  const discountEl = document.getElementById('discount');
  const subEl      = document.getElementById('subTotal');
  const grandEl    = document.getElementById('grandTotal');
  const dueEl      = document.getElementById('due');
  const tkgEl      = document.getElementById('tkgTotal');
  const paidAmtEl  = document.getElementById('paidAmount');
  const paidMethod = document.getElementById('paidMethod');

  /* ---------- calc helpers ---------- */
  function recalcRow(tr){
    const q  = parseFloat(tr.querySelector('.qty')?.value)||0;
    const a  = parseFloat(tr.querySelector('.adj')?.value)||0;
    const p  = parseFloat(tr.querySelector('.price')?.value)||0;
    const tk = q + a;
    const tkg = tr.querySelector('.tkg');
    if(tkg) tkg.value = tk ? tk.toFixed(2) : '';
    const sub = tr.querySelector('.sub');
    if(sub) sub.value = (tk*p || 0).toFixed(2);
    recalcTotals();
  }

  function recalcTotals(){
    let kg=0, sub=0;
    tbody.querySelectorAll('tr.r').forEach(r=>{
      kg += parseFloat(r.querySelector('.tkg')?.value)||0;
      sub+= parseFloat(r.querySelector('.sub')?.value)||0;
    });
    tkgEl.value = kg.toFixed(2);
    subEl.value = sub.toFixed(2);

    const d = parseFloat(discountEl.value)||0;
    const grand = Math.max(sub - d, 0);
    grandEl.value = grand.toFixed(2);

    const paid = parseFloat(paidAmtEl.value)||0;
    const due  = Math.max(grand - paid, 0);
    dueEl.value = due.toFixed(2);
  }

  /* ---------- dynamic rows (+ / -) ---------- */
  function nextIndex(){ return tbody.querySelectorAll('tr.r').length; }

  function renumberAndFixNames(){
    let i = 0;
    tbody.querySelectorAll('tr.r').forEach(tr=>{
      tr.querySelector('.sl').textContent = (i+1);
      tr.querySelectorAll('select, input').forEach(el=>{
        if(el.name){
          el.name = el.name.replace(/items\[\d+\]/,'items['+i+']');
        }
      });
      i++;
    });
    // disable minus if single row
    const rows = tbody.querySelectorAll('tr.r');
    rows.forEach(r => r.querySelector('.minus').disabled = (rows.length===1));
  }

  function clearRowValues(tr){
    tr.querySelectorAll('input').forEach(inp=>{
      const cls = inp.classList;
      if(cls.contains('unit') || cls.contains('cat') || cls.contains('avail') || cls.contains('tkg') || cls.contains('sub')){
        inp.value = '';
      }else if(cls.contains('adj')){
        inp.value = '0';
      }else{
        inp.value = '';
      }
    });
    const price = tr.querySelector('.price'); if(price) price.value='';
    const prod  = tr.querySelector('.prod');  if(prod)  prod.selectedIndex = 0;
    const wh    = tr.querySelector('select[name*="[warehouse_id]"]'); if(wh) wh.selectedIndex = 0;
  }

  function addRow(afterTr){
    const base = tbody.querySelector('tr.r');                 // template: first row
    const clone = base.cloneNode(true);
    // update index in names to next
    const idx = nextIndex();
    clone.querySelectorAll('select, input').forEach(el=>{
      if(el.name){ el.name = el.name.replace(/items\[\d+\]/,'items['+idx+']'); }
    });
    clearRowValues(clone);
    afterTr.insertAdjacentElement('afterend', clone);
    renumberAndFixNames();
  }

  function removeRow(tr){
    if(tbody.querySelectorAll('tr.r').length>1){
      tr.remove();
      renumberAndFixNames();
      recalcTotals();
    }
  }

  // delegate clicks for plus/minus
  tbody.addEventListener('click', e=>{
    const btnPlus  = e.target.closest('.plus');
    const btnMinus = e.target.closest('.minus');
    if(btnPlus){
      addRow(btnPlus.closest('tr.r'));
    }else if(btnMinus){
      removeRow(btnMinus.closest('tr.r'));
    }
  });

  /* ---------- product fill & calc bindings ---------- */
  tbody.addEventListener('change', e=>{
    if(e.target.classList.contains('prod')){
      const tr=e.target.closest('tr'); const o=e.target.selectedOptions[0];
      tr.querySelector('.unit').value  = o?.dataset?.unit || '';
      tr.querySelector('.cat').value   = o?.dataset?.cat  || '';
      tr.querySelector('.avail').value = o?.dataset?.qty  || '';
      const pr=tr.querySelector('.price'); if(pr && !pr.value) pr.value = o?.dataset?.price || '';
      recalcRow(tr);
    }
  });

  tbody.addEventListener('input', e=>{
    if(['qty','adj','price'].some(c=>e.target.classList.contains(c))) recalcRow(e.target.closest('tr'));
  });

  /* ---------- summary inputs ---------- */
  discountEl.addEventListener('input', recalcTotals);
  paidAmtEl.addEventListener('input', recalcTotals);

  function setPaidPlaceholder(){
    const m = paidMethod.value;
    const text = {
      bank:'Amount received (Bank)',
      cash:'Amount received (Cash)',
      bkash:'Amount received (Bkash)',
      rocket:'Amount received (Rocket)',
      deposit:'Amount received (Deposit)'
    }[m] || 'Amount received';
    paidAmtEl.placeholder = text;
  }
  paidMethod.addEventListener('change', setPaidPlaceholder);

  // init
  renumberAndFixNames();
  setPaidPlaceholder();
  recalcTotals();
})();
</script>
@endpush
