<?php

namespace App\Models;

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

class Star extends Model
{

    use HasFactory;

    protected $fillable = [
        'star_type',
        'star_name',
        'slug',
        'star_desc',
        'star_image',
        'country_id',
        'star_dob',
        'ranking',
        'gender',
        'industries',
        'view',
        'status',
        'facebook',
        'twitter',
        'instagram'
    ];
    protected $casts = [
        'industries' => 'array',
    ];

    protected $appends = [
        'country_name',
        'total_movies',
        'total_tv_shows',
        'industry_names'
    ];

    public function getCountryNameAttribute()
    {
        return $this->country ? $this->country->name : null;
    }

    public function country()
    {
        return $this->belongsTo(Country::class, 'country_id');
    }

    public function getTotalMoviesAttribute()
    {
    return Movie::whereJsonContains('stars', $this->id)->count();
    }

    public function getTotalTvShowsAttribute()
    {
        return TvShow::whereJsonContains('stars', $this->id)->count();
    }
    public function getIndustryNamesAttribute()
    {
        if (!$this->industries) {
            return [];
        }

        $ids = is_array($this->industries) ? $this->industries : json_decode($this->industries, true);

        return MovieIndustry::whereIn('id', $ids)->pluck('name');
    }
}

