@extends('adminlte::page')

@section('content')
<div class="container">
    <h2>Update Invoice Status</h2>

    <div class="mb-3"><strong>Invoice:</strong> {{ $invoice->invoice_number }}</div>
    <div class="mb-3"><strong>Date:</strong> {{ $invoice->invoice_date }}</div>
    <div class="mb-3"><strong>Total:</strong> {{ $invoice->total }}</div>
    <div class="mb-3"><strong>Customer:</strong> {{ $invoice->customer->name }}</div>

    <form id="statusForm">
        @csrf
        <label>Status</label>

        <select name="status" class="form-control mb-3">
            @php
                $statusOrder = ['created', 'submitted', 'partially_paid', 'paid', 'cancelled'];
                $allowed = ['submitted', 'cancelled'];

                $currentIndex = array_search($invoice->status, $statusOrder);
            @endphp

            @foreach ($allowed as $status)
                @php
                    $statusIndex = array_search($status, $statusOrder);
                @endphp

                @if ($statusIndex !== false && $statusIndex > $currentIndex)
                    <option value="{{ $status }}">{{ ucfirst($status) }}</option>
                @endif
            @endforeach
        </select>

        <button class="btn btn-primary">Update Status</button>
    </form>



    <div id="journalFormContainer" class="mt-4"></div>
</div>
@endsection

@section('js')
<script>
    $('#statusForm').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: '{{ route("invoices.updateStatus", $invoice->id) }}',
            method: 'POST',
            data: $(this).serialize(),
            success: function(res) {
                if (res.redirect) {
                    window.location.href = res.redirect;
                } else {
                    $('#journalFormContainer').html(res.form);
                }
            },
            error: function(err) {
                alert(err.responseJSON.error);
            }
        });
    });
</script>
@endsection
