<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class AdminSliderManagementController extends Controller
{
    public function SliderManagement()
    {
        $sliders = Banner::latest()->paginate(10);
        return view('adminDashboard.slider-management', compact('sliders'));
    }

    public function AddSliderManagement(Request $request)
    {
        $request->validate([
            'type' => 'required',
            'banner_title' => 'required'
        ]);

        if ($request->type == 'image') {
            $request->validate([
                'file_name' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            ]);
            if ($request->hasFile('file_name')) {
                $image = $request->file('file_name');
                $ext = $image->extension();
                $image_name = time() . uniqid() . '.' . $ext;
                request()->file_name->move(public_path('assets/img/banner'), $image_name);
                $request->request->add(['path' => '/banner/' . $image_name]);
            }
        } else if ($request->type == 'video') {
            $request->validate([
                'file_name' => 'required',
            ]);
            $request->request->add(['path' => $request->file_name]);
        }
        Banner::create($request->all());


        Session::flash('message', 'Slider Saved Successfully.');
        Session::flash('alert-type', 'success');
        return redirect()->back();
    }

    public function DeleteSlider($id)
    {
        $slider = Banner::findOrFail($id);
        if ($slider->type == "image") {
            $img = public_path("assets/img") . $slider->path;
            if (is_file($img)) {
                unlink($img);
            }
        }
        $slider->delete();
        return redirect()->back();
    }
}
