<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Gallery;
use Illuminate\Support\Facades\Validator;

class GalleryController extends Controller
{
    public function index()
    {
        $gallery = Gallery::paginate(10);
        return view('layouts.gallery.index', compact('gallery'));
    }


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

    // Store a new Gallery
    public function store(Request $request)
    {
        // Validate the input data
        $validator = Validator::make($request->all(), [
            'name' => 'nullable|string|max:255',
            'image' => $request->id ? 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048' : 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
            ], 422);
        }

        // Handle the image upload
        $imagePath = $request->id ? Gallery::find($request->id)->image : null;

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();

            try {
                $image->move(public_path('images'), $imageName);
                $imagePath = 'images/' . $imageName;
            } catch (\Exception $e) {
                return response()->json(['error' => 'Failed to upload image.'], 500);
            }
        }

        // Save the event data (including the image path)
        Gallery::updateOrCreate(
            ['id' => $request->id],
            [
                'name' => $request->name,
                'image' => $imagePath,
            ]
        );

        return response()->json([
            'success' => true,
            'redirect_url' => route('gallery.index'),
        ]);
    }
    // Update an existing Gallery
    public function edit($id)
    {
        $gallery = Gallery::findOrFail($id);

        return view('layouts.gallery.edit', compact('gallery')); // Return form view
    }

    // Update an existing Gallery

    // Delete a Gallery
    public function destroy($id)
    {
        $gallery = Gallery::findOrFail($id);
        $gallery->delete();
        $gallery = Gallery::paginate(10);

        return view('layouts.gallery.index', compact('gallery'));
    }

    public function gallery(Request $request)
    {
        // Fetch all galleries
        $gallery = Gallery::all();

        // Check if the collection is empty
        if ($gallery->isEmpty()) {
            return response()->json([
                'status' => 404,
                'message' => 'No gallery image found!'
            ]);
        }

        // Return gallery data if found
        return response()->json([
            'status' => 200,
            'message' => $gallery
        ]);
    }
}
