<?php

namespace App\Http\Controllers;

use App\Models\Banner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class BannerController extends Controller
{
    public function index()
    {
        $banners = Banner::all();
        return view('admin.pages.banners.index', compact('banners'));
    }

    public function create()
    {
        return view('admin.pages.banners.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'image_name' => 'required|string|max:255',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $filename = time() . '.' . $request->image->getClientOriginalExtension();
        $uploadPath = 'uploads/banner';
        $request->image->move($uploadPath, $filename);

        Banner::create([
            'image_name' => $request->image_name,
            'image' => $uploadPath . '/' . $filename,
        ]);

        return redirect()->route('banner.index')->with('success', 'Banner created successfully.');
    }

    public function edit(Banner $banner)
    {
        return view('admin.pages.banners.edit', compact('banner'));
    }

    public function update(Request $request, Banner $banner)
    {
        $request->validate([
            'image_name' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $imagePath = $banner->image;

        if ($request->hasFile('image')) {
            // Delete old image
            if ($banner->image && File::exists($banner->image)) {
                File::delete($banner->image);
            }

            // Upload new image
            $filename = time() . '.' . $request->image->getClientOriginalExtension();
            $uploadPath = 'uploads/banner';
            $request->image->move($uploadPath, $filename);
            $imagePath = $uploadPath . '/' . $filename;
        }

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

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

    public function destroy(Banner $banner)
    {
        if ($banner->image && File::exists($banner->image)) {
            File::delete($banner->image);
        }

        $banner->delete();

        return redirect()->route('banner.index')->with('success', 'Banner deleted successfully.');
    }
}