<?php

namespace App\Models\SelfPaced;

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

/**
 * CourseSubTopic Model
 *
 * Sub-section within a CourseTopic containing rich HTML content
 * (text, images, embedded video).
 *
 * @property int $id
 * @property int $topic_id
 * @property string $title
 * @property string|null $content
 * @property int $sort_order
 * @property bool $is_published
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class CourseSubTopic extends Model
{
    protected $table = 'self_paced_subtopics';

    protected $fillable = [
        'topic_id',
        'title',
        'content',
        'sort_order',
        'is_published',
    ];

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

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

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

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

    public function media(): HasMany
    {
        return $this->hasMany(CourseMedia::class, 'subtopic_id')->orderBy('sort_order');
    }

    public function progressRecords(): HasMany
    {
        return $this->hasMany(LearningProgress::class, 'subtopic_id');
    }

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

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

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

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

    /**
     * Check if this subtopic has been read by a given enrollment.
     */
    public function isReadByEnrollment(int $enrollmentId): bool
    {
        return LearningProgress::where('enrollment_id', $enrollmentId)
            ->where('subtopic_id', $this->id)
            ->exists();
    }
}
