<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ContentSection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TestimonialsController extends Controller
{
    public function index()
    {
        $testimonialsSection = ContentSection::where('section_key', 'testimonials')
            ->first();

        return view('admin.testimonials.index', compact('testimonialsSection'));
    }

    public function edit()
    {
        $testimonialsSection = ContentSection::where('section_key', 'testimonials')
            ->first();

        return view('admin.testimonials.edit', compact('testimonialsSection'));
    }

    public function update(Request $request)
    {
        try {
            $request->validate([
                'title' => 'required|string|max:255',
                'content' => 'required|string|max:500',
            ]);

            $testimonialsSection = ContentSection::where('section_key', 'testimonials')->first();

            if (!$testimonialsSection) {
                return redirect()->back()->with('error', 'Testimonials section not found.');
            }

            // Get existing data
            $existingData = $testimonialsSection->getAttribute('data') ?? [];

            // Update basic info using updateOrCreate
            ContentSection::updateOrCreate(
                ['section_key' => 'testimonials'],
                [
                    'title' => $request->input('title'),
                    'content' => $request->input('content'),
                    'is_active' => true,
                    'data' => $existingData
                ]
            );

            return redirect()->route('admin.testimonials.edit')
                ->with('success', 'Testimonials section updated successfully!');
        } catch (\Exception $e) {
            Log::error('Error updating testimonials section: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while updating the testimonials section.');
        }
    }

    public function addTestimonial(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'position' => 'required|string|max:255',
                'message' => 'required|string|max:1000',
                'rating' => 'required|integer|min:1|max:5',
            ]);

            $testimonialsSection = ContentSection::where('section_key', 'testimonials')->first();

            if (!$testimonialsSection) {
                return response()->json([
                    'success' => false,
                    'message' => 'Testimonials section not found.'
                ], 404);
            }

            // Get existing testimonials
            $data = $testimonialsSection->getAttribute('data') ?? [];
            $existingTestimonials = isset($data['testimonials']) ? $data['testimonials'] : [];

            // Add new testimonial
            $newTestimonial = [
                'name' => $request->input('name'),
                'position' => $request->input('position'),
                'message' => $request->input('message'),
                'rating' => (int) $request->input('rating'),
            ];

            $existingTestimonials[] = $newTestimonial;

            // Update section with new testimonials
            ContentSection::updateOrCreate(
                ['section_key' => 'testimonials'],
                [
                    'title' => $testimonialsSection->getAttribute('title') ?? 'Student Success Stories',
                    'content' => $testimonialsSection->getAttribute('content') ?? 'What our students say?',
                    'is_active' => true,
                    'data' => ['testimonials' => $existingTestimonials]
                ]
            );

            return response()->json([
                'success' => true,
                'message' => 'Testimonial added successfully!',
                'testimonial' => $newTestimonial
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            Log::error('Error adding testimonial: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while adding the testimonial.'
            ], 500);
        }
    }

    public function removeTestimonial(Request $request)
    {
        try {
            $request->validate([
                'index' => 'required|integer|min:0',
            ]);

            $testimonialsSection = ContentSection::where('section_key', 'testimonials')->first();

            if (!$testimonialsSection) {
                return response()->json([
                    'success' => false,
                    'message' => 'Testimonials section not found.'
                ], 404);
            }

            // Get existing testimonials
            $data = $testimonialsSection->getAttribute('data') ?? [];
            $existingTestimonials = isset($data['testimonials']) ? $data['testimonials'] : [];

            $index = $request->input('index');

            if (!isset($existingTestimonials[$index])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Testimonial not found.'
                ], 404);
            }

            // Remove testimonial
            array_splice($existingTestimonials, $index, 1);

            // Update section with remaining testimonials
            ContentSection::updateOrCreate(
                ['section_key' => 'testimonials'],
                [
                    'title' => $testimonialsSection->getAttribute('title') ?? 'Student Success Stories',
                    'content' => $testimonialsSection->getAttribute('content') ?? 'What our students say?',
                    'is_active' => true,
                    'data' => ['testimonials' => $existingTestimonials]
                ]
            );

            return response()->json([
                'success' => true,
                'message' => 'Testimonial removed successfully!'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            Log::error('Error removing testimonial: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while removing the testimonial.'
            ], 500);
        }
    }
}
