<?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;

/**
 * GalleryImage Model
 *
 * Represents a single image within a gallery.
 * Stores metadata: title, description, file path, dimensions.
 * Tracks who uploaded the image and when.
 *
 * @property int $id
 * @property int $gallery_id
 * @property string $title
 * @property string|null $description
 * @property string $image_path
 * @property string $image_name
 * @property int $file_size
 * @property string $mime_type
 * @property int|null $width
 * @property int|null $height
 * @property int $sort_order
 * @property int|null $uploaded_by
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property \Illuminate\Support\Carbon|null $deleted_at
 */
class GalleryImage extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'gallery_images';

    // =========================================================================
    // ATTRIBUTES & CASTING
    // =========================================================================

    protected $fillable = [
        'gallery_id',
        'title',
        'description',
        'image_path',
        'image_name',
        'file_size',
        'mime_type',
        'width',
        'height',
        'sort_order',
        'uploaded_by',
    ];

    protected $casts = [
        'file_size'  => 'integer',
        'width'      => 'integer',
        'height'     => 'integer',
        'sort_order' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

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

    // =========================================================================
    // RELATIONSHIPS
    // =========================================================================

    /**
     * Get the gallery this image belongs to.
     */
    public function gallery(): BelongsTo
    {
        return $this->belongsTo(Gallery::class, 'gallery_id');
    }

    /**
     * Get the user who uploaded this image.
     */
    public function uploader(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uploaded_by');
    }

    // =========================================================================
    // QUERY SCOPES
    // =========================================================================

    /**
     * Scope to order by sort order.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc')
                     ->orderBy('created_at', 'desc');
    }

    /**
     * Scope to search by title or description.
     */
    public function scopeSearch($query, string $search)
    {
        return $query->where('title', 'like', "%{$search}%")
                     ->orWhere('description', 'like', "%{$search}%");
    }

    // =========================================================================
    // HELPER METHODS & ACCESSORS
    // =========================================================================

    /**
     * Get the formatted file size.
     */
    public function getFormattedFileSize(): string
    {
        $bytes = $this->file_size;
        if ($bytes >= 1073741824) {
            return number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) {
            return number_format($bytes / 1048576, 2) . ' MB';
        } elseif ($bytes >= 1024) {
            return number_format($bytes / 1024, 2) . ' KB';
        }
        return $bytes . ' B';
    }

    /**
     * Get the full URL to display the image.
     */
    public function getImageUrl(): string
    {
        return asset('storage/' . $this->image_path);
    }

    /**
     * Check if image is a photo (vs other media).
     */
    public function isImage(): bool
    {
        return str_starts_with($this->mime_type, 'image/');
    }

    /**
     * Get image dimensions as a string (e.g., "1920x1080").
     */
    public function getDimensionsString(): ?string
    {
        if ($this->width && $this->height) {
            return "{$this->width}x{$this->height}";
        }
        return null;
    }

    /**
     * Calculate aspect ratio (width/height).
     */
    public function getAspectRatio(): ?float
    {
        if ($this->width && $this->height && $this->height != 0) {
            return $this->width / $this->height;
        }
        return null;
    }
}
