@extends('admin.layouts.app')

@section('title', 'مدیریت حواله‌ها')

@section('content')
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <h3 class="mb-0">{{ number_format($totalBills ?? 0) }}</h3>
                <small>کل حواله‌ها</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <h3 class="mb-0">{{ number_format($paidBills ?? 0) }}</h3>
                <small>پرداخت شده</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <h3 class="mb-0">{{ number_format($pendingBills ?? 0) }}</h3>
                <small>در انتظار پرداخت</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <h3 class="mb-0">{{ number_format($totalRevenue ?? 0) }}</h3>
                <small>مجموع درآمد (تومان)</small>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0">لیست حواله‌ها</h5>
            <a href="{{ route('admin.bills.create-internal') }}" class="btn btn-sm btn-primary">
                <i class="fas fa-file-medical me-1"></i>
                ثبت حواله داخلی
            </a>
        </div>
    </div>

    <div class="card-body">
        <!-- Filters -->
        <form method="GET" action="{{ route('admin.bills.index') }}" class="mb-4">
            <div class="row g-3">
                <div class="col-md-3">
                    <input type="text" name="search" class="form-control" placeholder="جستجو (کد، کاربر)" value="{{ request('search') }}">
                </div>

                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">همه وضعیت‌ها</option>
                        <option value="pending" {{ request('status') === 'pending' ? 'selected' : '' }}>در انتظار</option>
                        <option value="paid" {{ request('status') === 'paid' ? 'selected' : '' }}>پرداخت شده</option>
                        <option value="failed" {{ request('status') === 'failed' ? 'selected' : '' }}>ناموفق</option>
                        <option value="refunded" {{ request('status') === 'refunded' ? 'selected' : '' }}>بازگشت داده شده</option>
                    </select>
                </div>

                <div class="col-md-2">
                    <input type="text" name="from_date" class="form-control persian-datepicker" placeholder="از تاریخ" value="{{ request('from_date') }}">
                </div>

                <div class="col-md-2">
                    <input type="text" name="to_date" class="form-control persian-datepicker" placeholder="تا تاریخ" value="{{ request('to_date') }}">
                </div>

                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter me-2"></i>
                        فیلتر
                    </button>
                    <a href="{{ route('admin.bills.index') }}" class="btn btn-outline-secondary">
                        <i class="fas fa-redo"></i>
                    </a>
                </div>
            </div>
        </form>

        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>شماره حواله</th>
                        <th>نوع سند</th>
                        <th>درخواست‌کننده</th>
                        <th>راننده</th>
                        <th>بار</th>
                        <th>مبلغ</th>
                        <th>وضعیت</th>
                        <th>تاریخ</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($bills ?? [] as $bill)
                    <tr>
                        <td class="font-monospace">{{ $bill->dispatch_order_number ?? $bill->bill_number ?? ('#' . $bill->id) }}</td>
                        <td>
                            @if($bill->rmto_registered_at || $bill->rmto_bill_number)
                                <span class="badge bg-success">
                                    <i class="fas fa-check-circle me-1"></i>
                                    بارنامه صادر شده
                                </span>
                                <br>
                                <small class="text-muted">RMTO</small>
                            @else
                                <span class="badge bg-secondary">حواله داخلی</span>
                            @endif
                        </td>
                        <td>
                            {{ $bill->transportLoad->requester->name ?? 'نامشخص' }}
                            <br><small class="text-muted font-monospace">{{ $bill->transportLoad->requester->phone ?? '-' }}</small>
                        </td>
                        <td>
                            {{ $bill->transportLoad->driver->name ?? 'تخصیص‌نیافته' }}
                            <br><small class="text-muted font-monospace">{{ $bill->transportLoad->driver->phone ?? '-' }}</small>
                        </td>
                        <td>
                            @if($bill->transportLoad)
                                <a href="{{ route('admin.loads.show', $bill->load_id) }}">
                                    بار #{{ $bill->load_id }}
                                </a>
                            @else
                                -
                            @endif
                        </td>
                        <td>
                            <strong>{{ number_format($bill->declared_value ?? $bill->transportLoad->price ?? 0) }}</strong>
                            <small class="text-muted d-block">تومان</small>
                        </td>
                        <td>
                            @if($bill->status === 'delivered')
                                <span class="badge bg-success">پرداخت شده</span>
                            @elseif(in_array($bill->status, ['issued', 'in_transit']))
                                <span class="badge bg-warning">در انتظار</span>
                            @elseif($bill->status === 'cancelled')
                                <span class="badge bg-danger">لغو شده</span>
                            @else
                                <span class="badge bg-secondary">{{ $bill->status }}</span>
                            @endif
                        </td>
                        <td>
                            <small>{{ $bill->created_at ? \Morilog\Jalali\Jalalian::fromDateTime($bill->created_at)->format('Y/m/d H:i') : '-' }}</small>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <a href="{{ route('admin.bills.show', $bill->id) }}" class="btn btn-outline-info" title="جزئیات">
                                    <i class="fas fa-eye"></i>
                                </a>
                                @if($bill->tracking_code)
                                    <a href="{{ route('waybill.print', $bill->tracking_code) }}" target="_blank" class="btn btn-outline-primary" title="چاپ">
                                        <i class="fas fa-print"></i>
                                    </a>
                                    <a href="{{ url('/api/waybills/public/' . $bill->tracking_code) }}" target="_blank" class="btn btn-outline-secondary" title="API عمومی">
                                        <i class="fas fa-link"></i>
                                    </a>
                                @endif
                                <button type="button" class="btn btn-outline-warning btn-postal-inquiry" title="استعلام کد پستی"
                                    data-bill-id="{{ $bill->id }}"
                                    data-origin-postal="{{ $bill->origin_postal_code }}"
                                    data-destination-postal="{{ $bill->destination_postal_code }}"
                                    data-bs-toggle="modal" data-bs-target="#postalInquiryModal">
                                    <i class="fas fa-map-pin"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center text-muted py-5">
                            <i class="fas fa-file-invoice-dollar fa-3x mb-3"></i>
                            <p class="mb-0">هیچ حواله‌ای یافت نشد</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if(isset($bills) && $bills->hasPages())
        <div class="d-flex justify-content-center mt-4">
            {{ $bills->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Postal Code Inquiry Modal -->
<div class="modal fade" id="postalInquiryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">استعلام کد پستی</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="postalInquiryForm">
                    <div class="mb-3">
                        <label class="form-label">نوع استعلام</label>
                        <div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="inquiry_type" id="byPostalCode" value="postal_code" checked>
                                <label class="form-check-label" for="byPostalCode">کد پستی</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="inquiry_type" id="byAddress" value="address">
                                <label class="form-check-label" for="byAddress">آدرس</label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="postalInquiryValue" class="form-label">مقدار</label>
                        <input type="text" class="form-control" id="postalInquiryValue" placeholder="کد پستی یا آدرس" required>
                    </div>
                    <div id="postalResults" style="display: none;">
                        <div class="alert alert-info">
                            <h6>نتایج استعلام:</h6>
                            <div id="postalResultsContent"></div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
                <button type="button" class="btn btn-primary" id="submitPostalInquiry">استعلام</button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const postalModal = document.getElementById('postalInquiryModal');
    const postalForm = document.getElementById('postalInquiryForm');
    const submitBtn = document.getElementById('submitPostalInquiry');
    const resultsDiv = document.getElementById('postalResults');
    const resultsContent = document.getElementById('postalResultsContent');

    document.querySelectorAll('.btn-postal-inquiry').forEach(btn => {
        btn.addEventListener('click', function() {
            const billId = this.dataset.billId;
            const originPostal = this.dataset.originPostal;
            const destinationPostal = this.dataset.destinationPostal;

            // Pre-populate with origin postal if available
            const inquiryValue = document.getElementById('postalInquiryValue');
            inquiryValue.value = originPostal || '';

            document.querySelector('#postalInquiryModal .modal-header .modal-title').textContent =
                `استعلام کد پستی - حواله #${billId}`;
        });
    });

    submitBtn.addEventListener('click', async function() {
        const inquiryType = document.querySelector('input[name="inquiry_type"]:checked').value;
        const inquiryValue = document.getElementById('postalInquiryValue').value;

        if (!inquiryValue) {
            alert('لطفا مقدار استعلام را وارد کنید');
            return;
        }

        try {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>درحال جستجو...';

            const response = await fetch('{{ route("admin.rmto.inquiry.postal-code") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    postal_code: inquiryValue
                })
            });

            const data = await response.json();

            if (data.success && data.data) {
                const postal = data.data;
                let html = '<table class="table table-sm"><tbody>';
                html += `<tr><th>کد پستی</th><td>${postal.PostalCode || '-'}</td></tr>`;
                html += `<tr><th>آدرس</th><td>${postal.Address || '-'}</td></tr>`;
                html += `<tr><th>شهر</th><td>${postal.City || '-'}</td></tr>`;
                html += `<tr><th>استان</th><td>${postal.Province || '-'}</td></tr>`;
                html += '</tbody></table>';
                resultsContent.innerHTML = html;
                resultsDiv.style.display = 'block';
            } else {
                alert('خطا: ' + (data.message || 'استعلام ناموفق بود'));
                resultsDiv.style.display = 'none';
            }
        } catch (error) {
            console.error('Error:', error);
            alert('خطا در برقراری ارتباط');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'استعلام';
        }
    });
});
</script>
@endpush
@endsection
