<?php

namespace App\Models\SelfPaced;

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

/**
 * CourseDownload Model
 *
 * Downloadable resources (PDF, Excel, Word, ZIP) attached to a Course or CourseTopic.
 *
 * @property int $id
 * @property int|null $course_id
 * @property int|null $topic_id
 * @property string $title
 * @property string $file_path
 * @property string $file_name
 * @property int $file_size
 * @property string|null $mime_type
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class CourseDownload extends Model
{
    protected $table = 'self_paced_downloads';

    protected $fillable = [
        'course_id',
        'topic_id',
        'title',
        'file_path',
        'file_name',
        'file_size',
        'mime_type',
    ];

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

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

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

    public function course(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id');
    }

    public function topic(): BelongsTo
    {
        return $this->belongsTo(CourseTopic::class, 'topic_id');
    }

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

    public function scopeForCourse($query, int $courseId)
    {
        return $query->where('course_id', $courseId)->whereNull('topic_id');
    }

    public function scopeForTopic($query, int $topicId)
    {
        return $query->where('topic_id', $topicId);
    }

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

    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';
    }
}
