{{-- C4 currency snapshot fields. Params: $record, $fx (code=>Currency), $isNew?, $lockFx? --}}
@php $cur = old('currency_code', $record->currency_code ?? 'GHS'); $rt = old('exchange_rate', $record->exchange_rate ?? null); @endphp
<div class="fld c2"><label>Currency *</label>
<select name="currency_code" data-fx-cur {{ (!empty($lockFx) || !empty($lockCur)) ? 'disabled' : '' }} required>
@foreach($fx as $code => $c)<option value="{{ $code }}" data-rate="{{ $c->rate_to_ghs }}" data-sym="{{ $c->symbol ?: $code }}" {{ $cur===$code?'selected':'' }}>{{ $code }} — {{ $c->name }}</option>@endforeach
</select>
@if(!empty($lockFx) || !empty($lockCur))<input type="hidden" name="currency_code" value="{{ $cur }}">@endif
</div>
<div class="fld c2"><label>Rate → GHS *</label>
<input type="number" step="0.000001" min="0.000001" name="exchange_rate" data-fx-rate value="{{ $rt ?? ($fx[$cur]->rate_to_ghs ?? 1) }}" {{ !empty($lockFx) ? 'readonly' : '' }} required>
<small class="muted" data-fx-hint></small>
</div>
<script>
(function(){
  var cur = document.querySelector('[data-fx-cur]'), rate = document.querySelector('[data-fx-rate]'), hint = document.querySelector('[data-fx-hint]');
  function opt(){ return cur.options[cur.selectedIndex]; }
  function paint(){
    var r = parseFloat(opt().dataset.rate || '1');
    document.querySelectorAll('[data-fx-sym]').forEach(function(el){ el.textContent = opt().dataset.sym || cur.value; });
    if (hint) hint.textContent = cur.value === 'GHS' ? 'Base currency' : ('1 ' + cur.value + ' = ' + r + ' GHS (master)');
  }
  cur.addEventListener('change', function(){ rate.value = opt().dataset.rate || 1; paint(); });
  @if(!empty($isNew))
  ['customer_id','supplier_id'].forEach(function(nm){
    var ps = document.querySelector('select[name=' + nm + ']');
    if (ps) ps.addEventListener('change', function(){
      var dc = ps.options[ps.selectedIndex].dataset.defcur;
      if (dc && cur.querySelector('option[value=' + dc + ']')) { cur.value = dc; cur.dispatchEvent(new Event('change')); }
    });
  });
  @endif
  paint();
})();
</script>
