<?php

namespace App\Http\Controllers;

use App\Models\Gallery;
use Illuminate\Http\Request;

class GalleryController extends Controller
{
    public function index()
    {
        $galleries = Gallery::latest()->paginate(12);
        $categories = Gallery::distinct()->pluck('category');
        return view('pages.gallery', compact('galleries', 'categories'));
    }

    // Admin Gallery Methods
    public function adminIndex()
    {
        $galleries = Gallery::latest()->paginate(15);
        return view('admin.gallery.index', compact('galleries'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category' => 'required|string',
            'image' => 'required|image',
        ]);

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

        Gallery::create([
            'title' => $request->title,
            'category' => $request->category,
            'image' => $imagePath,
            'description' => $request->description,
            'featured' => $request->has('featured'),
        ]);

        return redirect()->route('admin.gallery')->with('success', 'Photo album entry added successfully!');
    }

    public function delete($id)
    {
        $gallery = Gallery::findOrFail($id);
        $gallery->delete();
        return back()->with('success', 'Gallery item deleted.');
    }
}
