<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\SliderItem;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class SliderController extends Controller
{
    public function index()
    {
        $sliders = SliderItem::get();
        return view('backend.sliders.index', compact('sliders'));
    }

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

    public function store(Request $request)
    {
        $item = SliderItem::create([
            'link' => $request->input('link')
        ]);
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $path = 'public/sliders/';
            $path = $request->file('image')->storeAs($path, $item->id . '.' . $file->getClientOriginalExtension());
            $item->image = $item->id . '.' . $file->getClientOriginalExtension();
            $item->save();
        }

        return redirect()->route('backend.sliders.index');
    }

    public function edit($id)
    {
        $item = SliderItem::find($id);
        return view('backend.sliders.edit', compact('item'));
    }
    public function update(Request $request, $id)
    {
        $item = SliderItem::find($id);
        $item->fill($request->only(['link']));
        $item->save();

        if ($request->hasFile('image')) {
            // Delete old file
            $path = 'public/sliders/'. $item->image;
            if (!empty($item->image) && File::exists(storage_path('app/' . $path))) {
                Storage::delete($path);
            }
            // Upload new file
            $file = $request->file('image');
            $path = 'public/sliders/';
            $path = $request->file('image')->storeAs($path, $item->id . '.' . $file->getClientOriginalExtension());
            $item->image = $item->id . '.' . $file->getClientOriginalExtension();
            $item->save();
        }

        return redirect()->route('backend.sliders.index');
    }

    public function delete($id)
    {
        $item = SliderItem::find($id);
        $item->delete();

        return redirect()->route('backend.sliders.index');
    }
}
