<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Gallery extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'galleries';

    protected $fillable = [
        'organization_id',
        'gallery_type_id',
        'title',
        'description',
        'image_count',
        'is_published',
        'sort_order',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'image_count'   => 'integer',
        'is_published'  => 'boolean',
        'sort_order'    => 'integer',
        'created_at'    => 'datetime',
        'updated_at'    => 'datetime',
        'deleted_at'    => 'datetime',
    ];

    protected $attributes = [
        'image_count'  => 0,
        'is_published' => true,
        'sort_order'   => 0,
    ];

    public function organization(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function type(): BelongsTo
    {
        return $this->belongsTo(GalleryType::class, 'gallery_type_id');
    }

    public function images(): HasMany
    {
        return $this->hasMany(GalleryImage::class, 'gallery_id');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeSearch($query, string $search)
    {
        return $query->where('title', 'like', "%{$search}%")
                     ->orWhere('description', 'like', "%{$search}%");
    }

    public function scopeOfOrganization($query, int $organizationId)
    {
        return $query->where('organization_id', $organizationId);
    }

    public function scopeOfType($query, int $typeId)
    {
        return $query->where('gallery_type_id', $typeId);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc')
                     ->orderBy('created_at', 'desc');
    }

    protected static function booted(): void
    {
        static::deleting(function (Gallery $gallery) {
            foreach ($gallery->images as $image) {
                $image->delete();
            }
        });
    }

    public function addImage(array $data): GalleryImage
    {
        return $this->images()->create($data);
    }

    public function incrementImageCount(): void
    {
        $this->increment('image_count');
    }

    public function decrementImageCount(): void
    {
        if ($this->image_count > 0) {
            $this->decrement('image_count');
        }
    }

    public function syncImageCount(): void
    {
        $this->update(['image_count' => $this->images()->count()]);
    }

    public function hasImages(): bool
    {
        return $this->image_count > 0;
    }
}
