@extends('admin.layouts.app')

@section('content')
    <section class="section">
        <div class="section-header">
            <h1>{{ $pageTitle }}</h1>
            <div class="section-header-breadcrumb">
                <div class="breadcrumb-item active"><a href="/admin/">{{ trans('admin/main.dashboard') }}</a></div>
                <div class="breadcrumb-item">{{ $pageTitle }}</div>
            </div>
        </div>

        <div class="section-body">
            @if(!empty(session()->has('msg')))
                <div class="alert alert-success my-25 d-flex align-items-center">
                    <i data-feather="check-square" width="20" height="20" class="mr-2"></i>
                    {{ session()->get('msg') }}
                </div>
            @endif

            @if(!empty($tableMissing))
                <div class="alert alert-warning my-25">
                    <h4><i class="fas fa-exclamation-triangle"></i> الجدول غير موجود</h4>
                    <p>جدول <strong><code>montessori_membership_applications</code></strong> غير موجود في قاعدة البيانات.</p>
                    <p class="mb-3">يجب تشغيل المايجريشن لإنشاء الجدول أولاً.</p>
                    <div>
                        <a href="/create-montessori-table" class="btn btn-primary mt-2" target="_blank">
                            <i class="fas fa-database"></i> إنشاء الجدول الآن
                        </a>
                        <a href="{{ url()->current() }}" class="btn btn-secondary mt-2">
                            <i class="fas fa-sync-alt"></i> تحديث الصفحة
                        </a>
                    </div>
                    <div class="mt-3">
                        <small class="text-muted">
                            <strong>ملاحظة:</strong> بعد إنشاء الجدول، قم بتحديث هذه الصفحة لرؤية الطلبات.
                        </small>
                    </div>
                </div>
            @endif

            <div class="row">
                <div class="col-12 col-md-3">
                    <div class="card card-statistic-1">
                        <div class="card-icon bg-primary">
                            <i class="fas fa-list"></i>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>إجمالي الطلبات</h4>
                            </div>
                            <div class="card-body">
                                {{ $totalApplications }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-12 col-md-3">
                    <div class="card card-statistic-1">
                        <div class="card-icon bg-warning">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>قيد الانتظار</h4>
                            </div>
                            <div class="card-body">
                                {{ $pendingApplications }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-12 col-md-3">
                    <div class="card card-statistic-1">
                        <div class="card-icon bg-success">
                            <i class="fas fa-check"></i>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>مقبولة</h4>
                            </div>
                            <div class="card-body">
                                {{ $approvedApplications }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-12 col-md-3">
                    <div class="card card-statistic-1">
                        <div class="card-icon bg-danger">
                            <i class="fas fa-times"></i>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>مرفوضة</h4>
                            </div>
                            <div class="card-body">
                                {{ $rejectedApplications }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h4>قائمة طلبات العضوية</h4>
                            <div class="card-header-action">
                                <a href="/admin/additional_page/montessori_membership_applications/export{{ request()->getQueryString() ? '?' . request()->getQueryString() : '' }}" 
                                   class="btn btn-success mr-2">
                                    <i class="fas fa-file-excel"></i> تصدير Excel
                                </a>
                                <div class="card-header-form d-inline-block">
                                    <form method="GET" action="/admin/additional_page/montessori_membership_applications" class="d-inline-flex">
                                        <div class="input-group">
                                            <input type="text" name="search" class="form-control" placeholder="البحث..." value="{{ request('search') }}" style="max-width: 200px;">
                                            <select name="status" class="form-control" style="max-width: 150px;">
                                                <option value="">جميع الحالات</option>
                                                <option value="pending" {{ request('status') == 'pending' ? 'selected' : '' }}>قيد الانتظار</option>
                                                <option value="approved" {{ request('status') == 'approved' ? 'selected' : '' }}>مقبولة</option>
                                                <option value="rejected" {{ request('status') == 'rejected' ? 'selected' : '' }}>مرفوضة</option>
                                            </select>
                                            <div class="input-group-btn">
                                                <button class="btn btn-primary"><i class="fas fa-search"></i></button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped font-14">
                                    <tr>
                                        <th>#</th>
                                        @php
                                            // Get field labels from settings for table headers
                                            $settings = \App\Models\Setting::where('name', 'montessori_membership')->first();
                                            $formFields = [];
                                            if (!empty($settings) && !empty($settings->value)) {
                                                $settingsData = json_decode($settings->value, true);
                                                $formFields = $settingsData['form_fields'] ?? [];
                                            }
                                            // Show first 4 fields as headers (excluding files)
                                            $displayFields = [];
                                            foreach ($formFields as $field) {
                                                if (count($displayFields) < 4 && (!isset($field['type']) || $field['type'] != 'file')) {
                                                    $displayFields[] = $field;
                                                }
                                            }
                                        @endphp
                                        @foreach($displayFields as $field)
                                            <th>{{ $field['label'] ?? 'غير محدد' }}</th>
                                        @endforeach
                                        <th class="text-center">الحالة</th>
                                        <th class="text-center">تاريخ التسجيل</th>
                                        <th>الإجراءات</th>
                                    </tr>

                                    @forelse($applications as $application)
                                        @php
                                            $formData = is_array($application->form_data) ? $application->form_data : json_decode($application->form_data, true);
                                            
                                            // Get values for the first 4 fields from settings
                                            $displayValues = [];
                                            foreach ($displayFields as $field) {
                                                $fieldName = $field['name'] ?? '';
                                                $value = 'غير محدد';
                                                
                                                if (!empty($fieldName) && isset($formData[$fieldName])) {
                                                    $val = $formData[$fieldName];
                                                    if (is_string($val) && !Str::startsWith($val, '/store/')) {
                                                        $value = Str::limit($val, 40);
                                                    } elseif (is_string($val) && Str::startsWith($val, '/store/')) {
                                                        $value = '📎 ملف';
                                                    }
                                                }
                                                
                                                $displayValues[] = $value;
                                            }
                                        @endphp
                                        <tr>
                                            <td>{{ $application->id }}</td>
                                            @foreach($displayValues as $value)
                                                <td>{{ $value }}</td>
                                            @endforeach
                                            <td class="text-center">
                                                <span class="badge badge-{{ $application->status == 'approved' ? 'success' : ($application->status == 'pending' ? 'warning' : 'danger') }}">
                                                    @if($application->status == 'approved')
                                                        مقبولة
                                                    @elseif($application->status == 'pending')
                                                        قيد الانتظار
                                                    @else
                                                        مرفوضة
                                                    @endif
                                                </span>
                                            </td>
                                            <td class="text-center">{{ date('Y-m-d H:i', $application->created_at) }}</td>
                                            <td>
                                                <a href="/admin/additional_page/montessori_membership_applications/{{ $application->id }}" class="btn btn-sm btn-transparent text-primary mr-1" data-toggle="tooltip" title="عرض التفاصيل">
                                                    <i class="fa fa-eye"></i>
                                                </a>
                                                <form action="/admin/additional_page/montessori_membership_applications/{{ $application->id }}/update-status" method="POST" style="display: inline-block;" class="mr-1">
                                                    {{ csrf_field() }}
                                                    <select name="status" onchange="this.form.submit()" class="form-control form-control-sm" style="width: auto; display: inline-block;">
                                                        <option value="pending" {{ $application->status == 'pending' ? 'selected' : '' }}>قيد الانتظار</option>
                                                        <option value="approved" {{ $application->status == 'approved' ? 'selected' : '' }}>قبول</option>
                                                        <option value="rejected" {{ $application->status == 'rejected' ? 'selected' : '' }}>رفض</option>
                                                    </select>
                                                </form>
                                                <a href="/admin/additional_page/montessori_membership_applications/{{ $application->id }}/delete" class="btn btn-sm btn-transparent text-danger" data-toggle="tooltip" title="حذف" onclick="return confirm('هل أنت متأكد من الحذف؟');">
                                                    <i class="fa fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="8" class="text-center">لا توجد طلبات مسجلة</td>
                                        </tr>
                                    @endforelse
                                </table>
                            </div>
                        </div>

                        <div class="card-footer text-center">
                            {{ $applications->appends(request()->input())->links() }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection
