<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * Class PostMedia
 * 
 * Represents a single media item (image, video, etc.) associated with a post.
 *
 * @property int $id
 * @property int $post_id
 * @property int $user_id
 * @property string $image_or_video
 * @property string $media_path
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 */
class PostMedia extends Model
{
    use HasFactory;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'posts_media';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'post_id',
        'user_id',
        'image_or_video',
        'media_path',
        'mime_type',
        'original_name',
        'file_size',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'updated_at',
    ];

    /**
     * Get the post that owns this media.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    /**
     * Get the user who uploaded this media.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope a query to only include images.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeImages($query)
    {
        return $query->where('image_or_video', 1);
    }

    /**
     * Scope a query to only include videos.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeVideos($query)
    {
        return $query->where('image_or_video', 2);
    }

    /**
     * Check if the media is an image.
     *
     * @return bool
     */
    public function isImage()
    {
        return $this->image_or_video == 1;
    }

    /**
     * Check if the media is a video.
     *
     * @return bool
     */
    public function isVideo()
    {
        return $this->image_or_video == 2;
    }

    public function isAudio()
    {
        return $this->image_or_video == 3;
    }

    /**
     * Get the media URL.
     *
     * @return string
     */
    public function getUrl()
    {
        // Adjust this to fit your storage system
        return asset("uploads/{$this->media_path}");
    }
}
