@extends('admin.layouts.app')

@section('content')
    <section class="section">
        <div class="section-header">
            <h1>إعدادات صفحة المؤسسات</h1>
            <div class="section-header-breadcrumb">
                <div class="breadcrumb-item active"><a href="/admin/">{{ trans('admin/main.dashboard') }}</a></div>
                <div class="breadcrumb-item">إعدادات صفحة المؤسسات</div>
            </div>
        </div>

        @if(session('debug_info'))
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <strong>Debug Info:</strong>
                <ul class="mb-0">
                    <li>عدد المؤسسات المحفوظة: {{ session('debug_info')['institutions_count'] }}</li>
                    <li>حجم البيانات: {{ session('debug_info')['raw_json_length'] }} bytes</li>
                </ul>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        @endif

        <div class="section-body">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <form action="/admin/additional_page/success_partners" method="post" id="success-partners-form">
                                {{ csrf_field() }}

                                <div class="row">
                                    <div class="col-12 col-md-6">
                                        <h4 class="section-title">إعدادات البانر</h4>
                                        
                                        <div class="form-group">
                                            <label class="input-label">صورة البانر</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <button type="button" class="input-group-text admin-file-manager" data-input="banner_image_record" data-preview="holder">
                                                        <i class="fa fa-chevron-up"></i>
                                                    </button>
                                                </div>
                                                <input type="text" name="value[banner_image]" id="banner_image_record" value="{{ (!empty($value) and !empty($value['banner_image'])) ? $value['banner_image'] : '' }}" class="form-control"/>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label class="input-label">عنوان البانر</label>
                                            <input type="text" name="value[banner_title]" value="{{ (!empty($value) and !empty($value['banner_title'])) ? $value['banner_title'] : 'المؤسسات' }}" class="form-control" placeholder="المؤسسات"/>
                                        </div>

                                        <div class="form-group">
                                            <label class="input-label">وصف البانر</label>
                                            <textarea name="value[banner_description]" rows="3" class="form-control" placeholder="وصف المؤسسات">{{ (!empty($value) and !empty($value['banner_description'])) ? $value['banner_description'] : '' }}</textarea>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-6">
                                        <h4 class="section-title">إعدادات العرض</h4>
                                        
                                        <div class="form-group">
                                            <label class="input-label">عدد المؤسسات المعروضة</label>
                                            <input type="number" name="value[organizations_limit]" value="{{ (!empty($value) and !empty($value['organizations_limit'])) ? $value['organizations_limit'] : '12' }}" class="form-control" min="1" max="100"/>
                                            <div class="text-muted text-small mt-1">عدد المؤسسات التي تظهر في الصفحة (افتراضي: 12)</div>
                                        </div>

                                    </div>
                                </div>

                                <div class="row mt-4">
                                    <div class="col-12">
                                        <h4 class="section-title">إعدادات SEO</h4>
                                    </div>
                                    
                                    <div class="col-12 col-md-6">
                                        <div class="form-group">
                                            <label class="input-label">عنوان الصفحة (Page Title)</label>
                                            <input type="text" name="value[seo_title]" value="{{ (!empty($value) and !empty($value['seo_title'])) ? $value['seo_title'] : 'المؤسسات' }}" class="form-control" placeholder="المؤسسات"/>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-6">
                                        <div class="form-group">
                                            <label class="input-label">وصف الصفحة (Meta Description)</label>
                                            <textarea name="value[seo_description]" rows="3" class="form-control" placeholder="وصف الصفحة لمحركات البحث">{{ (!empty($value) and !empty($value['seo_description'])) ? $value['seo_description'] : '' }}</textarea>
                                        </div>
                                    </div>
                                </div>

                                @php
                                    $institutions = !empty($value['institutions']) && is_array($value['institutions']) ? $value['institutions'] : [['name' => '', 'logo' => '', 'country' => '']];
                                @endphp

                                <div class="row mt-4">
                                    <div class="col-12">
                                        <h4 class="section-title d-flex align-items-center justify-content-between">
                                            <span>المؤسسات</span>
                                            <button type="button" class="btn btn-outline-primary btn-sm" id="addInstitution">إضافة مؤسسة</button>
                                        </h4>
                                    </div>

                                    <div class="col-12" id="institutionsList">
                                        @foreach($institutions as $key => $institution)
                                            <div class="card border rounded p-3 mb-3 institution-item">
                                                <div class="d-flex justify-content-between align-items-center mb-3">
                                                    <h5 class="mb-0">مؤسسة</h5>
                                                    <div class="d-flex gap-2">
                                                        <button type="button" class="btn btn-outline-primary btn-sm edit-institution">تعديل</button>
                                                        <button type="button" class="btn btn-danger btn-sm remove-institution">حذف</button>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-12 col-md-4">
                                                        <div class="form-group">
                                                            <label class="input-label">اسم المؤسسة</label>
                                                            <input type="text" name="value[institutions][{{ $key }}][name]" value="{{ $institution['name'] ?? '' }}" class="form-control" placeholder="اسم المؤسسة">
                                                        </div>
                                                    </div>
                                                    <div class="col-12 col-md-4">
                                                        <div class="form-group">
                                                            <label class="input-label">الدولة</label>
                                                            <input type="text" name="value[institutions][{{ $key }}][country]" value="{{ $institution['country'] ?? '' }}" class="form-control" placeholder="مثال: مصر">
                                                        </div>
                                                    </div>
                                                    <div class="col-12 col-md-4">
                                                        <div class="form-group">
                                                            <label class="input-label">شعار المؤسسة</label>
                                                            <div class="input-group">
                                                                <div class="input-group-prepend">
                                                                    <button type="button" class="input-group-text admin-file-manager" data-input="institution_logo_{{ $key }}" data-preview="holder">
                                                                        <i class="fa fa-chevron-up"></i>
                                                                    </button>
                                                                </div>
                                                                <input type="text" name="value[institutions][{{ $key }}][logo]" id="institution_logo_{{ $key }}" value="{{ $institution['logo'] ?? '' }}" class="form-control" placeholder="/store/.../logo.png">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>

                                <div class="row mt-4">
                                    <div class="col-12">
                                        <h4 class="section-title">إعدادات إضافية</h4>
                                    </div>
                                    
                                    <div class="col-12 col-md-6">
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" name="value[show_organizations]" value="1" class="custom-control-input" id="show_organizations" {{ (!empty($value) and !empty($value['show_organizations']) and $value['show_organizations'] == '1') ? 'checked' : 'checked' }}>
                                                <label class="custom-control-label" for="show_organizations">إظهار قسم المؤسسات</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="mt-4">
                                    <button type="submit" class="btn btn-primary">{{ trans('admin/main.save_change') }}</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection

@push('scripts_bottom')
    <script>
        (function () {
            const listEl = document.getElementById('institutionsList');
            const addBtn = document.getElementById('addInstitution');
            const formEl = document.getElementById('success-partners-form');
            let autoSaveTimeout = null;

            const template = `
                <div class="card border rounded p-3 mb-3 institution-item">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">مؤسسة</h5>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-outline-primary btn-sm edit-institution">تعديل</button>
                            <button type="button" class="btn btn-danger btn-sm remove-institution">حذف</button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 col-md-4">
                            <div class="form-group">
                                <label class="input-label">اسم المؤسسة</label>
                                <input type="text" name="value[institutions][__key__][name]" class="form-control" placeholder="اسم المؤسسة">
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <div class="form-group">
                                <label class="input-label">الدولة</label>
                                <input type="text" name="value[institutions][__key__][country]" class="form-control" placeholder="مثال: مصر">
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <div class="form-group">
                                <label class="input-label">شعار المؤسسة</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <button type="button" class="input-group-text admin-file-manager" data-input="institution_logo___key__" data-preview="holder">
                                            <i class="fa fa-chevron-up"></i>
                                        </button>
                                    </div>
                                    <input type="text" name="value[institutions][__key__][logo]" id="institution_logo___key__" class="form-control" placeholder="/store/.../logo.png">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            if (addBtn && listEl) {
                addBtn.addEventListener('click', function () {
                    const key = Date.now();
                    const html = template.replace(/__key__/g, key);
                    listEl.insertAdjacentHTML('beforeend', html);
                });
            }

            const scheduleAutoSave = () => {
                if (!formEl) return;
                if (autoSaveTimeout) clearTimeout(autoSaveTimeout);
                autoSaveTimeout = setTimeout(() => formEl.submit(), 500);
            };

            // Use document-level delegation to ensure clicks are caught reliably
            document.addEventListener('click', function (event) {
                const removeBtn = event.target.closest('.remove-institution');
                if (removeBtn) {
                    event.preventDefault();
                    if (!confirm('هل أنت متأكد من الحذف؟')) {
                        return;
                    }
                    const card = removeBtn.closest('.institution-item');
                    if (card) {
                        card.remove();
                        scheduleAutoSave();
                    }
                    return;
                }

                const editBtn = event.target.closest('.edit-institution');
                if (editBtn) {
                    event.preventDefault();
                    const card = editBtn.closest('.institution-item');
                    if (card) {
                        card.classList.add('border-primary', 'shadow-sm');
                        const input = card.querySelector('input, textarea');
                        if (input) input.focus();
                        setTimeout(() => card.classList.remove('border-primary', 'shadow-sm'), 1200);
                    }
                }
            });
        })();
    </script>
@endpush
