@extends('admin.layouts.app')

@section('title', 'إدارة السائقين')
@section('page-title', 'إدارة السائقين')
@section('page-icon', 'fas fa-user-tie')

<meta name="csrf-token" content="{{ csrf_token() }}">

@section('content')
{{-- إحصائيات --}}
<div class="row g-3 mb-4">
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon gold"><i class="fas fa-user-tie"></i></div>
            <div class="stat-value">{{ $stats['total'] }}</div>
            <div class="stat-label">إجمالي السائقين</div>
        </div>
    </div>
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon green"><i class="fas fa-check-circle"></i></div>
            <div class="stat-value">{{ $stats['verified'] }}</div>
            <div class="stat-label">حسابات موثقة</div>
        </div>
    </div>
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon orange"><i class="fas fa-hourglass-half"></i></div>
            <div class="stat-value">{{ $stats['verification_pending'] ?? 0 }}</div>
            <div class="stat-label">بانتظار مراجعة التوثيق</div>
        </div>
    </div>
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon blue"><i class="fas fa-car"></i></div>
            <div class="stat-value">{{ $stats['available'] }}</div>
            <div class="stat-label">متاحين</div>
        </div>
    </div>
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon orange"><i class="fas fa-route"></i></div>
            <div class="stat-value">{{ $drivers->sum(fn($d) => $d->driver->total_trips ?? 0) }}</div>
            <div class="stat-label">إجمالي الرحلات</div>
        </div>
    </div>
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon blue"><i class="fas fa-taxi"></i></div>
            <div class="stat-value">{{ $stats['by_service']['taxi'] ?? 0 }}</div>
            <div class="stat-label">تاكسي</div>
        </div>
    </div>
    <div class="col-6 col-lg-2">
        <div class="stat-card">
            <div class="stat-icon orange"><i class="fas fa-utensils"></i></div>
            <div class="stat-value">{{ $stats['by_service']['restaurant'] ?? 0 }}</div>
            <div class="stat-label">مطاعم</div>
        </div>
    </div>
</div>

{{-- فلاتر وجدول --}}
<div class="row g-3">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                <div><i class="fas fa-list"></i> قائمة السائقين</div>
                <div class="d-flex gap-2">
                    <a href="{{ route('admin.users.create') }}" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus"></i> إضافة سائق
                    </a>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" action="{{ route('admin.drivers') }}" id="driversFilterForm" class="row g-3 mb-4">
                    <div class="col-md-2">
                        <input type="text" class="form-control" name="name" placeholder="البحث بالاسم..." value="{{ request('name') }}">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">الحالة</option>
                            <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>نشط</option>
                            <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>غير نشط</option>
                            <option value="suspended" {{ request('status') == 'suspended' ? 'selected' : '' }}>معلق</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="availability">
                            <option value="">التوفر</option>
                            <option value="1" {{ request('availability') == '1' ? 'selected' : '' }}>متاح</option>
                            <option value="0" {{ request('availability') == '0' ? 'selected' : '' }}>غير متاح</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="service">
                            <option value="">الخدمة</option>
                            <option value="taxi" {{ request('service') == 'taxi' ? 'selected' : '' }}>تاكسي</option>
                            <option value="restaurant" {{ request('service') == 'restaurant' ? 'selected' : '' }}>مطاعم</option>
                            <option value="gas" {{ request('service') == 'gas' ? 'selected' : '' }}>غاز</option>
                            <option value="all" {{ request('service') == 'all' ? 'selected' : '' }}>الكل</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="verified">
                            <option value="">التوثيق</option>
                            <option value="1" {{ request('verified') == '1' ? 'selected' : '' }}>حساب موثق</option>
                            <option value="0" {{ request('verified') == '0' ? 'selected' : '' }}>غير موثق</option>
                            <option value="pending" {{ request('verified') == 'pending' ? 'selected' : '' }}>طلبات بانتظار المراجعة</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> بحث</button>
                    </div>
                </form>

                @if($drivers->count() > 0)
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>الصورة</th>
                                    <th>الاسم</th>
                                    <th>الهاتف</th>
                                    <th>المركبة</th>
                                    <th>الحالة</th>
                                    <th>متاح</th>
                                    <th>الخدمة</th>
                                    <th>الرحلات</th>
                                    <th>التقييم</th>
                                    <th>الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($drivers as $driver)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>
                                            @if($driver->profile_image)
                                                <img src="{{ asset('storage/' . $driver->profile_image) }}" class="rounded-circle" width="36" height="36" alt="">
                                            @else
                                                <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 36px; height: 36px; background: var(--dark-600);">
                                                    <i class="fas fa-user" style="color: var(--text-muted);"></i>
                                                </div>
                                            @endif
                                        </td>
                                        <td><strong>{{ $driver->name }}</strong></td>
                                        <td>{{ $driver->driver->phone ?? $driver->phone ?? 'غير محدد' }}</td>
                                        <td>
                                            @if($driver->driver && $driver->driver->vehicle)
                                                <span class="badge badge-secondary">{{ $driver->driver->vehicle->model ?? '-' }}</span>
                                            @else
                                                <span style="color: var(--text-muted);">-</span>
                                            @endif
                                        </td>
                                        <td>
                                            @switch($driver->status)
                                                @case('active') <span class="badge badge-success">نشط</span> @break
                                                @case('inactive') <span class="badge badge-secondary">غير نشط</span> @break
                                                @case('suspended') <span class="badge badge-danger">معلق</span> @break
                                                @default <span class="badge badge-secondary">{{ $driver->status ?? '-' }}</span>
                                            @endswitch
                                        </td>
                                        <td>
                                            @if($driver->driver && $driver->driver->is_available)
                                                <span class="badge badge-success">متاح</span>
                                            @else
                                                <span class="badge badge-danger">غير متاح</span>
                                            @endif
                                        </td>
                                        <td>
                                            @switch($driver->service_type)
                                                @case('taxi') <span class="badge badge-info">تاكسي</span> @break
                                                @case('restaurant') <span class="badge badge-warning">مطاعم</span> @break
                                                @case('gas') <span class="badge badge-danger">غاز</span> @break
                                                @case('all') <span class="badge badge-success">الكل</span> @break
                                                @default <span class="badge badge-secondary">-</span>
                                            @endswitch
                                        </td>
                                        <td><span class="badge badge-info">{{ $driver->driver->total_trips ?? 0 }}</span></td>
                                        <td>
                                            @if($driver->driver && $driver->driver->rating > 0)
                                                <span class="badge badge-warning">{{ number_format($driver->driver->rating, 1) }}</span>
                                                @for($i = 1; $i <= 5; $i++)
                                                    <i class="fas fa-star" style="color: var(--gold-400); font-size: 10px;"></i>
                                                @endfor
                                            @else
                                                <span style="color: var(--text-muted);">-</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <a href="{{ route('admin.drivers.show', $driver->id) }}" class="btn btn-info btn-sm" title="عرض"><i class="fas fa-eye"></i></a>
                                                <a href="{{ route('admin.users.edit', $driver->id) }}" class="btn btn-warning btn-sm" title="تعديل"><i class="fas fa-edit"></i></a>
                                                <button type="button" class="btn btn-success btn-sm" onclick="toggleAvailability({{ $driver->id }})" title="التوفر"><i class="fas fa-toggle-on"></i></button>
                                                <button type="button" class="btn btn-danger btn-sm" onclick="deleteDriver({{ $driver->id }})" title="حذف"><i class="fas fa-trash"></i></button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <div style="color: var(--text-muted); font-size: 13px;">
                            عرض {{ $drivers->firstItem() ?? 0 }} إلى {{ $drivers->lastItem() ?? 0 }} من أصل {{ $drivers->total() }}
                        </div>
                        {{ $drivers->appends(request()->query())->links('pagination::bootstrap-4') }}
                    </div>
                @else
                    <div class="empty-state">
                        <i class="fas fa-user-tie d-block"></i>
                        لا يوجد سائقين
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteModal" 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">هل أنت متأكد من حذف هذا السائق؟</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="button" class="btn btn-danger" id="confirmDelete">حذف</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
let driverToDelete = null;

function applyFilters() {
    const form = document.getElementById('driversFilterForm');
    if (form) form.submit();
}

function toggleAvailability(driverId) {
    fetch(`/admin/drivers/${driverId}/toggle-availability`, {
        method: 'PATCH',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Content-Type': 'application/json',
        },
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) location.reload();
        else alert('حدث خطأ');
    })
    .catch(() => alert('حدث خطأ'));
}

function deleteDriver(userId) {
    driverToDelete = userId;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

document.getElementById('confirmDelete').addEventListener('click', function() {
    if (driverToDelete) {
        fetch(`/admin/users/${driverToDelete}`, {
            method: 'DELETE',
            headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
        })
        .then(r => { if (r.ok) location.reload(); else alert('حدث خطأ'); })
        .catch(() => alert('حدث خطأ'));
    }
});
</script>
@endsection
