<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Helpers\ChineseNameConverter;
use App\Helpers\ChineseStrokesConverter;
use App\Traits\LogsModelActivity;

class Song extends Model
{
    /** @use HasFactory<\Database\Factories\SongFactory> */
    use HasFactory, LogsModelActivity;

    protected $fillable = [
        'id',
        'name',
        'adddate',
        'filename',
        'language_type',
        'db_change',
        'vocal',
        'situation',
        'copyright01',
        'copyright02',
        'note01',
        'note02',
        'note03',
        'note04',
        'enable',
        'simplified',
        'phonetic_abbr',
        'pinyin_abbr',
        'strokes_abbr',
        'song_number',
        'song_counts',
    ];

    protected function casts(): array
    {
        return [
            'vocal' => 'boolean',
            'enable' => 'boolean',
            'language_type' => \App\Enums\SongLanguageType::class,
            'situation' => \App\Enums\SongSituation::class,
        ];
    }
    
    public function users(){
        return $this->belongsToMany(User::class, 'user_song')->withTimestamps();
    }

    public function str_artists(){
        return $this->artists->pluck('name')->implode(', ');
    }
    public function str_artists_plus(): string
    {
        return $this->artists->pluck('name')->implode(' + ');
    }
    public function artists(){
        return $this->belongsToMany(Artist::class);
    }
    public function str_categories(){
        return $this->categories->pluck('name')->implode(', ');
    }
    public function categories(){
        return $this->belongsToMany(SongCategory::class);
    }
    public function branches(){
        return $this->belongsToMany(Branch::class)
                    ->withPivot('counts')
                    ->withTimestamps();
    }
    protected static function booted()
    {
        // 無論是 creating 或 updating，都執行這段共用的邏輯
        static::saving(function (Song $song) {
            $simplified=ChineseNameConverter::convertToSimplified($song->name);// 繁體轉簡體
            $song->simplified =  $simplified;
            $song->phonetic_abbr = ChineseNameConverter::getKTVZhuyinAbbr($simplified);// 注音符號
            $song->pinyin_abbr=ChineseNameConverter::getKTVPinyinAbbr($simplified);// 拼音首字母

            $chars = preg_split('//u', $song->name, -1, PREG_SPLIT_NO_EMPTY);
            $firstChar = $chars[0] ?? null;
            
            $song->strokes_abbr=($firstChar && preg_match('/\p{Han}/u', $firstChar)) ? ChineseStrokesConverter::getStrokes($firstChar) : 0;
            $song->song_number = mb_strlen($song->name, 'UTF-8');
        });
        static::deleting(function (Song $song) {
            // Detach 關聯資料
            $song->artists()->detach();
            $song->categories()->detach();
            $song->branches()->detach();
            $song->users()->detach();
        });
    }
}
