@extends('admin.layouts.app')

@push('styles_top')
    <link rel="stylesheet" href="/assets/default/vendors/sweetalert2/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="/assets/default/vendors/daterangepicker/daterangepicker.min.css">
    <link rel="stylesheet" href="/assets/default/vendors/bootstrap-timepicker/bootstrap-timepicker.min.css">
    <link rel="stylesheet" href="/assets/default/vendors/select2/select2.min.css">
    <link rel="stylesheet" href="/assets/default/vendors/bootstrap-tagsinput/bootstrap-tagsinput.min.css">
    <link rel="stylesheet" href="/assets/vendors/summernote/summernote-bs4.min.css">
    <link href="/assets/default/vendors/sortable/jquery-ui.min.css"/>
    <style>
        .bootstrap-timepicker-widget table td input {
            width: 35px !important;
        }

        .select2-container {
            z-index: 1212 !important;
        }
        /* Ensure the dropdown itself appears above modals/overlays */
        .select2-container--open .select2-dropdown {
            z-index: 2005 !important;
        }
    </style>
@endpush

@section('content')
    <section class="section">
        <div class="section-header">
            <h1>{{ !empty($webinar) ?trans('/admin/main.edit'): trans('admin/main.new') }} {{ trans('admin/main.class') }}</h1>
            <div class="section-header-breadcrumb">
                <div class="breadcrumb-item active"><a href="/admin/">{{ trans('admin/main.dashboard') }}</a>
                </div>
                <div class="breadcrumb-item active">
                    <a href="/admin/webinars">{{ trans('admin/main.classes') }}</a>
                </div>
                <div class="breadcrumb-item">{{ !empty($webinar) ?trans('/admin/main.edit'): trans('admin/main.new') }}</div>
            </div>
        </div>

        <div class="section-body">

            <div class="row">
                <div class="col-12 ">
                    <div class="card">
                        <div class="card-body">

                            <form method="post" action="/admin/webinars/{{ !empty($webinar) ? $webinar->id.'/update' : 'store' }}" id="webinarForm" class="webinar-form">
                                {{ csrf_field() }}
<section>
                                    <h2 class="section-title after-line">{{ trans('public.basic_information') }}</h2>

                                    <div class="row">
                                        <div class="col-12 col-md-5">

                                            @if(!empty(getGeneralSettings('content_translate')))
                                                <div class="form-group">
                                                    <label class="input-label">{{ trans('auth.language') }}</label>
                                                    <select name="locale" class="form-control {{ !empty($webinar) ? 'js-edit-content-locale' : '' }}">
                                                        @foreach($userLanguages as $lang => $language)
                                                            <option value="{{ $lang }}" @if(mb_strtolower(request()->get('locale', app()->getLocale())) == mb_strtolower($lang)) selected @endif>{{ $language }}</option>
                                                        @endforeach
                                                    </select>
                                                    @error('locale')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}

                                                    </div>
                                                    @enderror
                                                </div>
                                            @else
                                                <input type="hidden" name="locale" value="{{ getDefaultLocale() }}">
                                            @endif

                                            <div class="form-group mt-15 ">
                                                <label class="input-label d-block">{{ trans('panel.course_type') }}</label>

                                                <select name="type" class="custom-select @error('type')  is-invalid @enderror">
                                                    <option value="webinar" @if((!empty($webinar) and $webinar->isWebinar()) or old('type') == \App\Models\Webinar::$webinar) selected @endif>{{ trans('webinars.webinar') }}</option>
                                                    <option value="course" @if((!empty($webinar) and $webinar->isCourse()) or old('type') == \App\Models\Webinar::$course) selected @endif>{{ trans('product.video_course') }}</option>
                                                    <option value="text_lesson" @if((!empty($webinar) and $webinar->isTextCourse()) or old('type') == \App\Models\Webinar::$textLesson) selected @endif>{{ trans('product.text_course') }}</option>
                                                </select>

                                                @error('type')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>

                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.title') }}</label>
                                                <input type="text" name="title" value="{{ !empty($webinar) ? $webinar->title : old('title') }}" class="form-control @error('title')  is-invalid @enderror" placeholder=""/>
                                                @error('title')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>
                                            
                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.certified_from') }}</label>
                                                <input type="text" name="certified_from" value="{{ !empty($webinar) ? $webinar->certified_from : old('certified_from') }}" class="form-control @error('certified_from')  is-invalid @enderror" placeholder=""/>
                                                @error('certified_from')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>
                                            
                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.age_level') }}</label>
                                                <input type="text" name="age_level" value="{{ !empty($webinar) ? $webinar->age_level : old('age_level') }}" class="form-control @error('age_level')  is-invalid @enderror" placeholder=""/>
                                                @error('age_level')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>
                                            
                                             <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.order_show') }}</label>
                                                <input type="number" name="order_show" value="{{ !empty($webinar) ? $webinar->order_show : old('order_show') }}" class="form-control @error('order_show')  is-invalid @enderror" placeholder=""/>
                                                @error('order_show')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>
                                           

                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('update.points') }}</label>
                                                <input type="text" name="points" value="{{ !empty($webinar) ? $webinar->points : old('points') }}" class="form-control @error('points')  is-invalid @enderror" placeholder="Empty means inactive this mode"/>
                                                @error('points')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>

                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('admin/main.class_url') }}</label>
                                                <input type="text" name="slug" value="{{ !empty($webinar) ? $webinar->slug : old('slug') }}" class="form-control @error('slug')  is-invalid @enderror" placeholder=""/>
                                                <div class="text-muted text-small mt-1">{{ trans('admin/main.class_url_hint') }}</div>
                                                @error('slug')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>

                                            @if(!empty($webinar) and $webinar->creator->isOrganization())
                                                <div class="form-group mt-15 ">
                                                    <label class="input-label d-block">{{ trans('admin/main.organization') }}</label>

                                                    <select class="form-control" disabled readonly data-placeholder="{{ trans('public.search_instructor') }}">
                                                        <option selected>{{ $webinar->creator->full_name }}</option>
                                                    </select>
                                                </div>
                                            @endif


                                            <div class="form-group mt-15 ">
                                                <label class="input-label d-block">{{ trans('admin/main.select_a_instructor') }}</label>

                                                <select name="teacher_id" data-search-option="just_teacher_role" class="form-control search-user-select2"
                                                        data-placeholder="{{ trans('public.select_a_teacher') }}"
                                                >
                                                    @if(!empty($webinar))
                                                        <option value="{{ $webinar->teacher->id }}" selected>{{ $webinar->teacher->full_name }}</option>
                                                    @else
                                                        <option selected disabled>{{ trans('public.select_a_teacher') }}</option>
                                                    @endif
                                                </select>

                                                @error('teacher_id')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>


                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.seo_description') }}</label>
                                                <input type="text" name="seo_description" value="{{ !empty($webinar) ? $webinar->seo_description : old('seo_description') }}" class="form-control @error('seo_description')  is-invalid @enderror"/>
                                                <div class="text-muted text-small mt-1">{{ trans('admin/main.seo_description_hint') }}</div>
                                                @error('seo_description')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>

                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.thumbnail_image') }}</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <button type="button" class="input-group-text admin-file-manager" data-input="thumbnail" data-preview="holder">
                                                            <i class="fa fa-upload"></i>
                                                        </button>
                                                    </div>
                                                    <input type="text" name="thumbnail" id="thumbnail" value="{{ !empty($webinar) ? $webinar->thumbnail : old('thumbnail') }}" class="form-control @error('thumbnail')  is-invalid @enderror"/>
                                                    <div class="input-group-append">
                                                        <button type="button" class="input-group-text admin-file-view" data-input="thumbnail">
                                                            <i class="fa fa-eye"></i>
                                                        </button>
                                                    </div>
                                                    @error('thumbnail')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}

                                                    </div>
                                                    @enderror
                                                </div>
                                            </div>


                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.cover_image') }}</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <button type="button" class="input-group-text admin-file-manager" data-input="cover_image" data-preview="holder">
                                                            <i class="fa fa-upload"></i>
                                                        </button>
                                                    </div>
                                                    <input type="text" name="image_cover" id="cover_image" value="{{ !empty($webinar) ? $webinar->image_cover : old('image_cover') }}" class="form-control @error('image_cover')  is-invalid @enderror"/>
                                                    <div class="input-group-append">
                                                        <button type="button" class="input-group-text admin-file-view" data-input="cover_image">
                                                            <i class="fa fa-eye"></i>
                                                        </button>
                                                    </div>
                                                    @error('image_cover')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}

                                                    </div>
                                                    @enderror
                                                </div>
                                            </div>

                                            <div class="form-group mt-25">
                                                <label class="input-label">{{ trans('public.demo_video') }} ({{ trans('public.optional') }})</label>


                                                <div class="">
                                                    <label class="input-label font-12">{{ trans('public.source') }}</label>
                                                    <select name="video_demo_source"
                                                            class="js-video-demo-source form-control"
                                                    >
                                                        @foreach(\App\Models\Webinar::$videoDemoSource as $source)
                                                            <option value="{{ $source }}" @if(!empty($webinar) and $webinar->video_demo_source == $source): ?> selected @endif>{{ trans('update.file_source_'.$source) }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="form-group mt-0">
                                                <label class="input-label font-12">{{ trans('update.path') }}</label>
                                                <div class="input-group js-video-demo-path-input">
                                                    <div class="input-group-prepend">
                                                        <button type="button" class="js-video-demo-path-upload input-group-text admin-file-manager {{ (empty($webinar) or empty($webinar->video_demo_source) or $webinar->video_demo_source == 'upload') ? '' : 'd-none' }}" data-input="demo_video" data-preview="holder">
                                                            <i class="fa fa-upload"></i>
                                                        </button>

                                                        <button type="button" class="js-video-demo-path-links rounded-left input-group-text input-group-text-rounded-left  {{ (empty($webinar) or empty($webinar->video_demo_source) or $webinar->video_demo_source == 'upload') ? 'd-none' : '' }}">
                                                            <i class="fa fa-link"></i>
                                                        </button>
                                                    </div>
                                                    <input type="text" name="video_demo" id="demo_video" value="{{ !empty($webinar) ? $webinar->video_demo : old('video_demo') }}" class="form-control @error('video_demo')  is-invalid @enderror"/>
                                                    @error('video_demo')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}

                                                    </div>
                                                    @enderror
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-12">
                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.description') }}</label>
                                                <textarea id="summernote" name="description" class="form-control @error('description')  is-invalid @enderror" placeholder="{{ trans('forms.webinar_description_placeholder') }}">{{ !empty($webinar) ? $webinar->description : old('description') }}</textarea>
                                                @error('description')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="form-group mt-15">
                                                <label class="input-label">الوصف الاخر</label>
                                                <textarea id="summernote" name="description_2" class="form-control @error('description_2')  is-invalid @enderror" placeholder="{{ trans('forms.webinar_description_placeholder') }}">{{ !empty($webinar) ? $webinar->description_2 : old('description_2') }}</textarea>
                                                @error('description_2')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>
                                        </div>
                                    </div>
                                </section>

                                <section class="mt-3">
                                    <h2 class="section-title after-line">{{ trans('public.additional_information') }}</h2>
                                    <div class="row">
                                        <div class="col-12 col-md-6">

                                            @if(empty($webinar) or (!empty($webinar) and $webinar->isWebinar()))

                                                <div class="form-group mt-15 js-capacity {{ (!empty(old('type')) and old('type') != \App\Models\Webinar::$webinar) ? 'd-none' : '' }}">
                                                    <label class="input-label">{{ trans('public.capacity') }}</label>
                                                    <input type="number" name="capacity" value="{{ !empty($webinar) ? $webinar->capacity : old('capacity') }}" class="form-control @error('capacity')  is-invalid @enderror"/>
                                                    @error('capacity')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}

                                                    </div>
                                                    @enderror
                                                </div>
                                            @endif

                                            <div class="row mt-15">
                                                @if(empty($webinar) or (!empty($webinar) and $webinar->isWebinar()))
                                                    <div class="col-12 col-md-6 js-start_date {{ (!empty(old('type')) and old('type') != \App\Models\Webinar::$webinar) ? 'd-none' : '' }}">
                                                        <div class="form-group">
                                                            <label class="input-label">{{ trans('public.start_date') }}</label>
                                                            <div class="input-group">
                                                                <div class="input-group-prepend">
                                                                    <span class="input-group-text" id="dateInputGroupPrepend">
                                                                        <i class="fa fa-calendar-alt "></i>
                                                                    </span>
                                                                </div>
                                                                <input type="text" name="start_date" value="{{ (!empty($webinar) and $webinar->start_date) ? dateTimeFormat($webinar->start_date, 'Y-m-d H:i', false, false, $webinar->timezone) : old('start_date') }}" class="form-control @error('start_date')  is-invalid @enderror datetimepicker" aria-describedby="dateInputGroupPrepend"/>
                                                                @error('start_date')
                                                                <div class="invalid-feedback">
                                                                    {{ $message }}

                                                                </div>
                                                                @enderror
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endif

                                                <div class="col-12 col-md-6">
                                                    <div class="form-group">
                                                        <label class="input-label">{{ trans('public.duration') }} ({{ trans('public.minutes') }})</label>
                                                        <div class="input-group">
                                                            <div class="input-group-prepend">
                                                                <span class="input-group-text" id="timeInputGroupPrepend">
                                                                    <i class="fa fa-clock"></i>
                                                                </span>
                                                            </div>


                                                            <input type="text" name="duration" value="{{ !empty($webinar) ? $webinar->duration : old('duration') }}" class="form-control @error('duration')  is-invalid @enderror"/>
                                                            @error('duration')
                                                            <div class="invalid-feedback">
                                                                {{ $message }}

                                                            </div>
                                                            @enderror
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            @if(getFeaturesSettings('timezone_in_create_webinar'))
                                                @php
                                                    $selectedTimezone = getGeneralSettings('default_time_zone');

                                                    if (!empty($webinar) and !empty($webinar->timezone)) {
                                                        $selectedTimezone = $webinar->timezone;
                                                    }
                                                @endphp

                                                <div class="form-group">
                                                    <label class="input-label">{{ trans('update.timezone') }}</label>
                                                    <select name="timezone" class="form-control select2" data-allow-clear="false">
                                                        @foreach(getListOfTimezones() as $timezone)
                                                            <option value="{{ $timezone }}" @if($selectedTimezone == $timezone) selected @endif>{{ $timezone }}</option>
                                                        @endforeach
                                                    </select>
                                                    @error('timezone')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}

                                                    </div>
                                                    @enderror
                                                </div>
                                            @endif

                                            @if(!empty($webinar) and $webinar->creator->isOrganization())
                                                <div class="form-group mt-30 d-flex align-items-center justify-content-between">
                                                    <label class="" for="privateSwitch">{{ trans('webinars.private') }}</label>
                                                    <div class="custom-control custom-switch">
                                                        <input type="checkbox" name="private" class="custom-control-input" id="privateSwitch" {{ (!empty($webinar) and $webinar->private) ? 'checked' :  '' }}>
                                                        <label class="custom-control-label" for="privateSwitch"></label>
                                                    </div>
                                                </div>
                                            @endif

                                            <div class="form-group mt-30 d-flex align-items-center justify-content-between">
                                                <label class="" for="supportSwitch">{{ trans('panel.support') }}</label>
                                                <div class="custom-control custom-switch">
                                                    <input type="checkbox" name="support" class="custom-control-input" id="supportSwitch" {{ !empty($webinar) && $webinar->support ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="supportSwitch"></label>
                                                </div>
                                            </div>

                                            <div class="form-group mt-30 d-flex align-items-center justify-content-between">
                                                <label class="cursor-pointer" for="downloadableSwitch">{{ trans('home.downloadable') }}</label>
                                                <div class="custom-control custom-switch">
                                                    <input type="checkbox" name="downloadable" class="custom-control-input" id="downloadableSwitch" {{ !empty($webinar) && $webinar->downloadable ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="downloadableSwitch"></label>
                                                </div>
                                            </div>

                                            <div class="form-group mt-30 d-flex align-items-center justify-content-between">
                                                <label class="" for="partnerInstructorSwitch">{{ trans('public.partner_instructor') }}</label>
                                                <div class="custom-control custom-switch">
                                                    <input type="checkbox" name="partner_instructor" class="custom-control-input" id="partnerInstructorSwitch" {{ !empty($webinar) && $webinar->partner_instructor ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="partnerInstructorSwitch"></label>
                                                </div>
                                            </div>

                                            <div class="form-group mt-30 d-flex align-items-center justify-content-between">
                                                <label class="" for="forumSwitch">{{ trans('update.course_forum') }}</label>
                                                <div class="custom-control custom-switch">
                                                    <input type="checkbox" name="forum" class="custom-control-input" id="forumSwitch" {{ !empty($webinar) && $webinar->forum ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="forumSwitch"></label>
                                                </div>
                                            </div>

                                            <div class="form-group mt-30 d-flex align-items-center justify-content-between">
                                                <label class="" for="subscribeSwitch">{{ trans('public.subscribe') }}</label>
                                                <div class="custom-control custom-switch">
                                                    <input type="checkbox" name="subscribe" class="custom-control-input" id="subscribeSwitch" {{ !empty($webinar) && $webinar->subscribe ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="subscribeSwitch"></label>
                                                </div>
                                            </div>

                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('update.access_days') }}</label>
                                                <input type="text" name="access_days" value="{{ !empty($webinar) ? $webinar->access_days : old('access_days') }}" class="form-control @error('access_days')  is-invalid @enderror"/>
                                                @error('access_days')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                                <p class="mt-1">- {{ trans('update.access_days_input_hint') }}</p>
                                            </div>

                                            <div class="form-group mt-15">
                                                @include('admin.includes.currency_select', ['model' => $webinar ?? null])

                                                <label class="input-label">{{ trans('public.price') }}</label>
                                                <input type="text" name="price" value="{{ !empty($webinar) ? $webinar->price : old('price') }}" class="form-control @error('price')  is-invalid @enderror" placeholder="{{ trans('public.0_for_free') }}"/>
                                                @error('price')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>

                                            <div id="partnerInstructorInput" class="form-group mt-15 {{ !empty($webinar) && $webinar->partner_instructor ? '' : 'd-none' }}">
                                                <label class="input-label d-block">{{ trans('public.select_a_partner_teacher') }}</label>

                                                <select name="partners[]" multiple data-search-option="just_teacher_role" class="form-control search-user-select2"
                                                        data-placeholder="{{ trans('public.search_instructor') }}"
                                                >
                                                    @if(!empty($webinarPartnerTeacher))
                                                        @foreach($webinarPartnerTeacher as $partner)
                                                            @if(!empty($partner) and $partner->teacher): ?>
                                                                <option value="{{ $partner->teacher->id }}" selected>{{ $partner->teacher->full_name }}</option>
                                                            @endif
                                                        @endforeach
                                                    @else
                                                        <option selected disabled>{{ trans('public.search_instructor') }}</option>
                                                    @endif
                                                </select>

                                                <div class="text-muted text-small mt-1">{{ trans('admin/main.select_a_partner_hint') }}</div>
                                            </div>

                                            <div class="form-group mt-15">
                                                <label class="input-label d-block">{{ trans('public.tags') }}</label>
                                                <input type="text" name="tags" data-max-tag="200" value="{{ !empty($webinar) ? implode(',',$webinarTags) : '' }}" class="form-control inputtags" placeholder="{{ trans('public.type_tag_name_and_press_enter') }}"/>
                                            </div>


                                            <div class="form-group mt-15">
                                                <label class="input-label">{{ trans('public.category') }}</label>

                                                <select id="categories" class="custom-select @error('category_id')  is-invalid @enderror" name="category_id" required>
                                                    <option {{ !empty($webinar) ? '' : 'selected' }} disabled>{{ trans('public.choose_category') }}</option>
                                                    @foreach($categories as $category)
                                                        @if(!empty($category->subCategories) and count($category->subCategories))
                                                            <optgroup label="{{ $category->title }}">
                                                                @foreach($category->subCategories as $subCategory)
                                                                    <option value="{{ $subCategory->id }}" {{ (!empty($webinar) and $webinar->category_id == $subCategory->id) ? 'selected' : '' }}>{{ $subCategory->title }}</option>
                                                                @endforeach
                                                            </optgroup>
                                                        @else
                                                            <option value="{{ $category->id }}" {{ (!empty($webinar) and $webinar->category_id == $category->id) ? 'selected' : '' }}>{{ $category->title }}</option>
                                                        @endif
                                                    @endforeach
                                                </select>

                                                @error('category_id')
                                                <div class="invalid-feedback">
                                                    {{ $message }}

                                                </div>
                                                @enderror
                                            </div>

                                        </div>
                                    </div>

                                    <div class="form-group mt-15 {{ (!empty($webinarCategoryFilters) and count($webinarCategoryFilters)) ? '' : 'd-none' }}" id="categoriesFiltersContainer">
                                        <span class="input-label d-block">{{ trans('public.category_filters') }}</span>
                                        <div id="categoriesFiltersCard" class="row mt-3">

                                            @if(!empty($webinarCategoryFilters) and count($webinarCategoryFilters))
                                                @foreach($webinarCategoryFilters as $filter)
                                                    <div class="col-12 col-md-3">
                                                        <div class="webinar-category-filters">
                                                            <strong class="category-filter-title d-block">{{ $filter->title }}</strong>
                                                            <div class="py-10"></div>

                                                            @foreach($filter->options as $option)
                                                                <div class="form-group mt-3 d-flex align-items-center justify-content-between">
                                                                    <label class="text-gray font-14" for="filterOptions{{ $option->id }}">{{ $option->title }}</label>
                                                                    <div class="custom-control custom-checkbox">
                                                                        <input type="checkbox" name="filters[]" value="{{ $option->id }}" {{ ((!empty($webinarFilterOptions) && in_array($option->id,$webinarFilterOptions)) ? 'checked' : '') }} class="custom-control-input" id="filterOptions{{ $option->id }}">
                                                                        <label class="custom-control-label" for="filterOptions{{ $option->id }}"></label>
                                                                    </div>
                                                                </div>
                                                            @endforeach
                                                        </div>
                                                    </div>
                                                @endforeach
                                            @endif

                                        </div>
                                    </div>
                                </section>

                                @if(!empty($webinar))
                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">{{ trans('admin/main.price_plans') }}</h2>
                                            <button id="webinarAddTicket" type="button" class="btn btn-primary btn-sm mt-3">{{ trans('admin/main.add_price_plan') }}</button>
                                        </div>

                                        <div class="row mt-10">
                                            <div class="col-12">

                                                @if(!empty($tickets) and !$tickets->isEmpty())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">

                                                            <tr>
                                                                <th>{{ trans('public.title') }}</th>
                                                                <th>{{ trans('public.discount') }}</th>
                                                                <th>{{ trans('public.capacity') }}</th>
                                                                <th>{{ trans('public.date') }}</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($tickets as $ticket)
                                                                <tr>
                                                                    <th scope="row">{{ $ticket->title }}</th>
                                                                    <td>{{ $ticket->discount }}%</td>
                                                                    <td>{{ $ticket->capacity }}</td>
                                                                    <td>{{ dateTimeFormat($ticket->start_date,'j F Y') }} - {{ (new DateTime())->setTimestamp($ticket->end_date)->format('j F Y') }}</td>
                                                                    <td>
                                                                        <button type="button" data-ticket-id="{{ $ticket->id }}" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}" class="edit-ticket btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>

                                                                        @include('admin.includes.delete_button',['url' => '/admin/tickets/'. $ticket->id .'/delete', 'btnClass' => ' mt-1'])
                                                                    </td>
                                                                </tr>
                                                            @endforeach

                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'ticket.png',
                                                        'title' => trans('public.ticket_no_result'),
                                                        'hint' => trans('public.ticket_no_result_hint'),
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>


                                    @include('admin.webinars.create_includes.contents')


                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">{{ trans('public.prerequisites') }}</h2>
                                            <button id="webinarAddPrerequisites" type="button" class="btn btn-primary btn-sm mt-3">{{ trans('public.add_prerequisites') }}</button>
                                        </div>

                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if(!empty($prerequisites) and !$prerequisites->isEmpty())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">

                                                            <tr>
                                                                <th>{{ trans('public.title') }}</th>
                                                                <th class="text-left">{{ trans('public.instructor') }}</th>
                                                                <th>{{ trans('public.price') }}</th>
                                                                <th>{{ trans('public.publish_date') }}</th>
                                                                <th>{{ trans('public.forced') }}</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($prerequisites as $prerequisite)
                                                                @if(!empty($prerequisite->prerequisiteWebinar->title))
                                                                    <tr>
                                                                        <th>{{ $prerequisite->prerequisiteWebinar->title }}</th>
                                                                        <td class="text-left">{{ $prerequisite->prerequisiteWebinar->teacher->full_name }}</td>
                                                                        <td>{{ addCurrencyToPrice(handlePriceFormat($prerequisite->prerequisiteWebinar->price)) }}</td>
                                                                        <td>{{ dateTimeFormat($prerequisite->prerequisiteWebinar->created_at,'j F Y | H:i') }}</td>
                                                                        <td>{{ $prerequisite->required ? trans('public.yes') : trans('public.no') }}</td>

                                                                        <td>
                                                                            <button type="button" data-prerequisite-id="{{ $prerequisite->id }}" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}" class="edit-prerequisite btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                                <i class="fa fa-edit"></i>
                                                                            </button>

                                                                            @include('admin.includes.delete_button',['url' => '/admin/prerequisites/'. $prerequisite->id .'/delete', 'btnClass' => ' mt-1'])
                                                                        </td>
                                                                    </tr>
                                                                @endif
                                                            @endforeach

                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'comment.png',
                                                        'title' => trans('public.prerequisites_no_result'),
                                                        'hint' => trans('public.prerequisites_no_result_hint'),
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>
                                    
                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">محاور الدبلوم</h2>
                                            <button id="webinarAddForItems" type="button" class="btn btn-primary btn-sm mt-3">إضافة محور للدبلوم</button>
                                        </div>

                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if($webinar->for_items()->count())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">
                                                            <tr>
                                                                <th>الأيقونة</th>
                                                                <th>النص</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($webinar->for_items()->get() as $item)
                                                                <tr>
                                                                    <td>{{ $item->icon ?? 'users' }}</td>
                                                                    <th>{{ $item->description }}</th>
                                                                    <td>
                                                                        <button type="button" data-item-id="{{ $item->id }}" class="edit-for-item btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>
                                                                        @include('admin.includes.delete_button',['url' => '/admin/webinar-for-items/'. $item->id .'/delete', 'btnClass' => ' mt-1'])
                                                                    </td>
                                                                </tr>
                                                            @endforeach
                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'comment.png',
                                                        'title' => 'لا توجد عناصر',
                                                        'hint' => 'قم بإنشاء محاور الدبلوم',
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>

                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">مزايا الالتحاق بالدبلوم</h2>
                                            <button id="webinarAddFeatures" type="button" class="btn btn-primary btn-sm mt-3">إضافة ميزة للالتحاق بالدبلوم</button>
                                        </div>

                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if($webinar->features()->count())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">
                                                            <tr>
                                                                <th>النص</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($webinar->features()->get() as $feature)
                                                                <tr>
                                                                    <th>{{ $feature->description }}</th>
                                                                    <td>
                                                                        <button type="button" data-item-id="{{ $feature->id }}" class="edit-feature btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>
                                                                        @include('admin.includes.delete_button',['url' => '/admin/webinar-features/'. $feature->id .'/delete', 'btnClass' => ' mt-1'])
                                                                    </td>
                                                                </tr>
                                                            @endforeach
                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'comment.png',
                                                        'title' => 'لا توجد مزايا',
                                                        'hint' => 'قم بإنشاء مزايا للالتحاق بالدبلوم',
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>

                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">الأكاديمية تحتوي على</h2>
                                            <button id="webinarEditAcademySection" type="button" class="btn btn-primary btn-sm mt-3" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}">تعديل قسم الأكاديمية</button>
                                        </div>

                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @php
                                                    $academySection = !empty($webinar) ? $webinar->academy_section : null;
                                                @endphp
                                                @if(!empty($academySection) && $academySection->status)
                                                    <div class="alert alert-info">
                                                        <strong>عنوان القسم:</strong> {{ $academySection->title ?? 'الأكاديمية تحتوي على' }}
                                                        <br>
                                                        <strong>عدد الصناديق:</strong> {{ $academySection->boxes->count() ?? 0 }}
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'comment.png',
                                                        'title' => 'لا يوجد قسم أكاديمية',
                                                        'hint' => 'قم بإضافة قسم الأكاديمية للدبلوم',
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>

                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">{{ trans('webinars.admin_instructor_highlights_section') }}</h2>
                                            <button id="webinarEditInstructorHighlights" type="button" class="btn btn-primary btn-sm mt-3" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}">{{ trans('webinars.admin_instructor_highlights_edit') }}</button>
                                        </div>
                                        <p class="text-gray font-13 mt-10 mb-0">{{ trans('webinars.admin_instructor_highlights_hint') }}</p>
                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if(!empty($webinar) && \Illuminate\Support\Facades\Schema::hasTable('webinar_instructor_highlights') && $webinar->instructor_highlights()->count())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">
                                                            <tr>
                                                                <th>{{ trans('webinars.admin_instructor_highlights_icon') }}</th>
                                                                <th>{{ trans('webinars.admin_instructor_highlights_value') }}</th>
                                                                <th>{{ trans('webinars.admin_instructor_highlights_label') }}</th>
                                                                <th></th>
                                                            </tr>
                                                            @foreach($webinar->instructor_highlights as $highlight)
                                                                <tr>
                                                                    <td>{{ $highlight->icon }}</td>
                                                                    <td>{{ $highlight->value }}</td>
                                                                    <td>{{ $highlight->label }}</td>
                                                                    <td>
                                                                        <button type="button" class="edit-instructor-highlights btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>
                                                                    </td>
                                                                </tr>
                                                            @endforeach
                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'comment.png',
                                                        'title' => trans('webinars.admin_instructor_highlights_empty_title'),
                                                        'hint' => trans('webinars.admin_instructor_highlights_empty_hint'),
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>

                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">ماذا ستتعلم في هذا الدبلوم</h2>
                                            <button id="webinarAddInstructorTestimonials" type="button" class="btn btn-primary btn-sm mt-3">إضافة نقطة تعلّم</button>
                                        </div>
                                        <p class="text-gray font-13 mt-10 mb-0">{{ trans('webinars.admin_instructor_testimonials_hint') }}</p>

                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if($webinar->instructor_testimonials()->count())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">
                                                            <tr>
                                                                <th>الاسم</th>
                                                                <th>الرأى</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($webinar->instructor_testimonials()->get() as $testim)
                                                                <tr>
                                                                    <th>{{ $testim->name }}</th>
                                                                    <th>{{ $testim->comment }}</th>
                                                                    <td>
                                                                        <button type="button" data-item-id="{{ $testim->id }}" class="edit-instructor-testimonial btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>
                                                                        @include('admin.includes.delete_button',['url' => '/admin/webinar-instructor-testimonials/'. $testim->id .'/delete', 'btnClass' => ' mt-1'])
                                                                    </td>
                                                                </tr>
                                                            @endforeach
                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'comment.png',
                                                        'title' => 'لا توجد أراء',
                                                        'hint' => 'قم بإنشاء نقاط «ماذا ستتعلم» للدبلوم',
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>

                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">{{ trans('public.faq') }}</h2>
                                            <button id="webinarAddFAQ" type="button" class="btn btn-primary btn-sm mt-3">{{ trans('public.add_faq') }}</button>
                                        </div>

                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if(!empty($faqs) and !$faqs->isEmpty())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">

                                                            <tr>
                                                                <th>{{ trans('public.title') }}</th>
                                                                <th>{{ trans('public.answer') }}</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($faqs as $faq)
                                                                <tr>
                                                                    <th>{{ $faq->title }}</th>
                                                                    <td>
                                                                        <button type="button" class="js-get-faq-description btn btn-sm btn-gray200">{{ trans('public.view') }}</button>
                                                                        <input type="hidden" value="{{ $faq->answer }}"/>
                                                                    </td>

                                                                    <td class="text-right">
                                                                        <button type="button" data-faq-id="{{ $faq->id }}" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}" class="edit-faq btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>

                                                                        @include('admin.includes.delete_button',['url' => '/admin/faqs/'. $faq->id .'/delete', 'btnClass' => ' mt-1'])
                                                                    </td>
                                                                </tr>
                                                            @endforeach

                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'faq.png',
                                                        'title' => trans('public.faq_no_result'),
                                                        'hint' => trans('public.faq_no_result_hint'),
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>

                                    @foreach(\App\Models\WebinarExtraDescription::$types as $webinarExtraDescriptionType)
                                        <section class="mt-30">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <h2 class="section-title after-line">{{ trans('update.'.$webinarExtraDescriptionType) }}</h2>
                                                <button id="add_new_{{ $webinarExtraDescriptionType }}" type="button" class="btn btn-primary btn-sm mt-3">{{ trans('update.add_'.$webinarExtraDescriptionType) }}</button>
                                            </div>

                                            @php
                                                $webinarExtraDescriptionValues = $webinar->webinarExtraDescription->where('type',$webinarExtraDescriptionType);
                                            @endphp

                                            <div class="row mt-10">
                                                <div class="col-12">
                                                    @if(!empty($webinarExtraDescriptionValues) and count($webinarExtraDescriptionValues))
                                                        <div class="table-responsive">
                                                            <table class="table table-striped text-center font-14">

                                                                <tr>
                                                                    @if($webinarExtraDescriptionType == \App\Models\WebinarExtraDescription::$COMPANY_LOGOS)
                                                                        <th>{{ trans('admin/main.icon') }}</th>
                                                                    @else
                                                                        <th>{{ trans('public.title') }}</th>
                                                                    @endif
                                                                    <th></th>
                                                                </tr>

                                                                @foreach($webinarExtraDescriptionValues as $extraDescription)
                                                                    <tr>
                                                                        @if($webinarExtraDescriptionType == \App\Models\WebinarExtraDescription::$COMPANY_LOGOS)
                                                                            <td>
                                                                                <img src="{{ $extraDescription->value }}" class="webinar-extra-description-company-logos" alt="">
                                                                            </td>
                                                                        @else
                                                                            <td>{{ $extraDescription->value }}</td>
                                                                        @endif

                                                                        <td class="text-right">
                                                                            <button type="button" data-item-id="{{ $extraDescription->id }}" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}" class="edit-extraDescription btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                                <i class="fa fa-edit"></i>
                                                                            </button>

                                                                            @include('admin.includes.delete_button',['url' => '/admin/webinar-extra-description/'. $extraDescription->id .'/delete', 'btnClass' => ' mt-1'])
                                                                        </td>
                                                                    </tr>
                                                                @endforeach

                                                            </table>
                                                        </div>
                                                    @else
                                                        @include('admin.includes.no-result',[
                                                             'file_name' => 'faq.png',
                                                             'title' => trans("update.{$webinarExtraDescriptionType}_no_result"),
                                                             'hint' => trans("update.{$webinarExtraDescriptionType}_no_result_hint"),
                                                        ])
                                                    @endif
                                                </div>
                                            </div>
                                        </section>
                                    @endforeach

                                    <section class="mt-30">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h2 class="section-title after-line">{{ trans('public.quiz_certificate') }}</h2>
                                            <button id="webinarAddQuiz" type="button" class="btn btn-primary btn-sm mt-3">{{ trans('public.add_quiz') }}</button>
                                        </div>
                                        <div class="row mt-10">
                                            <div class="col-12">
                                                @if(!empty($webinarQuizzes) and !$webinarQuizzes->isEmpty())
                                                    <div class="table-responsive">
                                                        <table class="table table-striped text-center font-14">

                                                            <tr>
                                                                <th>{{ trans('public.title') }}</th>
                                                                <th>{{ trans('public.questions') }}</th>
                                                                <th>{{ trans('public.total_mark') }}</th>
                                                                <th>{{ trans('public.pass_mark') }}</th>
                                                                <th>{{ trans('public.certificate') }}</th>
                                                                <th></th>
                                                            </tr>

                                                            @foreach($webinarQuizzes as $webinarQuiz)
                                                                <tr>
                                                                    <th>{{ $webinarQuiz->title }}</th>
                                                                    <td>{{ $webinarQuiz->quizQuestions->count() }}</td>
                                                                    <td>{{ $webinarQuiz->quizQuestions->sum('grade') }}</td>
                                                                    <td>{{ $webinarQuiz->pass_mark }}</td>
                                                                    <td>{{ $webinarQuiz->certificate ? trans('public.yes') : trans('public.no') }}</td>
                                                                    <td>
                                                                        <button type="button" data-webinar-quiz-id="{{ $webinarQuiz->id }}" data-webinar-id="{{ !empty($webinar) ? $webinar->id : '' }}" class="edit-webinar-quiz btn-transparent text-primary mt-1" data-toggle="tooltip" data-placement="top" title="{{ trans('admin/main.edit') }}">
                                                                            <i class="fa fa-edit"></i>
                                                                        </button>

                                                                        @include('admin.includes.delete_button',['url' => '/admin/webinar-quiz/'. $webinarQuiz->id .'/delete', 'btnClass' => ' mt-1'])
                                                                    </td>
                                                                    @endforeach
                                                                </tr>

                                                        </table>
                                                    </div>
                                                @else
                                                    @include('admin.includes.no-result',[
                                                        'file_name' => 'cert.png',
                                                        'title' => trans('public.quizzes_no_result'),
                                                        'hint' => trans('public.quizzes_no_result_hint'),
                                                    ])
                                                @endif
                                            </div>
                                        </div>
                                    </section>
                                @endif

                                <section class="mt-3">
                                    <h2 class="section-title after-line">{{ trans('public.message_to_reviewer') }}</h2>
                                    <div class="row">
                                        <div class="col-12">
                                            <div class="form-group mt-15">
                                                <textarea name="message_for_reviewer" rows="10" class="form-control">{{ (!empty($webinar) && $webinar->message_for_reviewer) ? $webinar->message_for_reviewer : old('message_for_reviewer') }}</textarea>
                                            </div>
                                        </div>
                                    </div>
                                </section>

                                <input type="hidden" name="draft" value="no" id="forDraft"/>

                                <div class="row">
                                    <div class="col-12">
                                        <button type="button" id="saveAndPublish" class="btn btn-success">{{ !empty($webinar) ? trans('admin/main.save_and_publish') : trans('admin/main.save_and_continue') }}</button>

                                        @if(!empty($webinar))
                                            <button type="button" id="saveReject" class="btn btn-warning">{{ trans('public.reject') }}</button>

                                            @include('admin.includes.delete_button',[
                                                    'url' => '/admin/webinars/'. $webinar->id .'/delete',
                                                    'btnText' => trans('public.delete'),
                                                    'hideDefaultClass' => true,
                                                    'btnClass' => 'btn btn-danger'
                                                    ])
                                        @endif
                                    </div>
                                </div>
                            </form>


                            @include('admin.webinars.modals.prerequisites')
                            @include('admin.webinars.modals.quizzes')
                            @include('admin.webinars.modals.ticket')
                            @include('admin.webinars.modals.chapter')
                            @include('admin.webinars.modals.session')
                            @include('admin.webinars.modals.file')
                            @include('admin.webinars.modals.interactive_file')
                            @include('admin.webinars.modals.faq')
                            @include('admin.webinars.modals.testLesson')
                            @include('admin.webinars.modals.assignment')
                            @include('admin.webinars.modals.extra_description')
                            @include('admin.webinars.modals.items')
                            @include('admin.webinars.modals.features')
                            @include('admin.webinars.modals.InstructorTestimonials')
                            @include('admin.webinars.modals.instructor_highlights')
                            @include('admin.webinars.modals.academy_section')

<!-- Box Template (Hidden) - Must be outside modal -->
<div class="d-none" id="academyBoxTemplate">
    <div class="box-item card mb-3" data-box-index="">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">صندوق <span class="box-number"></span></h5>
                <button type="button" class="btn btn-sm btn-danger remove-academy-box">حذف</button>
            </div>
            
            <div class="form-group">
                <label>العنوان</label>
                <input type="text" name="boxes[][title]" class="form-control box-title" required>
            </div>

            <div class="form-group">
                <label>الوصف</label>
                <textarea name="boxes[][description]" class="form-control box-description" rows="3" required></textarea>
            </div>

            <div class="form-group">
                <label>نوع الأيقونة</label>
                <select name="boxes[][icon_type]" class="form-control box-icon-type">
                    <option value="class" selected>Class (Font Awesome)</option>
                    <option value="image">صورة</option>
                </select>
            </div>

            <div class="form-group box-icon-class-group">
                <label>اسم الأيقونة (Font Awesome Class)</label>
                <input type="text" name="boxes[][icon]" class="form-control box-icon" placeholder="مثال: fa fa-graduation-cap">
            </div>

            <div class="form-group box-icon-image-group" style="display:none;">
                <label>صورة الأيقونة</label>
                <div class="input-group">
                    <div class="input-group-prepend">
                        <button type="button" class="input-group-text admin-file-manager" data-input="box_icon_image_" data-preview="box_icon_preview_">
                            <i class="fa fa-chevron-up"></i>
                        </button>
                    </div>
                    <input type="text" name="boxes[][icon]" class="form-control box-icon-image">
                </div>
            </div>
        </div>
    </div>
</div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection

@push('scripts_bottom')
    <script>
        var saveSuccessLang = '{{ trans('webinars.success_store') }}';
        var titleLang = '{{ trans('admin/main.title') }}';
        var zoomJwtTokenInvalid = '{{ trans('admin/main.teacher_zoom_jwt_token_invalid') }}';
        var editChapterLang = '{{ trans('public.edit_chapter') }}';
        var requestFailedLang = '{{ trans('public.request_failed') }}';
        var thisLiveHasEndedLang = '{{ trans('update.this_live_has_been_ended') }}';
        var quizzesSectionLang = '{{ trans('quiz.quizzes_section') }}';
        var filePathPlaceHolderBySource = {
            upload: '{{ trans('update.file_source_upload_placeholder') }}',
            youtube: '{{ trans('update.file_source_youtube_placeholder') }}',
            vimeo: '{{ trans('update.file_source_vimeo_placeholder') }}',
            external_link: '{{ trans('update.file_source_external_link_placeholder') }}',
            google_drive: '{{ trans('update.file_source_google_drive_placeholder') }}',
            dropbox: '{{ trans('update.file_source_dropbox_placeholder') }}',
            iframe: '{{ trans('update.file_source_iframe_placeholder') }}',
            s3: '{{ trans('update.file_source_s3_placeholder') }}',
        }
    </script>

    <script src="/assets/default/vendors/sweetalert2/dist/sweetalert2.min.js"></script>
    <script src="/assets/default/vendors/feather-icons/dist/feather.min.js"></script>
    <script src="/assets/default/vendors/select2/select2.min.js"></script>
    <script src="/assets/default/vendors/moment.min.js"></script>
    <script src="/assets/default/vendors/daterangepicker/daterangepicker.min.js"></script>
    <script src="/assets/default/vendors/bootstrap-timepicker/bootstrap-timepicker.min.js"></script>
    <script src="/assets/default/vendors/bootstrap-tagsinput/bootstrap-tagsinput.min.js"></script>
    <script src="/assets/vendors/summernote/summernote-bs4.min.js"></script>
    <script src="/assets/default/vendors/sortable/jquery-ui.min.js"></script>

    <script src="/assets/default/js/admin/quiz.min.js"></script>
    <script src="/assets/admin/js/webinar.min.js"></script>
    <script>
   
   function handleItemInputHtml(key) {
        let html = '<div id="AddforItemsModal">';
        html += $('#forItemsModal').html();
        html += '</div>';

        var modalHtml = $(html);
        // No need to add image field again as it's already in the modal
        modalHtml.find('.js-form-groups').children().remove();

        return modalHtml;
    }
    
    function handleItemInputHtmlEdit(t) {
        var a = '<div id="AddforItemsModal">';
        a += $("#forItemsModal").html();
        var n = $((a += "</div>"));
        // No need to add image field again as it's already in the modal
        n.find(".js-form-groups").children().remove();
        var i = '<div id="AddforItemsModal">';
        return (i += n.html()), (i += "</div>");
    }
    function show_item_data(a, i) {
        var r = a.attr("data-item-id"),
            o = a.attr("data-webinar-id"),
            s = t(),
            l = { item_id: o, locale: i };
        $.post("/admin/webinar-for-items/" + r + "/edit", l, function (t) {
            if (t && t.webinarExtraDescription) {
                var a = t.webinarExtraDescription,
                    i = '<div id="AddforItemsModal">';
                (i += e("#forItemsModal").html()),
                    (i += "</div>"),
                    "company_logos" === a.type && (i = n(s)),
                    (i = i.replaceAll("/admin/webinar-for-items/store", "/admin/webinar-for-items/" + r + "/update")),
                    Swal.fire({
                        html: i,
                        showCancelButton: !1,
                        showConfirmButton: !1,
                        customClass: { content: "p-0 text-left" },
                        width: "48rem",
                        onOpen: function () {
                            var t = e("#AddforItemsModal");
                            Object.keys(a).forEach(function (e) {
                                t.find('[name="' + e + '"]').val(a[e]);
                            });
                            var n = t.find('select[name="locale"]');
                            n && (n.addClass("js-edit-extraDescription-locale-ajax"), n.attr("data-item-id", r), n.attr("data-webinar-id", o));
                        },
                    });
            }
        });
    }
  
        function openForItemModal(itemId) {
            var html = '<div id="AddforItemsModal">' + $('#forItemsModal').html() + '</div>';
            Swal.fire({
                html: html,
                showCancelButton: false,
                showConfirmButton: false,
                customClass: { content: 'p-0 text-left' },
                width: '48rem',
                onOpen: function () {
                    var $modal = $('#AddforItemsModal');
                    if (itemId) {
                        $modal.attr('data-action', '/admin/webinar-for-items/' + itemId + '/update');
                        $.post('/admin/webinar-for-items/' + itemId + '/edit', function (res) {
                            if (res && res.faq) {
                                var item = res.faq;
                                $modal.find('[name="description"]').val(item.description || '');
                                $modal.find('[name="image"]').val(item.image || '');
                                $modal.find('[name="icon"]').val(item.icon || 'users');
                                if (item.background_color) {
                                    $modal.find('[name="background_color"]').val(item.background_color);
                                    $modal.find('[name="background_color_text"]').val(item.background_color);
                                }
                                if (item.locale) {
                                    $modal.find('[name="locale"]').val(item.locale.toLowerCase());
                                }
                            }
                        });
                    } else {
                        $modal.attr('data-action', $('#forItemsModal form').attr('action'));
                    }
                }
            });
        }

        $("body").on("click", "#webinarAddForItems", function (t) {
            t.preventDefault();
            openForItemModal(null);
        });

        $("body").on("click", ".edit-for-item", function (t) {
            t.preventDefault();
            openForItemModal($(this).data('item-id'));
        });
        
         
        $("body").on("click", "#saveForItem", function (t) {
            console.log('good');
            t.preventDefault();
        
            var a = $(this),
                n = a.closest("#AddforItemsModal");
              
            handleWebinarItemForm(n, a);
        });
        
        
        function openFeatureModal(itemId) {
            var html = '<div id="AddFeaturesModal">' + $('#FeaturesModal').html() + '</div>';
            Swal.fire({
                html: html,
                showCancelButton: false,
                showConfirmButton: false,
                customClass: { content: 'p-0 text-left' },
                width: '48rem',
                onOpen: function () {
                    var $modal = $('#AddFeaturesModal');
                    if (itemId) {
                        $modal.attr('data-action', '/admin/webinar-features/' + itemId + '/update');
                        $.post('/admin/webinar-features/' + itemId + '/edit', function (res) {
                            if (res && res.faq) {
                                var feature = res.faq;
                                $modal.find('[name="description"]').val(feature.description || '');
                                if (feature.locale) {
                                    $modal.find('[name="locale"]').val(feature.locale.toLowerCase());
                                }
                            }
                        });
                    } else {
                        $modal.attr('data-action', $('#FeaturesModal form').attr('action'));
                    }
                }
            });
        }

        $("body").on("click", "#webinarAddFeatures", function (t) {
            t.preventDefault();
            openFeatureModal(null);
        });

        $("body").on("click", ".edit-feature", function (t) {
            t.preventDefault();
            openFeatureModal($(this).data('item-id'));
        });
        $("body").on("click", "#saveFeature", function (t) {
            console.log('good');
            t.preventDefault();
        
            var a = $(this),
                n = a.closest("#AddFeaturesModal");
              
            handleWebinarItemForm(n, a);
        });

        // Academy Section Modal
        $("body").on("click", "#webinarEditAcademySection", function (t) {
            t.preventDefault();
            var webinarId = $(this).attr("data-webinar-id");
            
            var n = '<div id="AddAcademySectionModal">';
            n += $("#AcademySectionModal").html();
            
            Swal.fire({
                html: n,
                showCancelButton: !1,
                showConfirmButton: !1,
                customClass: { content: "p-0 text-left" },
                width: "60rem",
                onOpen: function () {
                    $('#AddAcademySectionModal').attr("data-action", $('#AcademySectionModal form').attr('action'));
                    
                    // Initialize box index - will be calculated based on existing boxes
                    academyBoxIndex = 0;
                    
                    // Set status checkbox to checked by default (will be overridden if section exists)
                    setTimeout(function() {
                        var $modal = $('#AddAcademySectionModal');
                        if ($modal.length === 0) {
                            $modal = $('.swal2-container').find('#AddAcademySectionModal');
                        }
                        var $statusCheckbox = $modal.find('.js-academy-status');
                        if ($statusCheckbox.length === 0) {
                            $statusCheckbox = $('.swal2-container').find('.js-academy-status');
                        }
                        if ($statusCheckbox.length > 0) {
                            $statusCheckbox.prop('checked', true);
                            console.log('Status checkbox set to checked by default');
                        }
                    }, 100);
                    
                    // Load existing academy section if exists
                    if (webinarId) {
                        // Use setTimeout to ensure modal is fully rendered
                        setTimeout(function() {
                            var $modal = $('#AddAcademySectionModal');
                            if ($modal.length === 0) {
                                $modal = $('.swal2-container').find('#AddAcademySectionModal');
                            }
                            
                            if ($modal.length === 0) {
                                console.error('Modal not found after timeout!');
                                return;
                            }
                            
                            console.log('Loading academy section for webinar:', webinarId);
                            
                            $.get("/admin/webinar-academy-sections/" + webinarId + "/get", function (response) {
                                console.log('Academy section response:', response);
                                
                                if (response && response.status === 'success' && response.academySection) {
                                    var section = response.academySection;
                                    
                                    // Set title
                                    var $titleInput = $modal.find('.js-academy-title');
                                    if ($titleInput.length === 0) {
                                        $titleInput = $modal.find('input[name="title"]');
                                    }
                                    if ($titleInput.length > 0) {
                                        $titleInput.val(section.title || 'الأكاديمية تحتوي على');
                                        console.log('Title set to:', section.title);
                                    }
                                    
                                    // Set status
                                    var $statusInput = $modal.find('.js-academy-status');
                                    if ($statusInput.length === 0) {
                                        $statusInput = $modal.find('input[name="status"]');
                                    }
                                    if ($statusInput.length > 0) {
                                        var statusValue = section.status == 1 || section.status === true || section.status === '1';
                                        $statusInput.prop('checked', statusValue);
                                        console.log('Status set to:', statusValue, 'from section.status:', section.status);
                                    } else {
                                        console.warn('Status input not found!');
                                    }
                                    
                                    // Load boxes
                                    var $boxesList = $modal.find('#academyBoxesList');
                                    if ($boxesList.length === 0) {
                                        $boxesList = $('.swal2-container').find('#academyBoxesList');
                                    }
                                    
                                    if ($boxesList.length > 0) {
                                        $boxesList.empty();
                                        
                                        if (section.boxes && section.boxes.length > 0) {
                                            console.log('Loading ' + section.boxes.length + ' boxes');
                                            section.boxes.forEach(function(box, index) {
                                                addAcademyBox(box, index);
                                            });
                                        } else {
                                            console.log('No boxes found, adding default boxes');
                                            for (var i = 0; i < 3; i++) {
                                                addAcademyBox();
                                            }
                                        }
                                    } else {
                                        console.error('Boxes list not found!');
                                        for (var i = 0; i < 3; i++) {
                                            addAcademyBox();
                                        }
                                    }
                                } else {
                                    console.log('No academy section found, adding default boxes');
                                    // Set status to checked by default for new sections
                                    $modal.find('.js-academy-status').prop('checked', true);
                                    // Add default boxes if no section exists
                                    for (var i = 0; i < 3; i++) {
                                        addAcademyBox();
                                    }
                                }
                            }).fail(function(xhr, status, error) {
                                console.error('Failed to load academy section:', error);
                                // Add default boxes on error
                                for (var i = 0; i < 3; i++) {
                                    addAcademyBox();
                                }
                            });
                        }, 100);
                    } else {
                        // Add default boxes if no webinar ID
                        setTimeout(function() {
                            for (var i = 0; i < 3; i++) {
                                addAcademyBox();
                            }
                        }, 100);
                    }
                }
            });
        });

        let academyBoxIndex = 0;

        function addAcademyBox(boxData = null, index = null) {
            // Get template from outside the modal (in the main page)
            var template = $('#academyBoxTemplate');
            if (template.length === 0) {
                console.error('Template not found!');
                return;
            }
            
            // Find the list to determine current box count
            var $list = $('#AddAcademySectionModal').find('#academyBoxesList');
            if ($list.length === 0) {
                $list = $('.swal2-container').find('#academyBoxesList');
            }
            
            // Calculate box index based on existing boxes
            var boxIndex;
            if (index !== null) {
                boxIndex = index;
            } else {
                var currentBoxCount = $list.length > 0 ? $list.find('.box-item').length : 0;
                boxIndex = currentBoxCount;
                academyBoxIndex = currentBoxCount + 1;
            }
            var boxHtml = template.html();
            
            // Replace placeholders
            boxHtml = boxHtml.replace(/data-box-index=""/g, 'data-box-index="' + boxIndex + '"');
            boxHtml = boxHtml.replace(/<span class="box-number"><\/span>/g, '<span class="box-number">' + (boxIndex + 1) + '</span>');
            boxHtml = boxHtml.replace(/name="boxes\[\]\[/g, 'name="boxes[' + boxIndex + '][');
            boxHtml = boxHtml.replace(/data-input="box_icon_image_"/g, 'data-input="box_icon_image_' + boxIndex + '"');
            boxHtml = boxHtml.replace(/data-preview="box_icon_preview_"/g, 'data-preview="box_icon_preview_' + boxIndex + '"');
            
            // Create jQuery object from HTML
            var $box = $(boxHtml);
            
            // Fill with data if provided
            if (boxData) {
                console.log('Filling box with data:', boxData);
                
                var $titleInput = $box.find('.box-title');
                var $descInput = $box.find('.box-description');
                var $iconTypeSelect = $box.find('.box-icon-type');
                
                if ($titleInput.length > 0) {
                    $titleInput.val(boxData.title || '');
                    console.log('Title set to:', boxData.title);
                } else {
                    console.error('Title input not found!');
                }
                
                if ($descInput.length > 0) {
                    $descInput.val(boxData.description || '');
                    console.log('Description set to:', boxData.description);
                } else {
                    console.error('Description input not found!');
                }
                
                var iconType = boxData.icon_type || 'class';
                if ($iconTypeSelect.length > 0) {
                    $iconTypeSelect.val(iconType);
                    console.log('Icon type set to:', iconType);
                } else {
                    console.error('Icon type select not found!');
                }
                
                if (iconType == 'image') {
                    var $iconImageInput = $box.find('.box-icon-image');
                    if ($iconImageInput.length > 0) {
                        $iconImageInput.val(boxData.icon || '');
                        console.log('Icon image set to:', boxData.icon);
                    }
                    $box.find('.box-icon-class-group').hide();
                    $box.find('.box-icon-image-group').show();
                } else {
                    var $iconInput = $box.find('.box-icon');
                    if ($iconInput.length > 0) {
                        $iconInput.val(boxData.icon || '');
                        console.log('Icon class set to:', boxData.icon);
                    }
                    $box.find('.box-icon-class-group').show();
                    $box.find('.box-icon-image-group').hide();
                }
            } else {
                console.log('No box data provided, creating empty box');
            }
            
            // Append to the list inside the modal
            var $list = $('#AddAcademySectionModal').find('#academyBoxesList');
            if ($list.length === 0) {
                $list = $('.swal2-container').find('#academyBoxesList');
            }
            
            if ($list.length > 0) {
                $list.append($box);
                updateAcademyBoxNumbers();
            } else {
                console.error('academyBoxesList not found in modal!');
            }
        }

        function updateAcademyBoxNumbers() {
            var $list = $('#AddAcademySectionModal').find('#academyBoxesList');
            if ($list.length === 0) {
                $list = $('.swal2-container').find('#academyBoxesList');
            }
            
            if ($list.length > 0) {
                var boxCount = 0;
                $list.find('.box-item').each(function(index) {
                    var $box = $(this);
                    $box.find('.box-number').text(index + 1);
                    $box.attr('data-box-index', index);
                    
                    // Update input names - be more specific
                    $box.find('input.box-title').attr('name', 'boxes[' + index + '][title]');
                    $box.find('textarea.box-description').attr('name', 'boxes[' + index + '][description]');
                    $box.find('select.box-icon-type').attr('name', 'boxes[' + index + '][icon_type]');
                    $box.find('input.box-icon').attr('name', 'boxes[' + index + '][icon]');
                    $box.find('input.box-icon-image').attr('name', 'boxes[' + index + '][icon]');
                    
                    // Also update data attributes for file manager
                    $box.find('.admin-file-manager').attr('data-input', 'box_icon_image_' + index);
                    $box.find('.admin-file-manager').attr('data-preview', 'box_icon_preview_' + index);
                    $box.find('input.box-icon-image').attr('id', 'box_icon_image_' + index);
                    
                    boxCount++;
                });
                
                console.log('Updated ' + boxCount + ' boxes with correct names');
            }
        }

        $(document).on("click", "#addAcademyBox", function (t) {
            t.preventDefault();
            console.log('Add box button clicked');
            addAcademyBox();
        });

        $("body").on("click", ".remove-academy-box", function (t) {
            t.preventDefault();
            
            var $list = $('#AddAcademySectionModal').find('#academyBoxesList');
            if ($list.length === 0) {
                $list = $('.swal2-container').find('#academyBoxesList');
            }
            
            var boxCount = $list.find('.box-item').length;
            
            if (boxCount > 1) {
                $(this).closest('.box-item').remove();
                updateAcademyBoxNumbers();
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'تحذير',
                    text: 'يجب أن يكون هناك صندوق واحد على الأقل'
                });
            }
        });

        $(document).on("change", ".box-icon-type", function () {
            var boxItem = $(this).closest('.box-item');
            var iconType = $(this).val();
            
            if (iconType === 'class') {
                boxItem.find('.box-icon-class-group').show();
                boxItem.find('.box-icon-image-group').hide();
            } else {
                boxItem.find('.box-icon-class-group').hide();
                boxItem.find('.box-icon-image-group').show();
            }
        });

        $("body").on("click", "#saveAcademySection", function (t) {
            t.preventDefault();
            
            // Find the modal - try multiple ways
            var $modal = $('#AddAcademySectionModal');
            if ($modal.length === 0) {
                $modal = $('.swal2-container').find('#AddAcademySectionModal');
            }
            if ($modal.length === 0) {
                $modal = $(this).closest('#AddAcademySectionModal');
            }
            if ($modal.length === 0) {
                $modal = $(this).closest('.swal2-container').find('#AddAcademySectionModal');
            }
            
            if ($modal.length === 0) {
                console.error('Modal not found!');
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ',
                    text: 'لم يتم العثور على النموذج'
                });
                return;
            }
            
            var form = $modal.find('form');
            if (form.length === 0) {
                form = $modal.find('#academySectionForm');
            }
            
            if (form.length === 0) {
                console.error('Form not found in modal!');
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ',
                    text: 'لم يتم العثور على النموذج'
                });
                return;
            }
            
            // Get title value - try multiple selectors
            var title = $modal.find('.js-academy-title').val();
            if (!title) {
                title = form.find('input[name="title"]').val();
            }
            if (!title) {
                title = $modal.find('input[name="title"]').val();
            }
            
            console.log('Title found:', title);
            
            if (!title || title.trim() === '') {
                Swal.fire({
                    icon: 'warning',
                    title: 'تحذير',
                    text: 'يرجى إدخال عنوان القسم'
                });
                return;
            }
            
            // Collect boxes data - only non-empty boxes
            var boxes = [];
            
            // Find all boxes in the modal (try multiple selectors)
            var $list = $modal.find('#academyBoxesList');
            if ($list.length === 0) {
                $list = $('.swal2-container').find('#academyBoxesList');
            }
            if ($list.length === 0) {
                $list = form.find('#academyBoxesList');
            }
            if ($list.length === 0) {
                $list = $modal.find('.box-item').parent();
            }
            
            console.log('List found:', $list.length > 0);
            
            if ($list.length > 0) {
                $list.find('.box-item').each(function(index) {
                    var $box = $(this);
                    var boxTitle = $box.find('.box-title').val();
                    var boxDescription = $box.find('.box-description').val();
                    
                    console.log('Box ' + index + ' - Title: ' + boxTitle + ', Description: ' + boxDescription);
                    
                    // Only add box if it has title and description
                    if (boxTitle && boxTitle.trim() !== '' && boxDescription && boxDescription.trim() !== '') {
                        var iconType = $box.find('.box-icon-type').val() || 'class';
                        var icon = '';
                        
                        if (iconType === 'class') {
                            icon = $box.find('.box-icon').val() || '';
                        } else {
                            icon = $box.find('.box-icon-image').val() || '';
                        }
                        
                        boxes.push({
                            title: boxTitle.trim(),
                            description: boxDescription.trim(),
                            icon: icon,
                            icon_type: iconType
                        });
                    } else {
                        console.warn('Box ' + index + ' skipped - missing title or description');
                    }
                });
            } else {
                // Fallback: try to find boxes directly in form
                form.find('.box-item').each(function(index) {
                    var $box = $(this);
                    var boxTitle = $box.find('.box-title').val();
                    var boxDescription = $box.find('.box-description').val();
                    
                    if (boxTitle && boxTitle.trim() !== '' && boxDescription && boxDescription.trim() !== '') {
                        var iconType = $box.find('.box-icon-type').val() || 'class';
                        var icon = '';
                        
                        if (iconType === 'class') {
                            icon = $box.find('.box-icon').val() || '';
                        } else {
                            icon = $box.find('.box-icon-image').val() || '';
                        }
                        
                        boxes.push({
                            title: boxTitle.trim(),
                            description: boxDescription.trim(),
                            icon: icon,
                            icon_type: iconType
                        });
                    }
                });
            }
            
            if (boxes.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'تحذير',
                    text: 'يرجى إضافة صندوق واحد على الأقل مع عنوان ووصف'
                });
                return;
            }
            
            // Get status - try multiple selectors
            var status = false;
            var $statusInput = $modal.find('.js-academy-status');
            if ($statusInput.length > 0) {
                status = $statusInput.is(':checked');
                console.log('Status from .js-academy-status:', status, 'Checked:', $statusInput.prop('checked'));
            } else {
                $statusInput = form.find('input[name="status"]');
                if ($statusInput.length > 0) {
                    status = $statusInput.is(':checked');
                    console.log('Status from form input[name="status"]:', status);
                } else {
                    $statusInput = $modal.find('input[name="status"]');
                    if ($statusInput.length > 0) {
                        status = $statusInput.is(':checked');
                        console.log('Status from modal input[name="status"]:', status);
                    }
                }
            }
            
            console.log('Final status value:', status, 'Will send:', status ? '1' : '0');
            
            // Get webinar_id - try multiple selectors
            var webinarId = form.find('input[name="webinar_id"]').val();
            if (!webinarId) {
                webinarId = $modal.find('input[name="webinar_id"]').val();
            }
            
            // Get locale - try multiple selectors
            var locale = form.find('select[name="locale"]').val();
            if (!locale) {
                locale = $modal.find('select[name="locale"]').val();
            }
            if (!locale) {
                locale = form.find('input[name="locale"]').val();
            }
            if (!locale) {
                locale = 'AR';
            }
            
            console.log('Form data:', {
                webinar_id: webinarId,
                title: title,
                status: status,
                locale: locale,
                boxes_count: boxes.length
            });
            
            // Build form data
            var formData = new FormData();
            formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
            formData.append('webinar_id', webinarId);
            formData.append('title', title);
            // Double check status from checkbox directly - search in multiple places
            var finalStatus = '1'; // Default to active (1)
            var $statusCheckbox = null;
            var checkboxFound = false;
            
            // Try to find checkbox in multiple locations
            var selectors = [
                '.js-academy-status',
                'input[name="status"]',
                '.custom-switch-input',
                'input[type="checkbox"][name="status"]'
            ];
            
            var searchLocations = [
                $modal,
                $('.swal2-container'),
                form,
                $('body')
            ];
            
            for (var i = 0; i < selectors.length && !checkboxFound; i++) {
                for (var j = 0; j < searchLocations.length && !checkboxFound; j++) {
                    $statusCheckbox = searchLocations[j].find(selectors[i]);
                    if ($statusCheckbox.length > 0) {
                        checkboxFound = true;
                        console.log('Status checkbox found using selector:', selectors[i], 'in location:', j);
                        break;
                    }
                }
            }
            
            if (checkboxFound && $statusCheckbox.length > 0) {
                var isChecked = $statusCheckbox.is(':checked');
                finalStatus = isChecked ? '1' : '0';
                console.log('Status from checkbox:', finalStatus, 'Checked:', isChecked, 'Element:', $statusCheckbox[0]);
            } else {
                console.warn('Status checkbox not found! Using default: 1 (active)');
                // If checkbox not found, default to active (1)
                finalStatus = '1';
            }
            
            // Force to 1 if checkbox was not found or if we want to ensure it's always active
            // Uncomment the next line if you want to always force status to 1
            // finalStatus = '1';
            
            console.log('Final status value to send:', finalStatus);
            formData.append('status', finalStatus);
            formData.append('locale', locale);
            
            // Add boxes
            boxes.forEach(function(box, index) {
                formData.append('boxes[' + index + '][title]', box.title);
                formData.append('boxes[' + index + '][description]', box.description);
                formData.append('boxes[' + index + '][icon]', box.icon);
                formData.append('boxes[' + index + '][icon_type]', box.icon_type);
            });
            
            // Log form data
            console.log('=== Saving Academy Section ===');
            console.log('Title:', title);
            var totalBoxes = $list.length > 0 ? $list.find('.box-item').length : form.find('.box-item').length;
            console.log('Total boxes found in DOM:', totalBoxes);
            console.log('Boxes count (with valid data):', boxes.length);
            console.log('Boxes data:', boxes);
            
            // Verify all boxes are collected
            if ($list.length > 0) {
                console.log('=== Verifying all boxes ===');
                $list.find('.box-item').each(function(i) {
                    var $b = $(this);
                    var bTitle = $b.find('.box-title').val();
                    var bDesc = $b.find('.box-description').val();
                    var iconType = $b.find('.box-icon-type').val() || 'class';
                    var icon = iconType === 'class' ? $b.find('.box-icon').val() : $b.find('.box-icon-image').val();
                    
                    console.log('Box ' + i + ':', {
                        title: bTitle || '(empty)',
                        description: bDesc || '(empty)',
                        icon: icon || '(empty)',
                        icon_type: iconType,
                        hasTitle: !!bTitle && bTitle.trim() !== '',
                        hasDescription: !!bDesc && bDesc.trim() !== '',
                        willBeSaved: (!!bTitle && bTitle.trim() !== '' && !!bDesc && bDesc.trim() !== '')
                    });
                });
            }
            
            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    console.log('Success response:', response);
                    if (response.status == 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'نجح',
                            text: 'تم حفظ قسم الأكاديمية بنجاح',
                            timer: 2000
                        }).then(function() {
                            location.reload();
                        });
                    } else {
                        console.error('Error in response:', response);
                        Swal.fire({
                            icon: 'error',
                            title: 'خطأ',
                            text: response.msg || 'حدث خطأ أثناء الحفظ'
                        });
                    }
                },
                error: function(xhr) {
                    console.error('AJAX Error:', xhr);
                    console.error('Status:', xhr.status);
                    console.error('Response:', xhr.responseText);
                    
                    var errorMsg = 'حدث خطأ أثناء الحفظ';
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg = xhr.responseJSON.msg;
                    } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                        errorMsg = 'أخطاء في التحقق: ' + JSON.stringify(xhr.responseJSON.errors);
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'خطأ',
                        text: errorMsg,
                        html: xhr.responseJSON && xhr.responseJSON.errors ? 
                            '<div style="text-align: right; direction: rtl;">' + 
                            Object.values(xhr.responseJSON.errors).flat().join('<br>') + 
                            '</div>' : errorMsg
                    });
                }
            });
        });
        
      
        
      
        
        
        function openInstructorTestimonialModal(itemId) {
            var html = '<div id="AddInstructorTestimonialsModal">' + $('#forInstructorTestimonialsModal').html() + '</div>';
            Swal.fire({
                html: html,
                showCancelButton: false,
                showConfirmButton: false,
                customClass: { content: 'p-0 text-left' },
                width: '48rem',
                onOpen: function () {
                    var $modal = $('#AddInstructorTestimonialsModal');
                    if (itemId) {
                        $modal.attr('data-action', '/admin/webinar-instructor-testimonials/' + itemId + '/update');
                        $.post('/admin/webinar-instructor-testimonials/' + itemId + '/edit', function (res) {
                            if (res && res.faq) {
                                var testimonial = res.faq;
                                $modal.find('[name="name"]').val(testimonial.name || '');
                                $modal.find('[name="comment"]').val(testimonial.comment || '');
                                if (testimonial.locale) {
                                    $modal.find('[name="locale"]').val(testimonial.locale.toLowerCase());
                                }
                            }
                        });
                    } else {
                        $modal.attr('data-action', $('#forInstructorTestimonialsModal form').attr('action'));
                    }
                }
            });
        }

        $("body").on("click", ".edit-instructor-testimonial", function (t) {
            t.preventDefault();
            openInstructorTestimonialModal($(this).data('item-id'));
        });

        $("body").on("click", ".edit-instructor-highlights", function (t) {
            t.preventDefault();
            $("#webinarEditInstructorHighlights").trigger("click");
        });

        function getInstructorHighlightsModal() {
            var $modal = $('#AddInstructorHighlightsModal');
            if ($modal.length === 0) {
                $modal = $('.swal2-container').find('#AddInstructorHighlightsModal');
            }
            return $modal;
        }

        function addInstructorHighlightBox(boxData, index) {
            var template = $('#instructorHighlightBoxTemplate');
            if (template.length === 0) {
                return;
            }
            var $list = getInstructorHighlightsModal().find('#instructorHighlightsList');
            var boxIndex = index !== null && index !== undefined ? index : $list.find('.highlight-box-item').length;
            var boxHtml = template.html();
            boxHtml = boxHtml.replace(/data-box-index=""/g, 'data-box-index="' + boxIndex + '"');
            boxHtml = boxHtml.replace(/<span class="highlight-box-number"><\/span>/g, '<span class="highlight-box-number">' + (boxIndex + 1) + '</span>');
            boxHtml = boxHtml.replace(/name="items\[\]\[/g, 'name="items[' + boxIndex + '][');
            boxHtml = boxHtml.replace(/id="highlight_status_"/g, 'id="highlight_status_' + boxIndex + '"');
            boxHtml = boxHtml.replace(/for="highlight_status_"/g, 'for="highlight_status_' + boxIndex + '"');
            var $box = $(boxHtml);
            if (boxData) {
                $box.find('.highlight-icon').val(boxData.icon || 'award');
                $box.find('.highlight-value').val(boxData.value || '');
                $box.find('.highlight-label').val(boxData.label || '');
                $box.find('.highlight-status').prop('checked', boxData.status == 1 || boxData.status === true);
            }
            $list.append($box);
        }

        $("body").on("click", "#webinarEditInstructorHighlights", function (t) {
            t.preventDefault();
            var webinarId = $(this).attr('data-webinar-id');
            var html = '<div id="AddInstructorHighlightsModal">' + $('#InstructorHighlightsModal').html() + '</div>';
            Swal.fire({
                html: html,
                showCancelButton: false,
                showConfirmButton: false,
                customClass: { content: 'p-0 text-left' },
                width: '48rem',
                onOpen: function () {
                    var $modal = getInstructorHighlightsModal();
                    $modal.find('#instructorHighlightsList').empty();
                    if (webinarId) {
                        $.get('/admin/webinar-instructor-highlights/' + webinarId + '/get', function (response) {
                            if (response && response.status === 'success' && response.items && response.items.length) {
                                response.items.forEach(function (item, index) {
                                    addInstructorHighlightBox(item, index);
                                });
                            } else {
                                addInstructorHighlightBox(null, 0);
                            }
                        });
                    } else {
                        addInstructorHighlightBox(null, 0);
                    }
                }
            });
        });

        $('body').on('click', '#addInstructorHighlightBox', function () {
            addInstructorHighlightBox(null, null);
        });

        $('body').on('click', '.remove-instructor-highlight', function () {
            $(this).closest('.highlight-box-item').remove();
        });

        $('body').on('click', '#saveInstructorHighlights', function (e) {
            e.preventDefault();
            var $modal = getInstructorHighlightsModal();
            var $form = $modal.find('#instructorHighlightsForm');
            $.post($form.attr('action'), $form.serialize(), function (response) {
                if (response && response.status === 'success') {
                    Swal.fire({ icon: 'success', title: 'تم', text: response.msg || 'تم الحفظ' }).then(function () {
                        window.location.reload();
                    });
                } else {
                    Swal.fire({ icon: 'error', title: 'خطأ', text: (response && response.msg) ? response.msg : 'فشل الحفظ' });
                }
            }).fail(function (xhr) {
                var msg = 'فشل الحفظ';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    msg = xhr.responseJSON.msg;
                }
                Swal.fire({ icon: 'error', title: 'خطأ', text: msg });
            });
        });

        $("body").on("click", "#webinarAddInstructorTestimonials", function (t) {
            t.preventDefault();
            openInstructorTestimonialModal(null);
        });
        
        $("body").on("click", "#saveInstructorTestimonial", function (t) {
            
            t.preventDefault();
        
            var a = $(this),
                n = a.closest("#AddInstructorTestimonialsModal");
              
            handleWebinarItemForm(n, a);
        });
        
        // Ensure user selection dropdowns are searchable
        $(document).ready(function() {
            // Wait for all scripts to load
            setTimeout(function() {
                // Force initialize user selection dropdowns
                if (typeof window.initializeUserSelect2 === 'function') {
                    window.initializeUserSelect2();
                }
                
                // Also try direct initialization with AJAX
                $('select[name*="allowed_users"]').each(function() {
                    var $this = $(this);
                    if (!$this.hasClass('select2-hidden-accessible')) {
                        $this.select2({
                            multiple: true,
                            width: '100%',
                            placeholder: 'Type to search users...',
                            allowClear: true,
                            closeOnSelect: false,
                            minimumInputLength: 2,
                            // Fix dropdown visibility when inside overlays/collapses
                            dropdownParent: $this.closest('.swal2-container, .modal, .card-body, body'),
                            ajax: {
                                url: '/admin/webinars/search-users',
                                dataType: 'json',
                                delay: 250,
                                cache: false,
                                beforeSend: function(xhr, settings) {
                                    try { console.log('User search request →', settings.url); } catch(e) {}
                                },
                                data: function (params) {
                                    return {
                                        q: params.term,
                                        page: params.page || 1
                                    };
                                },
                                processResults: function (data, params) {
                                    try { console.log('User search response count:', Array.isArray(data) ? data.length : 'n/a', data); } catch(e) {}
                                    return {
                                        results: data
                                    };
                                },
                                error: function(xhr){
                                    try { console.error('User search error', xhr.status, xhr.responseText); } catch(e) {}
                                },
                                cache: true
                            }
                        });
                    }
                });
            }, 2000);
        });
        
    </script>
@endpush

@include('admin.layouts.app')