<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bundle;
use App\Models\WebinarForItem;
use App\Models\Translation\WebinarForItemTranslation;
use App\Models\Webinar;
use Illuminate\Http\Request;

class ForItemController extends Controller
{
    public function store(Request $request)
    {
        \Log::info('ForItem Store - Start', [
            'all_data' => $request->all(),
        ]);

        try {
            $this->authorize('admin_webinars_edit');
            ensureWebinarForItemsIconColumn();
            \Log::info('ForItem Store - Authorization passed');

            $this->validate($request, [
                'description' => 'required',
                'image' => 'nullable',
                'webinar_id' => 'required',
            ]);
            \Log::info('ForItem Store - Validation passed');

            $data = $request->all();

            $creator = null;

            if (!empty($data['webinar_id'])) {
                $webinar = Webinar::findOrFail($data['webinar_id']);
                \Log::info('ForItem Store - Webinar found', ['webinar_id' => $webinar->id]);

                $creator = $webinar->creator;
                \Log::info('ForItem Store - Creator found', ['creator_id' => $creator->id ?? 'null']);
            } else if (!empty($data['bundle_id'])) {
                $bundle = Bundle::findOrFail($data['bundle_id']);
                \Log::info('ForItem Store - Bundle found', ['bundle_id' => $bundle->id]);

                $creator = $bundle->creator;
            }

            if (!empty($creator)) {
                \Log::info('ForItem Store - Step 1: Before creating WebinarForItem object', [
                    'webinar_id_raw' => $data['webinar_id'] ?? null,
                    'webinar_id_int' => intval($data['webinar_id'] ?? 0),
                    'image' => $data['image'] ?? null,
                ]);

                // Insert directly using PDO to get the ID
                $insertData = [
                    'webinar_id' => !empty($data['webinar_id']) ? intval($data['webinar_id']) : null,
                    'bundle_id' => !empty($data['bundle_id']) ? intval($data['bundle_id']) : null,
                    'image' => !empty($data['image']) ? $data['image'] : null,
                    'icon' => $this->sanitizeIcon($data['icon'] ?? 'users'),
                    'background_color' => !empty($data['background_color']) ? $data['background_color'] : null,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
                
                \Log::info('ForItem Store - Step 2: Before insert', [
                    'insertData' => $insertData,
                ]);
                
                // Use PDO directly to ensure we get the ID
                $pdo = \DB::connection()->getPdo();
                $hasIcon = $this->hasIconColumn();
                if ($hasIcon) {
                    $stmt = $pdo->prepare("INSERT INTO webinar_for_items (webinar_id, bundle_id, image, icon, background_color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $insertData['webinar_id'],
                        $insertData['bundle_id'],
                        $insertData['image'],
                        $insertData['icon'],
                        $insertData['background_color'],
                        $insertData['created_at'],
                        $insertData['updated_at'],
                    ]);
                } else {
                    $stmt = $pdo->prepare("INSERT INTO webinar_for_items (webinar_id, bundle_id, image, background_color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $insertData['webinar_id'],
                        $insertData['bundle_id'],
                        $insertData['image'],
                        $insertData['background_color'],
                        $insertData['created_at'],
                        $insertData['updated_at'],
                    ]);
                }
                $id = $pdo->lastInsertId();
                
                \Log::info('ForItem Store - Step 3: After insert', [
                    'id' => $id,
                ]);
                
                if ($id > 0) {
                    // Load the model with the correct ID
                    $faq = WebinarForItem::find($id);
                    
                    \Log::info('ForItem Store - Step 4: Model loaded', [
                        'id' => $faq->id,
                        'webinar_id' => $faq->webinar_id,
                    ]);
                }

                if ($id > 0) {
                    \Log::info('ForItem Store - Step 5: Creating translation', [
                        'webinar_for_item_id' => $id,
                        'locale' => mb_strtolower($data['locale']),
                        'description' => $data['description'],
                    ]);

                    WebinarForItemTranslation::updateOrCreate([
                        'webinar_for_item_id' => $id,
                        'locale' => mb_strtolower($data['locale']),
                    ], [
                        'description' => $data['description'],
                    ]);

                    \Log::info('ForItem Store - Step 6: Translation created');
                } else {
                    \Log::error('ForItem Store - Failed to insert', [
                        'id' => $id,
                    ]);
                    throw new \Exception('Failed to insert WebinarForItem - ID is ' . $id);
                }

            } else {
                \Log::warning('ForItem Store - No creator found', [
                    'webinar_id' => $data['webinar_id'] ?? null,
                    'bundle_id' => $data['bundle_id'] ?? null,
                ]);
            }

            \Log::info('ForItem Store - Success');
            
            return response()->json([
                'code' => 200,
                'title' => 'نجح',
                'text' => 'تم الحفظ بنجاح',
            ], 200);

        } catch (\Illuminate\Validation\ValidationException $e) {
            \Log::error('ForItem Store - Validation failed', [
                'errors' => $e->errors(),
            ]);
            
            return response()->json([
                'code' => 422,
                'title' => 'خطأ في التحقق',
                'text' => 'يرجى التحقق من البيانات المدخلة',
                'errors' => $e->errors(),
            ], 422);

        } catch (\Exception $e) {
            \Log::error('ForItem Store - Exception', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            
            return response()->json([
                'code' => 500,
                'title' => 'خطأ',
                'text' => 'حدث خطأ أثناء الحفظ: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function description(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        removeContentLocale();

        $faq = WebinarForItem::where('id', $id)
            ->first();

        if (!empty($faq)) {
            return response()->json([
                'faq' => $faq
            ], 200);
        }

        return response()->json([], 422);
    }

    public function edit(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $item = WebinarForItem::find($id);

        if (!empty($item)) {
            $locale = $request->get('locale', app()->getLocale());
            if (empty($locale)) {
                $locale = app()->getLocale();
            }
            storeContentLocale($locale, $item->getTable(), $item->id);

            $item->description = $item->getDescriptionAttribute();
            $item->background_color = $item->background_color ?? '';
            $item->icon = $item->icon ?? 'users';
            $item->locale = mb_strtoupper($locale);

            return response()->json([
                'faq' => $item,
            ], 200);
        }

        return response()->json([], 422);
    }

    public function update(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');
        ensureWebinarForItemsIconColumn();

        $this->validate($request, [
            'description' => 'required',
            'image' => 'nullable',
            'icon' => 'nullable|string|max:64',
        ]);

        $data = $request->all();
        $item = WebinarForItem::findOrFail($id);

        $updateData = [
            'updated_at' => now(),
            'image' => !empty($data['image']) ? $data['image'] : null,
            'background_color' => !empty($data['background_color']) ? $data['background_color'] : null,
        ];

        if ($this->hasIconColumn()) {
            $updateData['icon'] = $this->sanitizeIcon($data['icon'] ?? 'users');
        }

        $item->update($updateData);

        WebinarForItemTranslation::updateOrCreate([
            'webinar_for_item_id' => $item->id,
            'locale' => mb_strtolower($data['locale'] ?? app()->getLocale()),
        ], [
            'description' => $data['description'],
        ]);

        return response()->json([
            'code' => 200,
            'title' => 'نجح',
            'text' => 'تم الحفظ بنجاح',
        ], 200);
    }

    public function destroy(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        WebinarForItem::find($id)->delete();

        return redirect()->back();
    }

    private function hasIconColumn(): bool
    {
        try {
            $columns = \DB::select("SHOW COLUMNS FROM webinar_for_items WHERE Field = 'icon'");

            return !empty($columns);
        } catch (\Exception $e) {
            return false;
        }
    }

    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',
            'briefcase', 'globe', 'smile', 'zap',
        ];

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