<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LandingGallery;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class LandingGalleryController extends Controller
{
    public function index()
    {
        $photos = LandingGallery::orderBy('sort_order')->orderBy('id', 'ASC')->get();
        return view('backEnd.landing.gallery.index', compact('photos'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'images'    => 'required',
            'images.*'  => 'image|mimes:jpg,jpeg,png,webp|max:2048',
            'caption'   => 'nullable|string|max:255',
            'sort_order'=> 'nullable|integer|min:0',
        ]);

        $uploadDir = public_path('uploads/gallery');
        if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

        foreach ($request->file('images') as $image) {
            $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
            $image->move($uploadDir, $imageName);

            LandingGallery::create([
                'image'      => 'public/uploads/gallery/' . $imageName,
                'caption'    => $request->caption,
                'sort_order' => $request->sort_order ?? 0,
                'status'     => 1,
            ]);
        }

        Cache::forget('landing_gallery');
        Toastr::success('Success', 'Photo(s) uploaded successfully');
        return redirect()->back();
    }

    public function toggleStatus(Request $request)
    {
        $photo = LandingGallery::findOrFail($request->id);
        $photo->status = !$photo->status;
        $photo->save();
        Cache::forget('landing_gallery');
        return response()->json(['status' => $photo->status]);
    }

    public function destroy(Request $request)
    {
        $photo = LandingGallery::findOrFail($request->hidden_id);

        $physicalPath = (str_starts_with($photo->image, 'public/'))
            ? substr($photo->image, 7)
            : $photo->image;

        $fullPath = public_path($physicalPath);
        if (file_exists($fullPath)) @unlink($fullPath);

        $photo->delete();

        Cache::forget('landing_gallery');
        Toastr::success('Success', 'Photo deleted successfully');
        return redirect()->back();
    }
}
