<?php

namespace App\Http\Controllers\Admin;

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

class GalleryController extends Controller
{
    public function index(Request $request)
    {
        $type = $request->get('type', 'all');
        $galleries = Gallery::when($type !== 'all', fn($q) => $q->where('type', $type))
            ->latest()
            ->paginate(20);
        return view('admin.gallery.index', compact('galleries', 'type'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'title'  => 'required|string|max:255',
            'type'   => 'required|in:photo,video',
            'photo'  => 'required_if:type,photo|image|max:5120',
            'media'  => 'required_if:type,video',
        ]);

        $media = $request->media;
        if ($request->type === 'photo' && $request->hasFile('photo')) {
            $media = $request->file('photo')->store('gallery', 'public');
        }

        Gallery::create([
            'title'       => $request->title,
            'type'        => $request->type,
            'media'       => $media,
            'description' => $request->description,
        ]);

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

    public function destroy(Gallery $gallery)
    {
        if ($gallery->type === 'photo' && $gallery->media) {
            Storage::disk('public')->delete($gallery->media);
        }
        $gallery->delete();
        return redirect()->route('admin.gallery.index')->with('success', 'Gallery item deleted.');
    }
}
