<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Webinar;
use App\Models\WebinarInstructorHighlight;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class InstructorHighlightsController extends Controller
{
    public function get($webinarId)
    {
        $this->authorize('admin_webinars_edit');

        if (!ensureWebinarInstructorHighlightsTable()) {
            return response()->json([
                'status' => 'error',
                'msg' => 'جدول webinar_instructor_highlights غير موجود. شغّل: php artisan migrate',
                'items' => [],
            ], 500);
        }

        $webinar = Webinar::findOrFail($webinarId);

        $items = $webinar->instructor_highlights()
            ->orderBy('order')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'icon' => $item->icon,
                    'value' => $item->value,
                    'label' => $item->label,
                    'order' => $item->order,
                    'status' => $item->status ? 1 : 0,
                ];
            });

        return response()->json([
            'status' => 'success',
            'items' => $items,
        ]);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_webinars_edit');

        if (!ensureWebinarInstructorHighlightsTable()) {
            return response()->json([
                'status' => 'error',
                'msg' => 'جدول webinar_instructor_highlights غير موجود. شغّل: php artisan migrate',
            ], 500);
        }

        $items = $request->input('items', []);
        if (!is_array($items)) {
            $items = [];
        }

        $filtered = [];
        foreach ($items as $item) {
            if (!is_array($item)) {
                continue;
            }
            $value = trim((string) ($item['value'] ?? ''));
            $label = trim((string) ($item['label'] ?? ''));
            if ($value === '' && $label === '') {
                continue;
            }
            $filtered[] = $item;
        }

        $request->merge(['items' => $filtered]);

        $validator = Validator::make($request->all(), [
            'webinar_id' => 'required|exists:webinars,id',
            'items' => 'array',
            'items.*.icon' => 'nullable|string|max:64',
            'items.*.value' => 'nullable|string|max:255',
            'items.*.label' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'msg' => $validator->errors()->first(),
                'errors' => $validator->errors()->toArray(),
            ], 422);
        }

        $webinar = Webinar::findOrFail($request->input('webinar_id'));

        WebinarInstructorHighlight::where('webinar_id', $webinar->id)->delete();

        foreach ($filtered as $index => $item) {
            WebinarInstructorHighlight::create([
                'webinar_id' => $webinar->id,
                'icon' => $this->sanitizeIcon($item['icon'] ?? 'award'),
                'value' => trim((string) ($item['value'] ?? '')),
                'label' => trim((string) ($item['label'] ?? '')),
                'order' => $index,
                'status' => (array_key_exists('status', $item) && (int) $item['status'] === 0) ? 0 : 1,
            ]);
        }

        return response()->json([
            'status' => 'success',
            'msg' => 'تم حفظ بطاقات المدرب بنجاح',
            'count' => count($filtered),
        ]);
    }

    private function sanitizeIcon($icon)
    {
        $icon = preg_replace('/[^a-z0-9-]/', '', mb_strtolower((string) $icon));
        $allowed = [
            'users', 'award', 'book-open', 'clock', 'star', 'check-circle',
            'layers', 'play-circle', 'monitor', 'calendar', 'target', 'heart',
        ];

        return in_array($icon, $allowed, true) ? $icon : 'award';
    }
}
