<?php

namespace App\Livewire\Forms;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;

use Livewire\Component;
use WireUi\Traits\WireUiActions;

use App\Enums\SongLanguageType;
use App\Enums\SongSituation;
use App\Models\Song;
use App\Models\SongCategory;
use App\Models\SongLibraryCache;

class SongForm extends Component
{
    use WireUiActions;

    protected $listeners = ['openModal','closeModal', 'deleteSong'];

    public bool $canCreate;
    public bool $canEdit;
    public bool $canDelect;
    
    public bool $showModal = false;

    public $songCategories =[];
    public $songLanguageType =[];
    public $songSituation =[];
    public $selectedCategories=[];
    public $selectedArtists=[];

    public ?int $songId = null;

    public array $fields = [
        'id' =>'',
        'name' => '',
        'adddate' => '',
        'filename' => '',
        'language_type' => '',
        
        'db_change' => '',
        'vocal' => '',
        'situation' => '',
        'copyright01' => '',
        'copyright02' => '',
        'note01' => '',
        'note02' => '',
        'note03' => '',
        'note04' => '',
        'enable' => true,
    ];
   

    //protected $rules = [
    //    'name' => 'required|string|max:255',
    //    
    //];

    public function mount()
    {
        $this->songCategories = SongCategory::all();
        $this->songLanguageType = collect(SongLanguageType::cases())->map(fn ($languageType) => [
            'name' => $languageType->labels(),
            'value' => $languageType->value,
        ])->toArray();
        $this->songSituation = collect(SongSituation::cases())->map(fn ($situation) => [
            'name' => $situation->labels(),
            'value' => $situation->value,
        ])->toArray();
        $this->canCreate = Auth::user()?->can('song-edit') ?? false;
        $this->canEdit = Auth::user()?->can('song-edit') ?? false;
        $this->canDownload=Auth::user()?->can('song-delete') ?? false;
        $this->canDelect = Auth::user()?->can('song-delete') ?? false;
    }

    public function openModal($id = null)
    {
        $this->resetFields();
        if ($id) {
            $song = Song::findOrFail($id);
            $this->songId = $song->id;
            $this->fields = $song->only(array_keys($this->fields));
            $this->selectedCategories = $song->categories()->pluck('id')->toArray();
            $this->selectedArtists = $song->artists()->pluck('id')->toArray();
            //dd($this->fields,$this->selectedCategories,$this->selectedArtists);
        }
        
        $this->showModal = true;
    }
    public function closeModal()
    {
        $this->resetFields();
        $this->showModal = false;
    }

    public function save()
    {
        //$this->validate();

        if ($this->songId) {
            if ($this->canEdit) {
                $song = Song::findOrFail($this->songId);
                $song->update($this->fields);
                // ⭐ 同步多對多關聯
                $song->artists()->sync($this->selectedArtists ?? []);
                $song->categories()->sync($this->selectedCategories ?? []);
                SongLibraryCache::syncFromSong($song);
                $this->notification()->send([
                    'icon' => 'success',
                    'title' => '成功',
                    'description' => '歌曲已更新',
                ]);
                
            }
        } else {
            if ($this->canCreate) {
                $song = Song::create($this->fields);
                // ⭐ 同步多對多關聯
                $song->artists()->sync($this->selectedArtists ?? []);
                $song->categories()->sync($this->selectedCategories ?? []);
                SongLibraryCache::syncFromSong($song);
                $this->notification()->send([
                    'icon' => 'success',
                    'title' => '成功',
                    'description' => '歌曲已新增',
                ]);
            }
        }

        $this->resetFields();
        $this->showModal = false;
        $this->dispatch('pg:eventRefresh-song-table');
    }
    
    public function deleteSong($id)
    {
        if ($this->canDelect) {
            Song::findOrFail($id)->delete();
            $this->notification()->send([
                'icon' => 'success',
                'title' => '成功',
                'description' => '歌曲已刪除',
            ]);
        }
    }

    public function resetFields()
    {
        foreach ($this->fields as $key => $value) {
            $this->fields[$key] = is_bool($value) ? false : '';
        }
        $this->songId = null;
    }
    public function render()
    {
        return view('livewire.forms.song-form');
    }
}
