<?php

namespace App\Http\Controllers\Admin;

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

class GalleryController extends Controller
{
    public function index()
    {
        $galleryItems = GalleryItem::latest()->paginate(12);
        return view('admin.gallery.index', compact('galleryItems'));
    }

    public function show($id)
    {
        $item = GalleryItem::findOrFail($id);
        return view('admin.gallery.show', compact('item'));
    }

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

        $file = $request->file('image');
        $filename = 'gallery_' . time() . '_' . $file->getClientOriginalName();
        $file->move(public_path('uploads/gallery'), $filename);

        GalleryItem::create([
            'image_path' => 'uploads/gallery/' . $filename,
            'caption' => $request->caption,
            'category' => $request->category ?? 'general',
        ]);

        return redirect()->route('admin.gallery.index')->with('success', 'Image added to gallery successfully.');
    }

    public function destroy($id)
    {
        $item = GalleryItem::findOrFail($id);
        
        if (file_exists(public_path($item->image_path))) {
            unlink(public_path($item->image_path));
        }
        
        $item->delete();

        return redirect()->route('admin.gallery.index')->with('success', 'Image removed from gallery.');
    }
}
