<?php

namespace App\Http\Controllers;

use App\Models\ImageGallery;
use App\Models\GalleryCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ImageGalleryController extends Controller
{

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        if (Auth::check() && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $images = ImageGallery::with('category')->get();
        $categories = GalleryCategory::all();
        return view('admin.image_gallery_admin', compact('images', 'categories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        if (Auth::check() && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $categories = GalleryCategory::all();
        return view('admin.image_gallery_create', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        if (Auth::check() && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:gallery_categories,id',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        // Handle image upload
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('gallery_images', 'public');
        }

        ImageGallery::create([
            'title' => $request->title,
            'category_id' => $request->category_id,
            'image_path' => $imagePath,
        ]);

        return redirect()->route('image-gallery.index')
            ->with('success', 'Image added to gallery successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ImageGallery $imageGallery)
    {
        if (Auth::check() && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $categories = GalleryCategory::all();
        return view('admin.image_gallery_edit', compact('imageGallery', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, ImageGallery $imageGallery)
    {
        if (Auth::check() && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:gallery_categories,id',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        $data = [
            'title' => $request->title,
            'category_id' => $request->category_id,
        ];

        // Handle image update
        if ($request->hasFile('image')) {
            // Delete old image
            if ($imageGallery->image_path) {
                Storage::disk('public')->delete($imageGallery->image_path);
            }

            $data['image_path'] = $request->file('image')->store('gallery_images', 'public');
        }

        $imageGallery->update($data);

        return redirect()->route('image-gallery.index')
            ->with('success', 'Image updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        if (Auth::check() && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $imageGallery = ImageGallery::findOrFail($id);

        // Delete image file from storage
        if ($imageGallery->image_path) {
            Storage::disk('public')->delete($imageGallery->image_path);
        }

        $imageGallery->delete();

        return redirect()->route('image-gallery.index')
            ->with('success', 'Image deleted successfully.');
    }

    public function showGallery()
    {
        // Fetch all categories
        $categories = GalleryCategory::all();

        // Fetch all images with their associated categories
        $images = ImageGallery::with('category')->get();

        return view('front.image_gallery', compact('images', 'categories'));
    }
}
