<?php

namespace App\Http\Controllers\Admin;

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

class GalleryController extends Controller
{
    public function index()
    {
        $galleries = Gallery::with(['user', 'images'])->orderBy('created_at', 'desc')->paginate(20);
        return view('admin.galleries.index', compact('galleries'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'images' => 'required|array|min:1',
            'images.*' => 'image|max:2048',
        ]);

        $gallery = new Gallery();
        $gallery->user_id = auth()->id();
        $gallery->title = $validated['title'];
        $gallery->description = $validated['description'] ?? null;
        $gallery->status = $request->status ?? 'draft';

        if ($request->hasFile('cover_image')) {
            $gallery->cover_image = $request->file('cover_image')->store('galleries', 'public');
        }

        if ($request->status === 'published') {
            $gallery->published_at = now();
        }

        $gallery->save();

        // Salvar imagens
        foreach ($request->file('images') as $index => $image) {
            $path = $image->store('galleries', 'public');
            GalleryImage::create([
                'gallery_id' => $gallery->id,
                'image_path' => $path,
                'order' => $index,
            ]);
        }

        // Definir primeira imagem como capa se não tiver
        if (!$gallery->cover_image && $gallery->images->count() > 0) {
            $gallery->cover_image = $gallery->images->first()->image_path;
            $gallery->save();
        }

        return redirect()->route('admin.galleries.index')
            ->with('success', 'Galeria criada com sucesso!');
    }

    public function edit(Gallery $gallery)
    {
        $gallery->load('images');
        return view('admin.galleries.edit', compact('gallery'));
    }

    public function update(Request $request, Gallery $gallery)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|in:draft,published,archived',
        ]);

        $gallery->update($validated);

        if ($request->status === 'published' && !$gallery->published_at) {
            $gallery->published_at = now();
            $gallery->save();
        }

        return redirect()->route('admin.galleries.index')
            ->with('success', 'Galeria atualizada com sucesso!');
    }

    public function destroy(Gallery $gallery)
    {
        // Deletar imagens
        foreach ($gallery->images as $image) {
            Storage::disk('public')->delete($image->image_path);
        }

        $gallery->delete();
        return redirect()->route('admin.galleries.index')
            ->with('success', 'Galeria excluída com sucesso!');
    }
}

