<?php

namespace App\Livewire\Website;

use App\Domain\Website\Enums\MediaCollection;
use App\Domain\Website\Models\Media;
use App\Domain\Website\Services\MediaService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use App\Domain\Shared\Traits\ChecksTemporaryUploads;
use Livewire\WithFileUploads;

#[Layout('layouts.app')]
#[Title('معرض الصور')]
class GalleryManager extends Component
{
    use WithFileUploads;
    use ChecksTemporaryUploads;

    public $photos = [];
    public array $gallery = [];

    public function mount(): void
    {
        $this->authorize('settings.manage');
        $this->loadGallery();
    }

    public function loadGallery(): void
    {
        $academy = app('current_academy');
        $this->gallery = Media::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->where('collection', 'gallery')
            ->orderBy('sort_order')
            ->get()
            ->map(fn ($m) => [
                'id' => $m->id,
                'url' => $m->url,
                'filename' => $m->original_filename,
                'size' => $m->file_size_human,
            ])
            ->toArray();
    }

    public function updatedPhotos(): void
    {
        if (! $this->temporaryUploadIsUsable('photos', $this->photos)) {
            return;
        }

        $this->validate([
            'photos.*' => 'image|max:1536|mimes:jpg,jpeg,png,webp',
        ]);

        $mediaService = app(MediaService::class);

        foreach ($this->photos as $photo) {
            $mediaService->upload($photo, MediaCollection::Gallery);
        }

        $this->photos = [];
        $this->loadGallery();
        session()->flash('success', __('تم رفع الصور بنجاح'));
    }

    public function deleteImage(int $id): void
    {
        $media = Media::find($id);
        if ($media) {
            app(MediaService::class)->delete($media);
            $this->loadGallery();
            session()->flash('success', __('تم حذف الصورة'));
        }
    }

    public function reorder(array $orderedIds): void
    {
        app(MediaService::class)->updateSortOrder($orderedIds);
        $this->loadGallery();
    }

    public function render()
    {
        return view('livewire.website.gallery-manager');
    }
}
