<?php

namespace App\Livewire\Forms;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use WireUi\Traits\WireUiActions;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Jobs\ImportJob;


class BranchImportData extends Component
{
    use WithFileUploads, WireUiActions;

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

    public bool $canCreate;

    public bool $showModal = false;

    public $file;
    public string $maxUploadSize;

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

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

    public function closeModal()
    {
        $this->deleteTmpFile(); // 關閉 modal 時刪除暫存檔案
        $this->reset(['file']);
        $this->showModal = false;
    }

    public function import()
    {
        // 檢查檔案是否有上傳
        $this->validate([
            'file' => 'required|file|mimes:csv,xlsx,xls'
        ]);
        if ($this->canCreate) {
            // 儲存檔案至 storage
            $path = $this->file->storeAs('imports', uniqid() . '_' . $this->file->getClientOriginalName());

            // 丟到 queue 執行
            ImportJob::dispatch($path,'Branch');
            
            $this->notification()->send([
                'icon' => 'info',
                'title' => $this->file->getClientOriginalName(),
                'description' => '已排入背景匯入作業，請稍候查看結果',
            ]);
            $this->deleteTmpFile(); // 匯入後也順便刪除 tmp 檔
            $this->reset(['file']);
            $this->showModal = false;
        }
    }
    protected function deleteTmpFile()
    {
        if($this->file!=null){
            $Path = $this->file->getRealPath();
            if ($Path && File::exists($Path)) {
                File::delete($Path);
            }
        }
    }

    private function getMaxUploadSize(): string
    {
        $uploadMax = $this->convertPHPSizeToBytes(ini_get('upload_max_filesize'));
        $postMax = $this->convertPHPSizeToBytes(ini_get('post_max_size'));
        $max = min($uploadMax, $postMax);
        return $this->humanFileSize($max);
    }

    private function convertPHPSizeToBytes(string $s): int
    {
        $s = trim($s);
        $unit = strtolower($s[strlen($s) - 1]);
        $bytes = (int) $s;
        switch ($unit) {
            case 'g':
                $bytes *= 1024;
            case 'm':
                $bytes *= 1024;
            case 'k':
                $bytes *= 1024;
        }
        return $bytes;
    }

    private function humanFileSize(int $bytes, int $decimals = 2): string
    {
        $sizes = ['B', 'KB', 'MB', 'GB'];
        $factor = floor((strlen((string) $bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $sizes[$factor];
    }

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

}