@extends('layouts.admin')
@section('title','Edit Invoice '.$invoice->invoice_number)
@section('content')
<div class="row justify-content-center"><div class="col-lg-9">
<div class="card">
  <div class="card-header">Edit Invoice {{ $invoice->invoice_number }}</div>
  <div class="card-body">
    @if(!in_array($invoice->status,['draft']))
    <div class="alert alert-warning"><i class="fas fa-exclamation-triangle me-2"></i>Hanya invoice berstatus <strong>Draft</strong> yang bisa diedit.</div>
    @endif
    <form action="{{ route('admin.invoices.update',$invoice) }}" method="POST" id="invoiceForm">
    @csrf @method('PUT')
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label fw-semibold">Klien</label>
        <input type="text" class="form-control" value="{{ $invoice->client->name }}" disabled>
      </div>
      <div class="col-md-3">
        <label class="form-label fw-semibold">Divisi</label>
        <input type="text" class="form-control" value="{{ $invoice->division }}" disabled>
      </div>
      <div class="col-md-3">
        <label class="form-label fw-semibold">Tipe</label>
        <input type="text" class="form-control" value="{{ strtoupper($invoice->type) }}" disabled>
      </div>
      <div class="col-md-4">
        <label class="form-label fw-semibold">Tanggal Invoice</label>
        <input type="text" class="form-control" value="{{ $invoice->issue_date->format('d/m/Y') }}" disabled>
      </div>
      <div class="col-md-4">
        <label class="form-label fw-semibold">Jatuh Tempo *</label>
        <input type="date" name="due_date" class="form-control" value="{{ $invoice->due_date->format('Y-m-d') }}" required>
      </div>
      <div class="col-md-4">
        <label class="form-label fw-semibold">PPN (%)</label>
        <input type="number" name="tax_percent" class="form-control" min="0" max="100" value="{{ $invoice->tax_percent }}" step="0.01" id="taxInput">
      </div>
      <div class="col-12">
        <label class="form-label fw-semibold">Catatan</label>
        <textarea name="notes" class="form-control" rows="2">{{ $invoice->notes }}</textarea>
      </div>

      {{-- Items --}}
      <div class="col-12">
        <label class="form-label fw-semibold">Item Invoice *</label>
        <div id="itemsContainer">
          @foreach($invoice->items as $i => $item)
          <div class="row g-2 mb-2 item-row align-items-end">
            <div class="col-md-6"><input type="text" name="items[{{ $i }}][description]" class="form-control form-control-sm" value="{{ $item->description }}" placeholder="Deskripsi" required></div>
            <div class="col-md-2"><input type="number" name="items[{{ $i }}][qty]" class="form-control form-control-sm qty-input" value="{{ $item->qty }}" min="1" required></div>
            <div class="col-md-3"><input type="number" name="items[{{ $i }}][unit_price]" class="form-control form-control-sm price-input" value="{{ $item->unit_price }}" min="0" required></div>
            <div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger remove-item"><i class="fas fa-trash"></i></button></div>
          </div>
          @endforeach
        </div>
        <button type="button" class="btn btn-sm btn-outline-primary mt-1" id="addItem"><i class="fas fa-plus me-1"></i>Tambah Item</button>
        <div class="mt-2 text-end fw-bold" id="totalPreview">Total: Rp 0</div>
      </div>

      <div class="col-12 d-flex gap-2 justify-content-end">
        <a href="{{ route('admin.invoices.show',$invoice) }}" class="btn btn-secondary">Batal</a>
        <button type="submit" class="btn btn-primary" {{ !in_array($invoice->status,['draft'])?'disabled':'' }}><i class="fas fa-save me-1"></i>Simpan</button>
      </div>
    </div>
    </form>
  </div>
</div>
</div></div>
@endsection
@push('scripts')
<script>
let idx = {{ $invoice->items->count() }};
document.getElementById('addItem').onclick = function() {
  document.getElementById('itemsContainer').insertAdjacentHTML('beforeend',
    `<div class="row g-2 mb-2 item-row align-items-end">
      <div class="col-md-6"><input type="text" name="items[${idx}][description]" class="form-control form-control-sm" placeholder="Deskripsi" required></div>
      <div class="col-md-2"><input type="number" name="items[${idx}][qty]" class="form-control form-control-sm qty-input" value="1" min="1" required></div>
      <div class="col-md-3"><input type="number" name="items[${idx}][unit_price]" class="form-control form-control-sm price-input" value="0" min="0" required></div>
      <div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger remove-item"><i class="fas fa-trash"></i></button></div>
    </div>`);
  idx++; bindEvents();
};
function bindEvents() {
  document.querySelectorAll('.remove-item').forEach(b => b.onclick = function() {
    if (document.querySelectorAll('.item-row').length > 1) { b.closest('.item-row').remove(); calcTotal(); }
  });
  document.querySelectorAll('.qty-input,.price-input').forEach(i => i.oninput = calcTotal);
}
function calcTotal() {
  let sub = 0;
  document.querySelectorAll('.item-row').forEach(row => {
    sub += (parseFloat(row.querySelector('.qty-input').value)||0) * (parseFloat(row.querySelector('.price-input').value)||0);
  });
  const tax   = parseFloat(document.getElementById('taxInput').value)||0;
  const total = sub * (1 + tax/100);
  document.getElementById('totalPreview').textContent = 'Total: Rp ' + total.toLocaleString('id-ID');
}
document.getElementById('taxInput').oninput = calcTotal;
bindEvents(); calcTotal();
</script>
@endpush
