<?php
// app/Models/Course.php

namespace App\Models;

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

class Course extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'slug',
        'description',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'category_id',
        'teacher_id',
        'level',
        'duration_value',
        'duration_type',
        'price_type',
        'price',
        'label',
        'has_certificate',
        'image',
        'ratings',
        'total_students',
        'requirements',
        'what_you_learn',
        'is_active',
        'is_featured'
    ];

    protected $casts = [
        'has_certificate' => 'boolean',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'ratings' => 'decimal:2',
        'price' => 'decimal:2',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($course) {
            if (empty($course->slug)) {
                $course->slug = Str::slug($course->title);
            }
        });

        static::updating(function ($course) {
            if ($course->isDirty('title') && empty($course->slug)) {
                $course->slug = Str::slug($course->title);
            }
        });
    }

public function category()
{
    return $this->belongsTo(CourseCategory::class, 'category_id');
}

    public function teacher()
    {
        return $this->belongsTo(Teacher::class);
    }

    public function getDurationAttribute()
    {
        return $this->duration_value . ' ' . $this->duration_type;
    }

    public function getFormattedPriceAttribute()
    {
        if ($this->price_type === 'free') {
            return 'Free';
        }
        return '$' . number_format($this->price, 2);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}