@extends('layouts.app')

@section('content')
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-12 col-xl-11">
            <form method="POST" action="{{ route('admin_fit.pay_bill.update', $payBill) }}" id="payBillForm" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-gradient bg-warning text-dark border-0 py-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <i class="bi bi-pencil-square fs-4 me-3"></i>
                                <div>
                                    <h5 class="mb-0 fw-bold">Editar Pago Interno #{{ $payBill->id }}</h5>
                                    <small class="opacity-75">Modificación de pago a facturas</small>
                                </div>
                            </div>
                            <a href="{{ route('admin_fit.pay_bill.index') }}" class="btn btn-sm btn-dark">
                                <i class="bi bi-chevron-left"></i> Volver
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        @if ($errors->any())
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="bi bi-exclamation-triangle me-2"></i>
                                <strong>Errores encontrados:</strong>
                                <ul class="mb-0 mt-2">
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        @endif

                        {{-- Sección 1: Datos del Pago --}}
                        <div class="mb-4">
                            <h6 class="text-muted text-uppercase small fw-bold mb-3">
                                <i class="bi bi-info-circle me-2"></i>Datos del Pago
                            </h6>
                            <div class="row g-3">
                                <div class="col-6 col-md-3">
                                    <label for="pay_date" class="form-label small fw-medium">Fecha de Pago <span class="text-danger">*</span></label>
                                    <input type="date" id="pay_date" name="pay_date" class="form-control @error('pay_date') is-invalid @enderror" value="{{ old('pay_date', $payBill->pay_date->format('Y-m-d')) }}" required>
                                    @error('pay_date')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-6 col-md-3">
                                    <label for="pay_type_id" class="form-label small fw-medium">Tipo de Pago <span class="text-danger">*</span></label>
                                    <select id="pay_type_id" name="pay_type_id" class="form-select @error('pay_type_id') is-invalid @enderror" required>
                                        <option value="">Seleccione...</option>
                                        @foreach($payTypes as $type)
                                            <option value="{{ $type->id }}" {{ old('pay_type_id', $payBill->pay_type_id) == $type->id ? 'selected' : '' }}>{{ $type->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('pay_type_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-6 col-md-3">
                                    <label for="amount" class="form-label small fw-medium">Monto Total <span class="text-danger">*</span></label>
                                    <input type="text" id="amount" name="amount" class="form-control mountFormat @error('amount') is-invalid @enderror" value="{{ old('amount', number_format($payBill->amount, 2, ',', '.')) }}" required>
                                    @error('amount')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-6 col-md-3">
                                    <label for="status" class="form-label small fw-medium">Estado <span class="text-danger">*</span></label>
                                    <select id="status" name="status" class="form-select @error('status') is-invalid @enderror" required>
                                        <option value="Pendiente" {{ old('status', $payBill->status) == 'Pendiente' ? 'selected' : '' }}>Pendiente</option>
                                        <option value="Aprobado" {{ old('status', $payBill->status) == 'Aprobado' ? 'selected' : '' }}>Aprobado</option>
                                        <option value="Rechazado" {{ old('status', $payBill->status) == 'Rechazado' ? 'selected' : '' }}>Rechazado</option>
                                    </select>
                                    @error('status')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        {{-- Sección 2: Información Adicional --}}
                        <div class="mb-4">
                            <h6 class="text-muted text-uppercase small fw-bold mb-3">
                                <i class="bi bi-card-text me-2"></i>Información Adicional
                            </h6>
                            <div class="row g-3">
                                <div class="col-6 col-md-4">
                                    <label for="reference" class="form-label small fw-medium">Referencia</label>
                                    <input type="text" id="reference" name="reference" class="form-control @error('reference') is-invalid @enderror" value="{{ old('reference', $payBill->reference) }}" maxlength="100">
                                    @error('reference')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-6 col-md-4">
                                    <label for="id_card_number" class="form-label small fw-medium">Cédula</label>
                                    <input type="text" id="id_card_number" name="id_card_number" class="form-control @error('id_card_number') is-invalid @enderror" value="{{ old('id_card_number', $payBill->id_card_number) }}" maxlength="50">
                                    @error('id_card_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-6 col-md-4">
                                    <label for="bank_id" class="form-label small fw-medium">Banco</label>
                                    <select id="bank_id" name="bank_id" class="form-select @error('bank_id') is-invalid @enderror">
                                        <option value="">Seleccione...</option>
                                        @foreach($banks as $bank)
                                            <option value="{{ $bank->id }}" {{ old('bank_id', $payBill->bank_id) == $bank->id ? 'selected' : '' }}>{{ $bank->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('bank_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        {{-- Sección 3: Detalles del Pago (Facturas Asociadas) --}}
                        <div class="mb-4">
                            <h6 class="text-muted text-uppercase small fw-bold mb-3">
                                <i class="bi bi-receipt me-2"></i>Facturas Asociadas al Pago
                            </h6>
                            
                            @if($payBill->details->isEmpty())
                                <div class="alert alert-info">
                                    <i class="bi bi-info-circle me-2"></i>
                                    Este pago no tiene facturas asociadas.
                                </div>
                            @else
                                <div class="border rounded-3 overflow-hidden">
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Factura</th>
                                                    <th>Proveedor</th>
                                                    <th class="text-end">Monto Asignado</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($payBill->details as $detail)
                                                    <tr>
                                                        <td>
                                                            <span class="fw-medium">#{{ $detail->bill_id }}</span>
                                                            <br><small class="text-muted">{{ $detail->bill?->created_at?->format('d/m/Y') ?? '' }}</small>
                                                        </td>
                                                        <td>{{ $detail->bill?->supplier?->supplier_name ?? 'N/A' }}</td>
                                                        <td class="text-end">
                                                            <span class="fw-bold text-success">{{ number_format($detail->amount, 2, ',', '.') }} Bs</span>
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                            <tfoot class="table-light">
                                                <tr>
                                                    <td colspan="2" class="text-end fw-bold">Total Asignado:</td>
                                                    <td class="text-end fw-bold text-success">{{ number_format($detailsTotal, 2, ',', '.') }} Bs</td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>

                                @if($remainingAmount > 0)
                                    <div class="alert alert-warning mt-3">
                                        <i class="bi bi-exclamation-triangle me-2"></i>
                                        <strong>Monto sin asignar:</strong> {{ number_format($remainingAmount, 2, ',', '.') }} Bs
                                    </div>
                                @endif
                            @endif
                        </div>

                        {{-- Nota sobre cambios --}}
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            <strong>Nota:</strong> Al cambiar el estado a <span class="badge bg-success">Aprobado</span>, se descontará automáticamente la deuda de las facturas asociadas. 
                            Al cambiar a <span class="badge bg-danger">Rechazado</span> desde Aprobado, se restaurará la deuda.
                        </div>

                        {{-- Botones de acción --}}
                        <div class="d-grid d-md-flex justify-content-md-between gap-2">
                            <div>
                                <button type="button" class="btn btn-outline-danger" id="deletePayBillBtn">
                                    <i class="bi bi-trash me-1"></i> Eliminar Pago
                                </button>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="{{ route('admin_fit.pay_bill.index') }}" class="btn btn-outline-secondary">
                                    <i class="bi bi-x-lg me-1"></i> Cancelar
                                </a>
                                <button type="submit" class="btn btn-warning btn-lg">
                                    <i class="bi bi-check-circle me-1"></i> Actualizar Pago
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Eliminar pago
    document.getElementById('deletePayBillBtn').addEventListener('click', function() {
        Swal.fire({
            title: '¿Estás seguro?',
            text: "Esta acción eliminará el pago permanentemente",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ route("admin_fit.pay_bill.destroy", $payBill) }}';
                
                const csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = '_token';
                csrfInput.value = '{{ csrf_token() }}';
                form.appendChild(csrfInput);
                
                const methodInput = document.createElement('input');
                methodInput.type = 'hidden';
                methodInput.name = '_method';
                methodInput.value = 'DELETE';
                form.appendChild(methodInput);
                
                document.body.appendChild(form);
                form.submit();
            }
        });
    });
});
</script>
@endpush
@endsection
