<?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 WhyLeclController extends Controller
{
    public function index()
    {
        $whyLeclSection = ContentSection::where('section_key', 'why_lecl')
            ->first();

        return view('admin.why-lecl.index', compact('whyLeclSection'));
    }

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

        return view('admin.why-lecl.edit', compact('whyLeclSection'));
    }

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

            $whyLeclSection = ContentSection::where('section_key', 'why_lecl')->first();

            if (!$whyLeclSection) {
                return redirect()->back()->with('error', 'Why Select LECL section not found.');
            }

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

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

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

    public function addBenefit(Request $request)
    {
        try {
            $request->validate([
                'title' => 'required|string|max:255',
                'description' => 'required|string|max:1000',
                'icon' => 'required|string|max:255',
                'color' => 'nullable|string|max:50',
            ]);

            $whyLeclSection = ContentSection::where('section_key', 'why_lecl')->first();

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

            // Get existing benefits
            $data = $whyLeclSection->getAttribute('data') ?? [];
            $existingBenefits = isset($data['benefits']) ? $data['benefits'] : [];

            // Add new benefit
            $newBenefit = [
                'title' => $request->input('title'),
                'description' => $request->input('description'),
                'icon' => $request->input('icon'),
                'color' => $request->input('color') ?: 'var(--primary-navy)',
            ];

            $existingBenefits[] = $newBenefit;

            // Update section with new benefits
            ContentSection::updateOrCreate(
                ['section_key' => 'why_lecl'],
                [
                    'title' => $whyLeclSection->getAttribute('title') ?? 'Why Select LECL?',
                    'content' => $whyLeclSection->getAttribute('content') ?? 'Countless Benefits & Easy Processing',
                    'is_active' => true,
                    'data' => ['benefits' => $existingBenefits]
                ]
            );

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

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

            $whyLeclSection = ContentSection::where('section_key', 'why_lecl')->first();

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

            // Get existing benefits
            $data = $whyLeclSection->getAttribute('data') ?? [];
            $existingBenefits = isset($data['benefits']) ? $data['benefits'] : [];

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

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

            // Remove benefit
            array_splice($existingBenefits, $index, 1);

            // Update section with remaining benefits
            ContentSection::updateOrCreate(
                ['section_key' => 'why_lecl'],
                [
                    'title' => $whyLeclSection->getAttribute('title') ?? 'Why Select LECL?',
                    'content' => $whyLeclSection->getAttribute('content') ?? 'Countless Benefits & Easy Processing',
                    'is_active' => true,
                    'data' => ['benefits' => $existingBenefits]
                ]
            );

            return response()->json([
                'success' => true,
                'message' => 'Benefit 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 benefit: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while removing the benefit.'
            ], 500);
        }
    }
}