<?php

namespace App\Models\SelfPaced;

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

/**
 * CourseCategory Model
 *
 * Organises self-paced courses into named categories with icons and display ordering.
 *
 * @property int $id
 * @property string $name
 * @property string $slug
 * @property string|null $description
 * @property string|null $icon
 * @property string|null $color
 * @property int $sort_order
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class CourseCategory extends Model
{
    protected $table = 'self_paced_categories';

    protected $fillable = [
        'name',
        'slug',
        'description',
        'icon',
        'color',
        'sort_order',
    ];

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

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

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

    public function courses(): HasMany
    {
        return $this->hasMany(Course::class, 'category_id');
    }

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

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

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

    public function getPublishedCoursesCount(): int
    {
        return $this->courses()->where('status', 'published')->count();
    }
}
