<?php

namespace App\Http\Controllers;

use App\Models\Homebanner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class HomeBannerController extends Controller
{
    public function store(Request $request)
    {   

        $request->validate([
            'heading'=> 'required|string|max:255',
            'description'=> 'required|string|max:255',
            'image'=> 'required|image|mimes:jpeg,png,jpg,webp|max:2048|dimensions:min_width=1920,min_height=1080',
        ]);

        $imagePath=null;

        if ($request->hasfile('image')){
            $imagePath = $request->file('image')->store('homebanners', 'public');
        }

        $banner=Homebanner::create([
            'heading' => $request->heading,
            'description' => $request->description,
            'image' => $imagePath,
        ]);

        return redirect()
            ->route('home-banners.index')
            ->with('success', 'Home banner created successfully.');
    }
    public function index()
    {
        $banners = Homebanner::latest()->get();
        return view('homebanner.index', compact('banners'));
    }
    public function create(){
        return view('homebanner.create');
    }
    public function show($id){
        $banner = Homebanner::findOrFail($id);
        return view('homebanner.show', compact('banner'));
    }
    public function edit($id){
        $homebanner = Homebanner::findOrFail($id);
        return view('homebanner.edit', compact('homebanner'));
    }
    public function destroy($id){
        $banner=Homebanner::findOrFail($id);

        if (!empty($banner->image) && Storage::disk('public')->exists($banner->image)){
            Storage::disk('public')->delete($banner->image);
        }
        $banner->delete();
        return redirect()
            ->route('home-banners.index')
            ->with('success', 'Home banner deleted successfully.');
    }
    public function update(Request $request, $id){
        $banner = Homebanner::findOrFail($id);

        $request->validate([
            'heading' => 'required|string|max:255',
            'description' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
        ]);

        $imagePath = $banner->image;

        if ($request->hasFile('image')) {
            if (!empty($banner->image) && Storage::disk('public')->exists($banner->image)) {
                Storage::disk('public')->delete($banner->image);
            }

            $imagePath = $request->file('image')->store('homebanners', 'public');
        }

        $banner->update([
            'heading' => $request->heading,
            'description' => $request->description,
            'image' => $imagePath,
        ]);

        return redirect()
            ->route('home-banners.index')
            ->with('success', 'Home banner updated successfully.');
    }
}
