<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bundle;
use App\Models\WebinarFeature;
use App\Models\Translation\WebinarFeatureTranslation;
use App\Models\Webinar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

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

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

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

            $data = $request->all();

            $creator = null;

            if (!empty($data['webinar_id'])) {
                $webinar = Webinar::findOrFail($data['webinar_id']);

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

                $creator = $bundle->creator;
                Log::info('Feature Store - Bundle found', ['bundle_id' => $bundle->id, 'creator_id' => $creator->id ?? null]);
            }

            if (!empty($creator)) {
                // Insert feature row manually to avoid Translatable ID issues
                $insertData = [
                    'webinar_id' => !empty($data['webinar_id']) ? intval($data['webinar_id']) : null,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];

                Log::info('Feature Store - Step 1: Before insert', [
                    'insertData' => $insertData,
                ]);

                $pdo = DB::connection()->getPdo();
                $stmt = $pdo->prepare("INSERT INTO webinar_features (webinar_id, created_at, updated_at) VALUES (?, ?, ?)");
                $stmt->execute([
                    $insertData['webinar_id'],
                    $insertData['created_at'],
                    $insertData['updated_at'],
                ]);

                $id = (int) $pdo->lastInsertId();

                Log::info('Feature Store - Step 2: After insert', [
                    'id' => $id,
                ]);

                if ($id > 0) {
                    Log::info('Feature Store - Step 3: Creating translation', [
                        'webinar_feature_id' => $id,
                        'locale' => mb_strtolower($data['locale']),
                        'description' => $data['description'],
                    ]);

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

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

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

            Log::info('Feature Store - Success');

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

        } catch (\Illuminate\Validation\ValidationException $e) {
            Log::error('Feature Store - Validation failed', [
                'errors' => $e->errors(),
            ]);

            return response()->json([
                'code' => 422,
                'title' => 'خطأ في التحقق',
                'text' => 'يرجى التحقق من البيانات المدخلة',
                'errors' => $e->errors(),
            ], 422);

        } catch (\Exception $e) {
            Log::error('Feature 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 = WebinarFeature::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');

        $faq = WebinarFeature::find($id);

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

            $faq->description = $faq->getDescriptionAttribute();
            $faq->locale = mb_strtoupper($locale);

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

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

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

        $this->validate($request, [
            'description' => 'required',
        ]);

        $data = $request->all();
        $feature = WebinarFeature::findOrFail($id);

        $feature->update([
            'updated_at' => now(),
        ]);

        WebinarFeatureTranslation::updateOrCreate([
            'webinar_feature_id' => $feature->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');

        $feature = WebinarFeature::find($id);

        if (!empty($feature)) {
            $feature->delete();
        }

        return redirect()->back();
    }
}
