<?php

namespace App\Models\SelfPaced;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * CourseMedia Model
 *
 * Video, image, PDF, and presentation files attached to a CourseSubTopic
 * for inline display in the Learner Portal.
 *
 * @property int $id
 * @property int $subtopic_id
 * @property string|null $title
 * @property string $type
 * @property string $file_path
 * @property string $file_name
 * @property int $file_size
 * @property string|null $mime_type
 * @property int $sort_order
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class CourseMedia extends Model
{
    protected $table = 'self_paced_media';

    protected $fillable = [
        'subtopic_id',
        'title',
        'type',
        'file_path',
        'file_name',
        'file_size',
        'mime_type',
        'sort_order',
    ];

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

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

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

    public function subtopic(): BelongsTo
    {
        return $this->belongsTo(CourseSubTopic::class, 'subtopic_id');
    }

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

    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }

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

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    public function isVideo(): bool
    {
        return $this->type === 'video';
    }

    public function isImage(): bool
    {
        return $this->type === 'image';
    }

    public function isPdf(): bool
    {
        return $this->type === 'pdf';
    }

    public function getFormattedFileSize(): string
    {
        $bytes = $this->file_size;

        if ($bytes >= 1073741824) {
            return number_format($bytes / 1073741824, 2) . ' GB';
        }

        if ($bytes >= 1048576) {
            return number_format($bytes / 1048576, 2) . ' MB';
        }

        if ($bytes >= 1024) {
            return number_format($bytes / 1024, 2) . ' KB';
        }

        return $bytes . ' B';
    }

    /** Max allowed upload size in bytes (500 MB). */
    public static function maxFileSizeBytes(): int
    {
        return 500 * 1024 * 1024;
    }
}
