<?php

namespace App\Services\Dashboard;

use App\Models\Gallery;
use App\Helper\Media;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GalleryService
{
    public function store($request, $data)
    {
        DB::beginTransaction();
        try {
            $gallery = Gallery::create($data);
            DB::commit();
            return $gallery;
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function update($request, $data, $gallery)
    {
        DB::beginTransaction();
        try {
            $gallery->update($data);
            DB::commit();
            return $gallery;
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function delete($selectedIds, $data = null)
    {
        // Handle if selectedIds is null or empty
        if (empty($selectedIds)) {
            return false;
        }

        // Ensure selectedIds is an array
        if (!is_array($selectedIds)) {
            $selectedIds = [$selectedIds];
        }

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

        if ($galleries->isEmpty()) {
            return false;
        }

        DB::beginTransaction();
        try {
            foreach ($galleries as $gallery) {
                // Delete associated images
                $images = \App\Models\GalleryImage::where('gallery_id', $gallery->id)->get();
                foreach ($images as $image) {
                    if ($image->image) {
                        Media::removeFile('galleries', $image->image);
                    }
                }
                \App\Models\GalleryImage::where('gallery_id', $gallery->id)->delete();

                // Delete the gallery
                $gallery->delete();
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error deleting gallery: ' . $e->getMessage());
            throw $e;
        }
    }
}

