<?php

namespace App\Http\Controllers;

use App\Models\SliderModel;
use Illuminate\Http\Request;

class SliderController extends Controller
{
    public function index()
    {
        $data = SliderModel::allSlider();
        return view('dashboard.slider.slider', ['data' => $data]);
    }

    public function store(Request $request)
    {
        $imageName = time() . '.' . $request->foto->extension();

        $request->foto->move(public_path('storage/slider'), $imageName);

        $slider = new SliderModel();
        $slider->gambar = $imageName;
        $slider->tanggal_post = date('Y-m-d');
        $slider->save();

        return redirect()->route('slider')
            ->with('success', 'Slider berhasil ditambahkan');
    }

    public function update(Request $request, $id_slider)
    {
        $slider = SliderModel::find($id_slider);

        if ($request->hasFile('foto')) {
            if ($slider->gambar && file_exists(public_path('storage/slider/' . $slider->gambar))) {
                unlink(public_path('storage/slider/' . $slider->gambar));
            }

            $imageName = time() . '.' . $request->foto->extension();
            $request->foto->move(public_path('storage/slider'), $imageName);
            $slider->gambar = $imageName;
        }

        $slider->tanggal_post = date('Y-m-d');
        $slider->save();

        return redirect()->route('slider')
            ->with('success', 'Slider berhasil diperbarui');
    }
    public function destroy(Request $request)
    {
        $id_slider = $request->input('id_slider');
        $slider = SliderModel::find($id_slider);
        if ($slider->gambar) {
            unlink(public_path('storage/slider/' . $slider->gambar));
        }
        $slider->delete();
        return redirect()->route('slider')
            ->with('success', 'Slider berhasil dihapus');
    }
}
