<?php

namespace App\Livewire\Admin;

use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ArtistDataImport;

class ArtistImportData extends Component
{
    use WithFileUploads;

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

    public bool $canCreate;

    public bool $showModal = false;

    public $file;

    public function mount()
    {
        $this->canCreate = Auth::user()?->can('song-edit') ?? false;
    }

    public function openModal()
    {
        $this->showModal = true;
    }
    public function closeModal()
    {
        $this->showModal = false;
    }

    public function import()
    {
        // 檢查檔案是否有上傳
        $this->validate([
            'file' => 'required|file|mimes:csv,xlsx,xls'
        ]);
        if ($this->canCreate) {
            $import = new ArtistDataImport();
            Excel::import($import, $this->file);
            $success = $import->successCount;
            $fail = $import->failCount;
            $this->reset('file');
            $this->showModal =false;
            session()->flash('message', '匯入完成：成功 $success 筆，失敗 $fail 筆。');
        }
    }

    public function render()
    {
        return view('livewire.admin.artist-import-data');
    }

}