<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use AleshaCMS\Models\CMS\Slider;
use AleshaCMS\Models\CMS\SliderSlide;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SliderController extends Controller
{
    public function index()
    {
        $sliders = Slider::withCount('slides')->latest()->get();
        return view('admin.sliders.index', compact('sliders'));
    }

    public function create()
    {
        return view('admin.sliders.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'     => 'required|string|max:100',
            'slug'     => 'nullable|string|max:100|unique:sliders',
            'autoplay' => 'boolean',
            'interval' => 'integer|min:1000|max:30000',
        ]);

        $data['slug']     = $data['slug'] ?? Str::slug($data['name']);
        $data['autoplay'] = $request->boolean('autoplay', true);
        $data['interval'] = $data['interval'] ?? 5000;

        $slider = Slider::create($data);

        if ($request->wantsJson()) {
            return response()->json([
                'success'  => true,
                'message'  => 'Slider created.',
                'redirect' => route('admin.sliders.edit', $slider->id),
            ]);
        }

        return redirect()->route('admin.sliders.edit', $slider->id)->with('success', 'Slider created.');
    }

    public function edit(Slider $slider)
    {
        $slider->load('slides');
        return view('admin.sliders.edit', compact('slider'));
    }

    public function update(Request $request, Slider $slider)
    {
        if (is_string($request->slides)) {
            $request->merge(['slides' => json_decode($request->slides, true) ?? []]);
        }

        $data = $request->validate([
            'name'     => 'required|string|max:100',
            'slug'     => 'nullable|string|max:100|unique:sliders,slug,' . $slider->id,
            'autoplay' => 'boolean',
            'interval' => 'integer|min:1000|max:30000',
            'slides'   => 'present|array',
        ]);

        $slider->update([
            'name'     => $data['name'],
            'slug'     => $data['slug'] ?? $slider->slug,
            'autoplay' => $request->boolean('autoplay', true),
            'interval' => $data['interval'] ?? 5000,
        ]);

        $incomingIds = array_filter(array_column($data['slides'], 'id'));
        $slider->slides()->whereNotIn('id', $incomingIds)->delete();

        foreach ($data['slides'] as $sort => $slide) {
            $attrs = [
                'slider_id'     => $slider->id,
                'title'         => $slide['title'] ?? null,
                'subtitle'      => $slide['subtitle'] ?? null,
                'image_url'     => $slide['image_url'] ?? null,
                'button_text'   => $slide['button_text'] ?? null,
                'button_url'    => $slide['button_url'] ?? null,
                'button_target' => $slide['button_target'] ?? '_self',
                'sort_order'    => $sort,
                'is_active'     => $slide['is_active'] ?? true,
            ];

            if (!empty($slide['id']) && is_numeric($slide['id'])) {
                $existing = SliderSlide::find($slide['id']);
                $existing ? $existing->update($attrs) : SliderSlide::create($attrs);
            } else {
                SliderSlide::create($attrs);
            }
        }

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Slider saved.']);
        }

        return back()->with('success', 'Slider saved.');
    }

    public function destroy(Slider $slider)
    {
        $slider->delete();

        if (request()->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Slider deleted.']);
        }

        return redirect()->route('admin.sliders.index')->with('success', 'Slider deleted.');
    }
}
