<?php

namespace App\Http\Controllers;

use App\Models\GalleryGroup;
use App\Models\GalleryItem;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class GalleryController extends Controller
{
    public function index(Request $request)
    {
        $groups = GalleryGroup::withCount('items')->get();
        
        $query = GalleryItem::latest();

        if ($request->has('group')) {
            $query->whereHas('group', function($q) use ($request) {
                $q->where('slug', $request->group);
            });
        }

        $items = $query->get();

        return view('pages.gallery', compact('items', 'groups'));
    }

    public function create()
    {
        $groups = GalleryGroup::all();
        return view('pages.gallery-upload', compact('groups'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'media' => 'required|array',
            'media.*' => 'file|mimes:jpg,jpeg,png,gif,webp,mp4,mov,webm|max:20480',
            'group_id' => 'nullable|exists:gallery_groups,id',
            'new_group' => 'nullable|string|max:255',
        ]);

        $groupId = $request->group_id;

        // Create new group if provided
        if ($request->filled('new_group')) {
            $group = GalleryGroup::firstOrCreate(
                ['name' => $request->new_group],
                ['slug' => Str::slug($request->new_group)]
            );
            $groupId = $group->id;
        }

        foreach ($request->file('media') as $media) {
            $path = $media->store('gallery', 'public');
            $type = str_starts_with($media->getMimeType(), 'image/') ? 'image' : 'video';

            GalleryItem::create([
                'title' => $request->title,
                'description' => $request->description,
                'file_path' => $path,
                'type' => $type,
                'gallery_group_id' => $groupId,
            ]);
        }

        return redirect()->route('gallery')->with('success', 'Media uploaded successfully.');
    }

    public function destroy(GalleryItem $item)
    {
        if ($item->file_path) {
            \Illuminate\Support\Facades\Storage::disk('public')->delete($item->file_path);
        }

        $item->delete();

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

    public function bulkDestroy(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:gallery_items,id',
        ]);

        $items = GalleryItem::whereIn('id', $request->ids)->get();

        foreach ($items as $item) {
            if ($item->file_path) {
                \Illuminate\Support\Facades\Storage::disk('public')->delete($item->file_path);
            }
            $item->delete();
        }

        return redirect()->route('gallery')->with('success', count($items) . ' items deleted successfully.');
    }
}
