<?php

namespace App\Http\Controllers\Admin;

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

class GalleryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Gallery::query();

        // Filtres
        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('title', 'like', '%' . $request->search . '%')
                  ->orWhere('description', 'like', '%' . $request->search . '%');
            });
        }

        $galleries = $query->orderBy('order')->orderBy('created_at', 'desc')->paginate(20);

        return view('admin.galleries.index', compact('galleries'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.galleries.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'image_path' => 'required|image|max:5120',
            'alt_text' => 'nullable|string|max:255',
            'category' => 'nullable|in:events,training,community,projects,partnerships,general',
            'order' => 'nullable|integer|min:0',
            'is_featured' => 'boolean',
        ]);

        // Gestion de l'image
        if ($request->hasFile('image_path')) {
            $validated['image_path'] = $request->file('image_path')->store('gallery', 'public');
        }

        // Ordre automatique si non spécifié
        if (!isset($validated['order'])) {
            $validated['order'] = Gallery::max('order') + 1 ?? 0;
        }

        // Valeurs par défaut
        $validated['type'] = 'image';
        $validated['is_published'] = true;
        $validated['is_featured'] = $request->has('is_featured') ? true : false;

        Gallery::create($validated);

        return redirect()->route('admin.galleries.index')
            ->with('success', 'Image de galerie créée avec succès.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Gallery $gallery)
    {
        return view('admin.galleries.show', compact('gallery'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Gallery $gallery)
    {
        return view('admin.galleries.edit', compact('gallery'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Gallery $gallery)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'image_path' => 'nullable|image|max:5120',
            'alt_text' => 'nullable|string|max:255',
            'category' => 'nullable|in:events,training,community,projects,partnerships,general',
            'order' => 'nullable|integer|min:0',
            'is_featured' => 'boolean',
        ]);

        // Gestion de l'image
        if ($request->hasFile('image_path')) {
            // Supprimer l'ancienne image
            if ($gallery->image_path) {
                \Storage::disk('public')->delete($gallery->image_path);
            }
            $validated['image_path'] = $request->file('image_path')->store('gallery', 'public');
        }

        $validated['is_featured'] = $request->has('is_featured') ? true : false;

        $gallery->update($validated);

        return redirect()->route('admin.galleries.index')
            ->with('success', 'Image de galerie mise à jour avec succès.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Gallery $gallery)
    {
        try {
            // Supprimer l'image de couverture
            if ($gallery->cover_image && \Storage::disk('public')->exists($gallery->cover_image)) {
                \Storage::disk('public')->delete($gallery->cover_image);
            }

            // Supprimer les images de la galerie
            if ($gallery->images && is_array(json_decode($gallery->images, true))) {
                foreach (json_decode($gallery->images, true) as $image) {
                    if (\Storage::disk('public')->exists($image)) {
                        \Storage::disk('public')->delete($image);
                    }
                }
            }

            // Supprimer la galerie
            $title = $gallery->title;
            $gallery->delete();

            return redirect()->route('admin.galleries.index')
                ->with('success', "La galerie '{$title}' a été supprimée avec succès.");

        } catch (\Exception $e) {
            \Log::error('Erreur lors de la suppression de la galerie: ' . $e->getMessage());
            
            return redirect()->route('admin.galleries.index')
                ->with('error', 'Une erreur est survenue lors de la suppression de la galerie.');
        }
    }

    /**
     * Upload multiple files
     */
    public function bulkUpload(Request $request)
    {
        $request->validate([
            'files' => 'required|array',
            'files.*' => 'image|max:5120',
        ]);

        $uploaded = 0;
        $maxOrder = Gallery::max('order') ?? 0;

        foreach ($request->file('files') as $file) {
            $imagePath = $file->store('gallery/images', 'public');
            
            Gallery::create([
                'title' => pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME),
                'type' => 'image',
                'image_path' => $imagePath,
                'order' => ++$maxOrder,
            ]);
            
            $uploaded++;
        }

        return response()->json([
            'success' => true,
            'message' => "$uploaded images téléchargées avec succès."
        ]);
    }

    /**
     * Reorder gallery items
     */
    public function reorder(Request $request)
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:galleries,id',
            'items.*.order' => 'required|integer|min:0',
        ]);

        foreach ($request->items as $item) {
            Gallery::where('id', $item['id'])->update(['order' => $item['order']]);
        }

        return response()->json(['success' => true]);
    }

    /**
     * Bulk actions
     */
    public function bulkAction(Request $request)
    {
        $request->validate([
            'action' => 'required|in:delete',
            'galleries' => 'required|array',
            'galleries.*' => 'exists:galleries,id'
        ]);

        $galleries = Gallery::whereIn('id', $request->galleries);

        switch ($request->action) {
            case 'delete':
                $galleries->each(function ($gallery) {
                    if ($gallery->image_path) {
                        \Storage::disk('public')->delete($gallery->image_path);
                    }
                    if ($gallery->thumbnail_path) {
                        \Storage::disk('public')->delete($gallery->thumbnail_path);
                    }
                });
                $galleries->delete();
                $message = 'Éléments de galerie supprimés avec succès.';
                break;
        }

        return redirect()->route('admin.galleries.index')
            ->with('success', $message);
    }
}