<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\WebinarInstructorTestimonial;
use App\Models\Translation\WebinarInstructorTestimonialTranslation;
use App\Models\Webinar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

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

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

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

            $data = $request->all();

            $webinar = Webinar::findOrFail($data['webinar_id']);
            Log::info('InstructorTestimonials Store - Webinar found', ['webinar_id' => $webinar->id]);

            $insertData = [
                'webinar_id' => (int) $data['webinar_id'],
                'created_at' => now(),
                'updated_at' => now(),
            ];

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

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

            if ($id <= 0) {
                Log::error('InstructorTestimonials Store - Failed to insert testimonial', ['id' => $id]);
                throw new \Exception('Failed to insert WebinarInstructorTestimonial');
            }

            WebinarInstructorTestimonialTranslation::updateOrCreate([
                'webinar_instructor_testimonial_id' => $id,
                'locale' => mb_strtolower($data['locale'] ?? app()->getLocale()),
            ], [
                'name' => $data['name'],
                'comment' => $data['comment'],
            ]);

            Log::info('InstructorTestimonials Store - Success', ['id' => $id]);

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

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

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

        } catch (\Exception $e) {
            Log::error('InstructorTestimonials 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 = WebinarInstructorTestimonial::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 = WebinarInstructorTestimonial::find($id);

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

            $faq->name = $faq->getNameAttribute();
            $faq->comment = $faq->getCommentAttribute();
            $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, [
            'name' => 'required',
            'comment' => 'required',
        ]);

        $data = $request->all();

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

        if ($faq) {
            $faq->update([
                'updated_at' => time()
            ]);

            WebinarInstructorTestimonialTranslation::updateOrCreate([
                'webinar_instructor_testimonial_id' => $faq->id,
                'locale' => mb_strtolower($data['locale']),
            ], [
                  'name' => $data['name'],
                    'comment' => $data['comment'],
            ]);
        }

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

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

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

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