@extends('layouts.app')

@section('content')

<div class="row">
    <div class="col-sm-12">
        <div class="page-title-box">
            <div class="row">
                <div class="col">
                    <h4 class="page-title">New Credit Note</h4>
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('finance.credit-notes.index') }}">Credit Notes</a></li>
                        <li class="breadcrumb-item active">Create</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow-sm">
            <div class="card-body p-4">

                <form id="credit-note-form" action="{{ route('finance.credit-notes.store') }}" method="POST">
                @csrf

                {{-- Invoice Selection --}}
                <div class="mb-3">
                    <label class="form-label fw-bold">Invoice <span class="text-danger">*</span></label>
                    <select name="invoice_id" id="invoice_id" class="form-select select2" required>
                        <option value="">— Select Invoice to Credit —</option>
                        @foreach($invoices as $invoice)
                            <option value="{{ $invoice->id }}"
                                data-client="{{ $invoice->client?->name }}"
                                data-client-id="{{ $invoice->client_id }}"
                                data-total="{{ $invoice->total_amount }}"
                                data-balance="{{ $invoice->balance_amount }}"
                                data-currency="{{ $invoice->currency?->symbol ?? '' }}">
                                {{ $invoice->invoice_number }} — {{ $invoice->client?->name }} (Balance: {{ $invoice->currency?->symbol ?? '' }}{{ number_format($invoice->balance_amount, 2) }})
                            </option>
                        @endforeach
                    </select>
                    <input type="hidden" name="client_id" id="client_id_hidden">
                </div>

                {{-- Invoice Info Preview --}}
                <div id="invoice-preview" class="p-3 bg-light rounded mb-3" style="display:none;">
                    <div class="row small">
                        <div class="col-md-3">
                            <span class="text-muted d-block">Client</span>
                            <strong id="preview-client"></strong>
                        </div>
                        <div class="col-md-3">
                            <span class="text-muted d-block">Invoice Total</span>
                            <strong id="preview-total"></strong>
                        </div>
                        <div class="col-md-3">
                            <span class="text-muted d-block">Balance Due</span>
                            <strong id="preview-balance" class="text-danger"></strong>
                        </div>
                        <div class="col-md-3">
                            <span class="text-muted d-block">Max Credit</span>
                            <strong id="preview-max" class="text-success"></strong>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Credit Note Date <span class="text-danger">*</span></label>
                            <input type="date" name="credit_note_date" class="form-control" required value="{{ date('Y-m-d') }}">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Credit Amount <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text" id="currency-symbol">$</span>
                                <input type="number" name="total_amount" id="credit_amount" class="form-control" step="0.01" min="0.01" placeholder="0.00" required>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Reason <span class="text-danger">*</span></label>
                    <select name="reason_type" id="reason_type" class="form-select mb-2" required>
                        <option value="">— Select Reason —</option>
                        <option value="returned_goods">Returned Goods</option>
                        <option value="billing_error">Billing Error / Overcharge</option>
                        <option value="service_not_rendered">Service Not Rendered</option>
                        <option value="quality_issue">Quality / Defect Issue</option>
                        <option value="discount_applied">Discount Applied</option>
                        <option value="duplicate_invoice">Duplicate Invoice</option>
                        <option value="other">Other</option>
                    </select>
                    <input type="hidden" name="reason" id="reason_final">
                    <textarea id="reason_detail" name="reason_detail" class="form-control" rows="2" placeholder="Additional details (optional)"></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Internal Notes</label>
                    <textarea name="notes" class="form-control" rows="2" placeholder="Internal notes (not shown to client)"></textarea>
                </div>

                <div class="d-flex gap-2 justify-content-end">
                    <a href="{{ route('finance.credit-notes.index') }}" class="btn btn-light">Cancel</a>
                    <button type="submit" class="btn btn-primary">
                        <i class="ti ti-check me-1"></i>Create Credit Note
                    </button>
                </div>

                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm border-info border-top border-3">
            <div class="card-body p-4">
                <h6 class="fw-bold mb-3"><i class="ti ti-info-circle me-2 text-info"></i>About Credit Notes</h6>
                <ul class="list-unstyled small text-muted">
                    <li class="mb-2"><i class="ti ti-check me-2 text-success"></i>A credit note reduces the amount owed by a client.</li>
                    <li class="mb-2"><i class="ti ti-check me-2 text-success"></i>It can be issued for returns, overcharges, or corrections.</li>
                    <li class="mb-2"><i class="ti ti-check me-2 text-success"></i>The credit amount cannot exceed the invoice balance.</li>
                    <li class="mb-2"><i class="ti ti-check me-2 text-success"></i>The invoice balance will be updated automatically.</li>
                </ul>

                <hr>

                <div class="totals-summary" style="display:none;" id="cn-summary">
                    <p class="text-muted small fw-bold text-uppercase mb-2" style="font-size:11px;">Credit Summary</p>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted small">Invoice Balance</span>
                        <span class="fw-semibold small" id="sum-balance">—</span>
                    </div>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted small">Credit Amount</span>
                        <span class="fw-semibold small text-warning" id="sum-credit">—</span>
                    </div>
                    <hr class="my-2">
                    <div class="d-flex justify-content-between">
                        <span class="small fw-bold">Remaining Balance</span>
                        <span class="fw-bold small" id="sum-remaining">—</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function () {

    $('#invoice_id').select2({ theme: 'bootstrap-5', placeholder: '— Select Invoice to Credit —' });

    $('#invoice_id').on('change', function () {
        const opt     = $(this).find('option:selected');
        const balance = parseFloat(opt.data('balance')) || 0;
        const total   = parseFloat(opt.data('total')) || 0;
        const symbol  = opt.data('currency') || '$';
        const client  = opt.data('client') || '';
        const cid     = opt.data('client-id') || '';

        if (!$(this).val()) {
            $('#invoice-preview').hide();
            $('#cn-summary').hide();
            return;
        }

        $('#preview-client').text(client);
        $('#preview-total').text(symbol + parseFloat(total).toFixed(2));
        $('#preview-balance').text(symbol + balance.toFixed(2));
        $('#preview-max').text(symbol + balance.toFixed(2));
        $('#invoice-preview').show();

        $('#client_id_hidden').val(cid);
        $('#currency-symbol').text(symbol);
        $('#credit_amount').attr('max', balance.toFixed(2)).val(balance.toFixed(2));

        updateSummary();
        $('#cn-summary').show();
    });

    $('#credit_amount').on('input', updateSummary);

    function updateSummary() {
        const opt      = $('#invoice_id option:selected');
        const balance  = parseFloat(opt.data('balance')) || 0;
        const symbol   = opt.data('currency') || '$';
        const credit   = parseFloat($('#credit_amount').val()) || 0;
        const remaining = balance - credit;

        $('#sum-balance').text(symbol + balance.toFixed(2));
        $('#sum-credit').text(symbol + credit.toFixed(2));
        $('#sum-remaining').text(symbol + remaining.toFixed(2))
            .toggleClass('text-danger', remaining < 0)
            .toggleClass('text-success', remaining >= 0);
    }

    $('#credit-note-form').on('submit', function (e) {
        e.preventDefault();

        // Build reason from type + detail
        const type   = $('#reason_type').val();
        const detail = $('#reason_detail').val().trim();
        const label  = $('#reason_type option:selected').text();
        $('#reason_final').val(detail ? `${label}: ${detail}` : label);

        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status) {
                    Swal.fire({ icon: 'success', title: 'Created!', text: res.message, timer: 1500 })
                        .then(() => window.location.href = "{{ route('finance.credit-notes.index') }}");
                }
            },
            error: function (xhr) {
                const errors = xhr.responseJSON?.errors;
                if (errors) {
                    Swal.fire('Validation Error', Object.values(errors).flat().join('\n'), 'error');
                } else {
                    Swal.fire('Error', xhr.responseJSON?.message ?? 'Something went wrong.', 'error');
                }
            }
        });
    });
});
</script>
@endsection
