@extends('layouts.app')
@section('title', 'Edit Invoice')
@section('page-title', 'Edit Invoice')

@push('styles')
<style>
    .item-row td { vertical-align: middle; }
    .summary-table td:first-child { color: #6c757d; }
    .summary-table .total-row td { font-weight: 700; font-size: 1.05rem; border-top: 2px solid #dee2e6; }
</style>
@endpush

@section('content')
<div class="row mb-3">
    <div class="col-sm-12 d-flex align-items-center">
        <a href="{{ route('invoices.show', $invoice) }}" class="btn btn-sm btn-outline-secondary mr-2"><i class="fas fa-arrow-left"></i></a>
        <h5 class="mb-0 font-weight-bold">Edit Invoice #{{ $invoice->invoice_number }}</h5>
    </div>
</div>

<form method="POST" action="{{ route('invoices.update', $invoice) }}" id="invoice-form">
@csrf @method('PUT')
<div class="row">
    <div class="col-md-9">
        <div class="card card-primary card-outline mb-3">
            <div class="card-header">
                <h3 class="card-title">Informasi Invoice</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>No. Invoice</label>
                            <input type="text" class="form-control" value="{{ $invoice->invoice_number }}" readonly>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Pelanggan <span class="text-danger">*</span></label>
                            <select name="customer_id" class="form-control" required>
                                <option value="">-- Pilih Pelanggan --</option>
                                @foreach($customers as $c)
                                    <option value="{{ $c->id }}" @selected(old('customer_id', $invoice->customer_id) == $c->id)>{{ $c->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Tanggal Invoice <span class="text-danger">*</span></label>
                            <input type="date" name="invoice_date" class="form-control" value="{{ old('invoice_date', $invoice->invoice_date->format('Y-m-d')) }}" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Jatuh Tempo</label>
                            <input type="date" name="due_date" class="form-control" value="{{ old('due_date', $invoice->due_date?->format('Y-m-d')) }}">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Status</label>
                            <select name="status" class="form-control">
                                <option value="draft" @selected(old('status', $invoice->status)=='draft')>Draft</option>
                                <option value="sent" @selected(old('status', $invoice->status)=='sent')>Terkirim</option>
                                <option value="paid" @selected(old('status', $invoice->status)=='paid')>Lunas</option>
                                <option value="cancelled" @selected(old('status', $invoice->status)=='cancelled')>Dibatalkan</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card card-info card-outline mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h3 class="card-title">Item / Barang / Jasa</h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-sm btn-primary" id="add-item">
                        <i class="fas fa-plus"></i> Tambah Item
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped align-middle mb-0" id="items-table">
                        <thead>
                            <tr>
                                <th style="width:40px">No</th>
                                <th>Deskripsi</th>
                                <th style="width:100px">Jumlah</th>
                                <th style="width:80px">Satuan</th>
                                <th style="width:140px">Harga Satuan</th>
                                <th style="width:140px" class="text-right">Harga Total</th>
                                <th style="width:40px"></th>
                            </tr>
                        </thead>
                        <tbody id="items-body"></tbody>
                        <tfoot>
                            <tr>
                                <td colspan="7" class="p-2">
                                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-item-2">
                                        <i class="fas fa-plus"></i> Tambah Baris
                                    </button>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header">
                <h3 class="card-title">Catatan</h3>
            </div>
            <div class="card-body">
                <textarea name="notes" class="form-control" rows="3">{{ old('notes', $invoice->notes) }}</textarea>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card card-success card-outline sticky-top" style="top: 20px">
            <div class="card-header">
                <h3 class="card-title">Ringkasan</h3>
            </div>
            <div class="card-body">
                <table class="table table-sm summary-table">
                    <tr><td>Subtotal</td><td class="text-right" id="disp-subtotal">Rp 0</td></tr>
                    <tr><td>Bayar (-)</td><td class="text-right text-danger" id="disp-paid">Rp 0</td></tr>
                    <tr><td>Diskon (-)</td><td class="text-right text-danger" id="disp-discount">Rp 0</td></tr>
                    <tr><td>Pajak (+)</td><td class="text-right text-success" id="disp-tax">Rp 0</td></tr>
                    <tr><td>Kirim (+)</td><td class="text-right text-success" id="disp-shipping">Rp 0</td></tr>
                    <tr class="total-row"><td>TOTAL</td><td class="text-right" id="disp-total">Rp 0</td></tr>
                </table>
                <hr>
                <div class="form-group mb-2">
                    <label class="small">Sudah Dibayar (Rp)</label>
                    <input type="number" name="amount_paid" id="inp-paid" class="form-control form-control-sm" value="{{ old('amount_paid', $invoice->amount_paid) }}" min="0" step="1">
                </div>
                <div class="form-group mb-2">
                    <label class="small">Diskon (Rp)</label>
                    <input type="number" name="discount" id="inp-discount" class="form-control form-control-sm" value="{{ old('discount', $invoice->discount) }}" min="0" step="1">
                </div>
                <div class="form-group mb-2">
                    <label class="small">Pajak (Rp)</label>
                    <input type="number" name="tax" id="inp-tax" class="form-control form-control-sm" value="{{ old('tax', $invoice->tax) }}" min="0" step="1">
                </div>
                <div class="form-group mb-3">
                    <label class="small">Biaya Pengiriman (Rp)</label>
                    <input type="number" name="shipping_cost" id="inp-shipping" class="form-control form-control-sm" value="{{ old('shipping_cost', $invoice->shipping_cost) }}" min="0" step="1">
                </div>
                <button type="submit" class="btn btn-success btn-block">
                    <i class="fas fa-save"></i> Simpan Perubahan
                </button>
                <a href="{{ route('invoices.show', $invoice) }}" class="btn btn-outline-secondary btn-block mt-2">Batal</a>
            </div>
        </div>
    </div>
</div>
</form>
@endsection

@push('scripts')
<script>
let itemCount = 0;
const existingItems = @json($invoice->items);

function fmt(n) {
    return 'Rp ' + Math.max(0, n).toLocaleString('id-ID');
}

function addItem(serviceType = '', desc = '', qty = 1, unit = '', price = 0) {
    const idx = itemCount++;
    const total = qty * price;
    const row = `
    <tr class="item-row" data-idx="${idx}">
        <td class="text-center text-muted row-num"></td>
        <td><input type="text" name="items[${idx}][service_type]" class="form-control form-control-sm" value="${serviceType}" placeholder="Jenis Jasa"></td>
        <td><input type="text" name="items[${idx}][description]" class="form-control form-control-sm" value="${desc}" placeholder="Deskripsi" required></td>
        <td><input type="number" name="items[${idx}][quantity]" class="form-control form-control-sm qty" value="${qty}" min="0.01" step="0.01" required></td>
        <td><input type="text" name="items[${idx}][unit]" class="form-control form-control-sm" value="${unit}" placeholder="pcs"></td>
        <td><input type="number" name="items[${idx}][unit_price]" class="form-control form-control-sm unit-price" value="${price}" min="0" step="1" required></td>
        <td class="text-right"><span class="row-total font-weight-bold">${fmt(total)}</span></td>
        <td class="text-center"><button type="button" class="btn btn-sm btn-link text-danger remove-item"><i class="fas fa-times"></i></button></td>
    </tr>`;
    document.getElementById('items-body').insertAdjacentHTML('beforeend', row);
    reNumberRows();
    recalc();
}

function reNumberRows() {
    document.querySelectorAll('#items-body tr').forEach((tr, i) => {
        tr.querySelector('.row-num').textContent = i + 1;
    });
}

function recalc() {
    let subtotal = 0;
    document.querySelectorAll('#items-body .item-row').forEach(tr => {
        const qty   = parseFloat(tr.querySelector('.qty').value) || 0;
        const price = parseFloat(tr.querySelector('.unit-price').value) || 0;
        const t     = qty * price;
        tr.querySelector('.row-total').textContent = fmt(t);
        subtotal += t;
    });
    const paid     = parseFloat(document.getElementById('inp-paid').value) || 0;
    const discount = parseFloat(document.getElementById('inp-discount').value) || 0;
    const tax      = parseFloat(document.getElementById('inp-tax').value) || 0;
    const shipping = parseFloat(document.getElementById('inp-shipping').value) || 0;
    const total    = subtotal - paid - discount + tax + shipping;

    document.getElementById('disp-subtotal').textContent = fmt(subtotal);
    document.getElementById('disp-paid').textContent     = fmt(paid);
    document.getElementById('disp-discount').textContent = fmt(discount);
    document.getElementById('disp-tax').textContent      = fmt(tax);
    document.getElementById('disp-shipping').textContent = fmt(shipping);
    document.getElementById('disp-total').textContent    = fmt(total);
}

document.getElementById('items-body').addEventListener('input', e => {
    if (e.target.matches('.qty, .unit-price')) recalc();
});
document.getElementById('items-body').addEventListener('click', e => {
    if (e.target.closest('.remove-item')) {
        e.target.closest('tr').remove();
        reNumberRows(); recalc();
    }
});
['inp-paid','inp-discount','inp-tax','inp-shipping'].forEach(id => {
    document.getElementById(id).addEventListener('input', recalc);
});
document.getElementById('add-item').addEventListener('click', () => addItem());
document.getElementById('add-item-2').addEventListener('click', () => addItem());

// Load existing items
existingItems.forEach(item => {
    addItem(item.description, item.quantity, item.unit || '', item.unit_price);
});
if (existingItems.length === 0) addItem();
</script>
@endpush

