<?php

namespace App\Http\Controllers;

use App\Models\Slide;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class SlideController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        $query = Slide::query();

        // Filter by status
        if ($request->has('status')) {
            $status = $request->status;
            if (in_array($status, ['active', 'inactive'])) {
                $query->where('status', $status);
            }
        }

        // Search by title or subtitle
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title->en', 'like', "%{$search}%")
                    ->orWhere('title->km', 'like', "%{$search}%")
                    ->orWhere('subtitle->en', 'like', "%{$search}%")
                    ->orWhere('subtitle->km', 'like', "%{$search}%");
            });
        }

        // Sorting - default by order then created_at
        $sortBy = $request->get('sort_by', 'order');
        $sortOrder = $request->get('sort_order', 'asc');
        $query->orderBy($sortBy, $sortOrder);

        // Pagination
        $perPage = $request->get('per_page', 15);
        $slides = $query->paginate($perPage);

        // Transform to API format
        $transformedSlides = $slides->getCollection()->map(function ($slide) {
            return $slide->toApiArray();
        });

        return response()->json([
            'success' => true,
            'data' => $transformedSlides,
            'pagination' => [
                'current_page' => $slides->currentPage(),
                'last_page' => $slides->lastPage(),
                'per_page' => $slides->perPage(),
                'total' => $slides->total(),
            ],
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        // Normalize field names (accept both camelCase and snake_case)
        $requestData = $request->all();
        if (isset($requestData['backgroundImage']) && ! isset($requestData['background_image'])) {
            $requestData['background_image'] = $requestData['backgroundImage'];
        }
        if (isset($requestData['ctaText']) && ! isset($requestData['cta_text'])) {
            $requestData['cta_text'] = $requestData['ctaText'];
        }
        if (isset($requestData['ctaLink']) && ! isset($requestData['cta_link'])) {
            $requestData['cta_link'] = $requestData['ctaLink'];
        }

        $validator = Validator::make($requestData, [
            'title' => 'required|array',
            'title.en' => 'required|string|max:255',
            'title.km' => 'nullable|string|max:255',
            'subtitle' => 'nullable|array',
            'subtitle.en' => 'nullable|string|max:500',
            'subtitle.km' => 'nullable|string|max:500',
            'background_image' => 'nullable|string|max:500',
            'cta_text' => 'nullable|array',
            'cta_text.en' => 'nullable|string|max:255',
            'cta_text.km' => 'nullable|string|max:255',
            'cta_link' => 'nullable|string|max:255',
            'order' => 'nullable|integer|min:0',
            'status' => 'nullable|string|in:active,inactive',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        $data = $validator->validated();
        $data['status'] = $data['status'] ?? 'active';
        $data['order'] = $data['order'] ?? 0;

        // Handle empty/null background_image
        if (isset($data['background_image']) && empty($data['background_image'])) {
            $data['background_image'] = null;
        }

        $slide = Slide::create($data);

        return response()->json([
            'success' => true,
            'message' => 'Slide created successfully',
            'data' => $slide->toApiArray(),
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        $slide = Slide::find($id);

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

        return response()->json([
            'success' => true,
            'data' => $slide->toApiArray(),
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        $slide = Slide::find($id);

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

        // Normalize field names (accept both camelCase and snake_case)
        $requestData = $request->all();
        if (isset($requestData['backgroundImage']) && ! isset($requestData['background_image'])) {
            $requestData['background_image'] = $requestData['backgroundImage'];
        }
        if (isset($requestData['ctaText']) && ! isset($requestData['cta_text'])) {
            $requestData['cta_text'] = $requestData['ctaText'];
        }
        if (isset($requestData['ctaLink']) && ! isset($requestData['cta_link'])) {
            $requestData['cta_link'] = $requestData['ctaLink'];
        }

        $validator = Validator::make($requestData, [
            'title' => 'sometimes|required|array',
            'title.en' => 'required_with:title|string|max:255',
            'title.km' => 'nullable|string|max:255',
            'subtitle' => 'nullable|array',
            'subtitle.en' => 'nullable|string|max:500',
            'subtitle.km' => 'nullable|string|max:500',
            'background_image' => 'nullable|string|max:500',
            'cta_text' => 'nullable|array',
            'cta_text.en' => 'nullable|string|max:255',
            'cta_text.km' => 'nullable|string|max:255',
            'cta_link' => 'nullable|string|max:255',
            'order' => 'nullable|integer|min:0',
            'status' => 'nullable|string|in:active,inactive',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        $data = $validator->validated();

        // Handle partial updates for nested JSON fields
        if (isset($data['title'])) {
            $currentTitle = $slide->title ?? [];
            $data['title'] = array_merge($currentTitle, $data['title']);
        }

        if (isset($data['subtitle'])) {
            $currentSubtitle = $slide->subtitle ?? [];
            $data['subtitle'] = array_merge($currentSubtitle, $data['subtitle']);
        }

        if (isset($data['cta_text'])) {
            $currentCtaText = $slide->cta_text ?? [];
            $data['cta_text'] = array_merge($currentCtaText, $data['cta_text']);
        }

        // Handle background_image update - allow null/empty to clear the field
        if (array_key_exists('background_image', $data)) {
            if (empty($data['background_image'])) {
                $data['background_image'] = null;
            }
        }

        $slide->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Slide updated successfully',
            'data' => $slide->fresh()->toApiArray(),
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): JsonResponse
    {
        $slide = Slide::find($id);

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

        // Delete associated image if exists
        if ($slide->background_image) {
            // Remove /storage/ prefix if present
            $imagePath = str_replace('/storage/', '', $slide->background_image);
            if (Storage::disk('public')->exists($imagePath)) {
                Storage::disk('public')->delete($imagePath);
            }
        }

        $slide->delete();

        return response()->json([
            'success' => true,
            'message' => 'Slide deleted successfully',
        ]);
    }
}
