<?php
namespace App\Models\Movies;


use App\Models\Movies\genre;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Movie extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'title',
        'description',
        'genre_id',
        'release_year',
        'duration',
        'director',
        'cast',
        'poster_url',
        'video_url',
        'trailer_url',
        'featured',
        'content_rating',
        'is_active',
        'views_count',
        'slug'
    ];

    protected $casts = [
        'cast' => 'array',
        'featured' => 'boolean',
        'is_active' => 'boolean',
    ];

    // Relationships
    public function genre()
    {
        return $this->belongsTo(Genre::class);
    }

    public function ratings()
    {
        return $this->hasMany(MovieRating::class);
    }

    public function watchHistory()
    {
        return $this->hasMany(WatchHistory::class);
    }

    // Calculate average rating
    public function getAvgRatingAttribute()
    {
        return $this->ratings()->avg('rating') ?: 0;
    }

    // Scopes
    public function scopeFeatured($query)
    {
        return $query->where('featured', true);
    }

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

    public function scopePopular($query)
    {
        return $query->orderBy('views_count', 'desc');
    }

    public function scopeNewest($query)
    {
        return $query->orderBy('created_at', 'desc');
    }

    public function scopeTopRated($query)
    {
        return $query->withAvg('ratings', 'rating')
            ->orderBy('ratings_avg_rating', 'desc');
    }
}