@extends('admin.layouts.app')

@section('title', 'ویرایش قالب')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-gradient-primary">
                    <h3 class="card-title text-white">
                        <i class="fas fa-paint-brush ml-2"></i>
                        ویرایش قالب
                    </h3>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.templates.update', $template) }}" method="POST" id="templateForm">
                        @csrf
                        @method('PUT')
                        <div class="row">
                            <!-- اطلاعات پایه -->
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-light">
                                        <h4 class="card-title">
                                            <i class="fas fa-info-circle ml-2"></i>
                                            اطلاعات پایه
                                        </h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="name">
                                                <i class="fas fa-font ml-1"></i>
                                                نام قالب
                                            </label>
                                            <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name', $template->name) }}" required>
                                            @error('name')
                                                <span class="invalid-feedback">{{ $message }}</span>
                                            @enderror
                                        </div>
                                        <div class="form-group">
                                            <label for="category_id">
                                                <i class="fas fa-folder ml-1"></i>
                                                دسته‌بندی
                                            </label>
                                            <select class="form-control select2 @error('category_id') is-invalid @enderror" id="category_id" name="category_id" required>
                                                <option value="">انتخاب کنید</option>
                                                @foreach($categories as $category)
                                                    <option value="{{ $category->id }}" {{ old('category_id', $template->category_id) == $category->id ? 'selected' : '' }}>
                                                        {{ $category->category_fa ?? $category->name ?? '-' }}
                                                    </option>
                                                @endforeach
                                            </select>
                                            @error('category_id')
                                                <span class="invalid-feedback">{{ $message }}</span>
                                            @enderror
                                        </div>
                                        <div class="form-group">
                                            <label for="template_type">نوع قالب</label>
                                            <select name="template_type" id="template_type" class="form-control">
                                                <option value="base" {{ $template->template_type === 'base' ? 'selected' : '' }}>پایه</option>
                                                <option value="parent" {{ $template->template_type === 'parent' ? 'selected' : '' }}>والد</option>
                                                <option value="child" {{ $template->template_type === 'child' ? 'selected' : '' }}>فرزند</option>
                                                <option value="custom" {{ $template->template_type === 'custom' ? 'selected' : '' }}>سفارشی</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- تنظیمات ظاهری -->
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-light">
                                        <h4 class="card-title">
                                            <i class="fas fa-palette ml-2"></i>
                                            تنظیمات ظاهری
                                        </h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="primary_color">
                                                <i class="fas fa-fill-drip ml-1"></i>
                                                رنگ اصلی
                                            </label>
                                            <input type="color" class="form-control" id="primary_color" name="primary_color" value="{{ old('primary_color', $template->primary_color ?? '#007bff') }}">
                                        </div>
                                        <div class="form-group">
                                            <label for="secondary_color">
                                                <i class="fas fa-fill ml-1"></i>
                                                رنگ فرعی
                                            </label>
                                            <input type="color" class="form-control" id="secondary_color" name="secondary_color" value="{{ old('secondary_color', $template->secondary_color ?? '#6c757d') }}">
                                        </div>
                                        <div class="form-group">
                                            <label for="font_family">
                                                <i class="fas fa-font ml-1"></i>
                                                فونت
                                            </label>
                                            <select class="form-control select2" id="font_family" name="font_family">
                                                <option value="vazir" {{ (old('font_family', $template->font_family) == 'vazir') ? 'selected' : '' }}>وزیر</option>
                                                <option value="iransans" {{ (old('font_family', $template->font_family) == 'iransans') ? 'selected' : '' }}>ایران سنس</option>
                                                <option value="yekan" {{ (old('font_family', $template->font_family) == 'yekan') ? 'selected' : '' }}>یکان</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- ویژگی‌ها و امکانات -->
                        <div class="card mt-4">
                            <div class="card-header bg-light">
                                <h4 class="card-title">
                                    <i class="fas fa-cogs ml-2"></i>
                                    ویژگی‌ها و امکانات
                                </h4>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    @php
                                        $templateFeatures = $template->features;
                                        if (is_string($templateFeatures)) {
                                            $templateFeatures = json_decode($templateFeatures, true);
                                        }
                                        if (!is_array($templateFeatures)) {
                                            $templateFeatures = [];
                                        }
                                        $availableFeatures = config('features.available', []);
                                        if (!is_array($availableFeatures)) {
                                            $availableFeatures = [];
                                        }
                                    @endphp
                                    @foreach($availableFeatures as $feature => $config)
                                        <div class="col-md-4 mb-4">
                                            <div class="card h-100 feature-card">
                                                <div class="card-header bg-gradient-info d-flex align-items-center justify-content-between">
                                                    <div>
                                                        <i class="{{ $config['icon'] ?? 'fas fa-star' }} ml-2"></i>
                                                        <span class="font-weight-bold">{{ $config['title'] }}</span>
                                                    </div>
                                                    <div class="custom-control custom-switch">
                                                        <input type="checkbox" class="custom-control-input feature-toggle" id="feature_{{ $feature }}" name="features[{{ $feature }}][is_enabled]" value="1" {{ old("features.{$feature}.is_enabled", $templateFeatures[$feature]['is_enabled'] ?? false) ? 'checked' : '' }}>
                                                        <label class="custom-control-label" for="feature_{{ $feature }}"></label>
                                                    </div>
                                                </div>
                                                <div class="card-body feature-settings">
                                                    @if(!empty($config['settings']) && is_array($config['settings']))
                                                        @php
                                                            $featureSettings = [];
                                                            if (isset($templateFeatures[$feature]['settings'])) {
                                                                if (is_string($templateFeatures[$feature]['settings'])) {
                                                                    $featureSettings = json_decode($templateFeatures[$feature]['settings'], true);
                                                                } elseif (is_array($templateFeatures[$feature]['settings'])) {
                                                                    $featureSettings = $templateFeatures[$feature]['settings'];
                                                                }
                                                            }
                                                            if (!is_array($featureSettings)) {
                                                                $featureSettings = [];
                                                            }
                                                        @endphp
                                                        @foreach($config['settings'] as $setting => $settingConfig)
                                                            <div class="form-group">
                                                                <label for="feature_{{ $feature }}_setting_{{ $setting }}">
                                                                    <i class="{{ $settingConfig['icon'] ?? 'fas fa-cog' }} ml-1"></i>
                                                                    {{ $settingConfig['title'] }}
                                                                </label>
                                                                @if($settingConfig['type'] === 'boolean')
                                                                    <div class="custom-control custom-switch">
                                                                        <input type="checkbox" class="custom-control-input" id="feature_{{ $feature }}_setting_{{ $setting }}" name="features[{{ $feature }}][settings][{{ $setting }}]" value="1" {{ old("features.{$feature}.settings.{$setting}", $featureSettings[$setting] ?? false) ? 'checked' : '' }}>
                                                                        <label class="custom-control-label" for="feature_{{ $feature }}_setting_{{ $setting }}">{{ $settingConfig['description'] }}</label>
                                                                    </div>
                                                                @elseif($settingConfig['type'] === 'select')
                                                                    <select class="form-control select2" id="feature_{{ $feature }}_setting_{{ $setting }}" name="features[{{ $feature }}][settings][{{ $setting }}]">
                                                                        @foreach($settingConfig['options'] as $value => $label)
                                                                            <option value="{{ $value }}" {{ old("features.{$feature}.settings.{$setting}", $featureSettings[$setting] ?? '') == $value ? 'selected' : '' }}>{{ $label }}</option>
                                                                        @endforeach
                                                                    </select>
                                                                @elseif($settingConfig['type'] === 'color')
                                                                    <input type="color" class="form-control" id="feature_{{ $feature }}_setting_{{ $setting }}" name="features[{{ $feature }}][settings][{{ $setting }}]" value="{{ old("features.{$feature}.settings.{$setting}", $featureSettings[$setting] ?? '#000000') }}">
                                                                @else
                                                                    <input type="{{ $settingConfig['type'] }}" class="form-control" id="feature_{{ $feature }}_setting_{{ $setting }}" name="features[{{ $feature }}][settings][{{ $setting }}]" value="{{ old("features.{$feature}.settings.{$setting}", $featureSettings[$setting] ?? '') }}" placeholder="{{ $settingConfig['description'] }}">
                                                                @endif
                                                                @if(!empty($settingConfig['help']))
                                                                    <small class="form-text text-muted">
                                                                        <i class="fas fa-info-circle ml-1"></i>
                                                                        {{ $settingConfig['help'] }}
                                                                    </small>
                                                                @endif
                                                            </div>
                                                        @endforeach
                                                    @endif
                                                    @if(!empty($config['help']))
                                                        <div class="alert alert-info mt-2 p-2 small">{{ $config['help'] }}</div>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                        <div class="card-footer bg-light">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save ml-1"></i>
                                        ذخیره تغییرات
                                    </button>
                                    <a href="{{ route('admin.templates.index') }}" class="btn btn-secondary">
                                        <i class="fas fa-arrow-right ml-1"></i>
                                        بازگشت
                                    </a>
                                </div>
                                <div>
                                    <button type="button" class="btn btn-info" id="previewTemplate">
                                        <i class="fas fa-eye ml-1"></i>
                                        پیش‌نمایش
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- مودال پیش‌نمایش -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">پیش‌نمایش قالب</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .feature-card {
        transition: all 0.3s ease;
    }
    .feature-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    .feature-settings {
        display: none;
    }
    .feature-card.active .feature-settings {
        display: block;
    }
    .select2-container--default .select2-selection--single {
        height: calc(2.25rem + 2px);
        padding: .375rem .75rem;
    }
    .card-header.bg-gradient-primary {
        background: linear-gradient(45deg, #007bff, #6610f2);
    }
    .card-header.bg-gradient-info {
        background: linear-gradient(45deg, #17a2b8, #20c997);
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    // فعال‌سازی Select2
    $('.select2').select2({
        theme: 'bootstrap4',
        width: '100%'
    });
    // مدیریت نمایش/مخفی کردن تنظیمات ویژگی‌ها
    $('.feature-toggle').change(function() {
        var $card = $(this).closest('.feature-card');
        if ($(this).is(':checked')) {
            $card.addClass('active');
            $card.find('.feature-settings').slideDown();
        } else {
            $card.removeClass('active');
            $card.find('.feature-settings').slideUp();
        }
    }).trigger('change');
    // پیش‌نمایش قالب
    $('#previewTemplate').click(function() {
        var formData = new FormData($('#templateForm')[0]);
        $.ajax({
            url: '{{ route("admin.admin.templates.preview", [], false) }}',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#previewModal .modal-body').html(response);
                $('#previewModal').modal('show');
            },
            error: function(xhr) {
                toastr.error('خطا در پیش‌نمایش قالب');
            }
        });
    });
    // اعتبارسنجی فرم
    $('#templateForm').submit(function(e) {
        var isValid = true;
        $(this).find('[required]').each(function() {
            if (!$(this).val()) {
                isValid = false;
                $(this).addClass('is-invalid');
            } else {
                $(this).removeClass('is-invalid');
            }
        });
        if (!isValid) {
            e.preventDefault();
            toastr.error('لطفاً تمام فیلدهای الزامی را پر کنید');
        }
    });
});
</script>
@endpush 