<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\SliderModel;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SliderController extends Controller
{
    public function addSlider(): View
    {
        return view('admin.add-slider', [
        ]);
    }

    public function storeSlider(Request $request): RedirectResponse
    {
        $slider = new SliderModel();

        $request->validate([
            'title' => 'required',
            'description' => 'required',
            'path' => 'required',
            'index' => 'required',
        ]);

        // Determine the values of active and featured based on the checkbox status
        $active = $request->has('active') ? 1 : 0;
        $featured = $request->has('featured') ? 1 : 0;


        $slider->title = $request->title;
        $slider->description = $request->description;
        $slider->active = $active;
        $slider->featured = $featured;
        $slider->image = $request->path;
        $slider->index = $request->index;
        $slider->slug = strtolower(str_replace(' ', '-', $request->title));

        $slider->save();

        return redirect()->route('list-sliders')->with('success', 'Slider created successfully');

    }


    public function listSliders(): View
    {
        $sliders = SliderModel::all();
        return view('admin.list-slider', [
            'sliders' => $sliders,
        ]);
    }


    public function editSlider($id): View
    {

        $slider = SliderModel::findOrFail($id);


        return view('admin.edit-slider', [
            'slider' => $slider,
        ]);
    }


    public function updateSlider(Request $request): RedirectResponse
    {

        $request->validate([
            'title' => 'required',
            'description' => 'required',
            'path' => 'required',
            'index' => 'required',
        ]);

        $id = $request->id;


        // Determine the values of active and featured based on the checkbox status
        $active = $request->has('active') ? 1 : 0;
        $featured = $request->has('featured') ? 1 : 0;

        SliderModel::findOrFail($id)->update([
            'title' => $request->title,
            'description' => $request->description,
            'active' => $active,
            'featured' => $featured,
            'image' => $request->path,
            'index' => $request->index,
            'slug' => strtolower(str_replace(' ', '-', $request->title)),
        ]);

        return redirect()->route('list-sliders')->with('success', 'Slider updated successfully');

    }


    public function deleteSlider($id): RedirectResponse
    {
        SliderModel::findOrFail($id)->delete();
        return redirect()->route('list-sliders')->with('success', 'Slider deleted successfully');

    }

}
