<?php

namespace App\Models\Courses;

use App\Models\User;
use Illuminate\Support\Str;
use App\Models\Courses\CourseLesson;
use Illuminate\Database\Eloquent\Model;



class Course extends Model
{
    protected $fillable = [
        'user_id', 'category_id', 'title', 'slug', 'description', 'requirements',
        'what_you_will_learn', 'target_audience', 'price', 'discount_price',
        'discount_ends_at', 'level', 'language', 'thumbnail', 'preview_video',
        'is_featured', 'is_published', 'average_rating', 'total_reviews',
        'total_students', 'total_lessons', 'total_duration'
    ];

    protected $casts = [
        'discount_ends_at' => 'datetime',
        'is_featured' => 'boolean',
        'is_published' => 'boolean',
    ];

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

    public function instructor()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

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

    public function sections()
    {
        return $this->hasMany(CourseSection::class)->orderBy('sort_order');
    }

    public function enrollments()
    {
        return $this->hasMany(CourseEnrollment::class);
    }

    public function reviews()
    {
        return $this->hasManyThrough(
            CourseReview::class,
            CourseEnrollment::class,
            'course_id',
            'enrollment_id'
        );
    }

    public function announcements()
    {
        return $this->hasMany(CourseAnnouncement::class);
    }

    public function questions()
    {
        return $this->hasMany(CourseQuestion::class);
    }

    public function wishlist()
    {
        return $this->hasMany(WishlistCourse::class);
    }

    public function coupons()
    {
        return $this->hasMany(CourseCoupon::class);
    }

    public function getLessons()
    {
        return CourseLesson::whereIn('section_id', $this->sections->pluck('id'))->orderBy('sort_order');
    }

    public function getCurrentPrice()
    {
        if ($this->discount_price && $this->discount_ends_at && $this->discount_ends_at > now()) {
            return $this->discount_price;
        }
        
        return $this->price;
    }

    public function isEnrolled($userId)
    {
        return $this->enrollments()->where('user_id', $userId)->exists();
    }

    public function isPurchased($userId)
    {
        return $this->enrollments()->where('user_id', $userId)->whereNotNull('transaction_id')->exists();
    }

    public function isFree()
    {
        return $this->price == 0;
    }

    public function hasDiscount()
    {
        return $this->discount_price && $this->discount_ends_at && $this->discount_ends_at > now();
    }

    public function getDiscountPercentage()
    {
        if ($this->hasDiscount() && $this->price > 0) {
            return round((($this->price - $this->discount_price) / $this->price) * 100);
        }
        
        return 0;
    }

    public function updateCourseStats()
    {
        // Update total lessons and duration
        $this->total_lessons = $this->getLessons()->count();
        $this->total_duration = $this->getLessons()->sum('duration');
        
        // Update total students
        $this->total_students = $this->enrollments()->count();
        
        // Update average rating and total reviews
        $reviews = $this->reviews()->where('is_approved', true);
        $this->total_reviews = $reviews->count();
        
        if ($this->total_reviews > 0) {
            $this->average_rating = $reviews->avg('rating');
        }
        
        $this->save();
    }
}