<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\TypeItems;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage; // Gunakan Storage facade
use Illuminate\Support\Str;

class TypeItemTable extends Component
{
    use WithPagination;
    use WithFileUploads;

    public $search = '';
    public $sortBy = 'name';
    public $sortDirection = 'asc';

    public $typeItemId;
    public $name;
    public $description;
    public $image_url;
    public $new_image;

    public $isModalOpen = false;
    public $isDeleteModalOpen = false; // Perbaikan typo, dari isDeleteModalOpen
    public $typeItemToDeleteId;

    protected $rules = [
        'name' => 'required|string|max:255|unique:type_items,name',
        'description' => 'nullable|string',
        'new_image' => 'nullable|image|max:1024|mimes:jpeg,png,jpg,gif',
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function create()
    {
        $this->resetInputFields();
        $this->isModalOpen = true;
    }

    public function edit($id)
    {
        $typeItem = TypeItems::findOrFail($id);
        $this->typeItemId = $typeItem->id;
        $this->name = $typeItem->name;
        $this->description = $typeItem->description;
        $this->image_url = $typeItem->image_url;
        $this->isModalOpen = true;
    }

    public function store()
    {
        $rules = $this->rules;
        if ($this->typeItemId) {
            $rules['name'] = 'required|string|max:255|unique:type_items,name,' . $this->typeItemId;
        }

        if (!$this->new_image && !$this->image_url) {
            unset($rules['new_image']);
        }

        $this->validate($rules);

        $typeItemData = [
            'name' => $this->name,
            'description' => $this->description,
        ];

        // Penanganan upload gambar menggunakan disk 'public_path_disk'
        if ($this->new_image) {
            // Hapus gambar lama jika ada saat update
            if ($this->typeItemId && $this->image_url) {
                // $this->image_url sudah menyimpan path relatif dari folder public (e.g., 'img/menu/nama_file.jpg')
                Storage::disk('public_path_disk')->delete($this->image_url);
            }

            // Tentukan direktori tujuan di dalam public_path_disk (misal: 'img/menu/')
            $uploadDirectory = 'img/menu'; // Relatif terhadap root 'public_path_disk' (yaitu public/)

            // Buat direktori jika belum ada di dalam disk
            if (!Storage::disk('public_path_disk')->exists($uploadDirectory)) {
                Storage::disk('public_path_disk')->makeDirectory($uploadDirectory);
            }

            // Simpan gambar baru ke disk 'public_path_disk' dengan nama unik
            $fileName = Str::random(20) . '.' . $this->new_image->extension();
            $imagePath = $this->new_image->storeAs($uploadDirectory, $fileName, 'public_path_disk');

            $typeItemData['image_url'] = $imagePath; // Simpan path relatif penuh (e.g., 'img/menu/nama_file.jpg')
        } elseif ($this->typeItemId && $this->image_url !== null && !$this->new_image) {
            // Jika pengguna menghapus gambar yang sudah ada (saat update)
            // Hapus file fisik lama
            Storage::disk('public_path_disk')->delete($this->image_url);
            $typeItemData['image_url'] = null;
        } elseif (!$this->typeItemId && !$this->new_image) {
            // Jika membuat baru dan tidak ada gambar diupload
            $typeItemData['image_url'] = null;
        }

        if ($this->typeItemId) {
            TypeItems::find($this->typeItemId)->update($typeItemData);
            session()->flash('message', 'Tipe item berhasil diperbarui!');
        } else {
            TypeItems::create($typeItemData);
            session()->flash('message', 'Tipe item berhasil ditambahkan!');
        }

        $this->closeModal();
        $this->resetInputFields();
    }

    public function confirmDelete($id)
    {
        $this->typeItemToDeleteId = $id;
        $this->isDeleteModalOpen = true; // Perbaikan typo
    }

    public function delete()
    {
        if ($this->typeItemToDeleteId) {
            $typeItem = TypeItems::find($this->typeItemToDeleteId);

            if ($typeItem) {
                if ($typeItem->items()->count() > 0) {
                    session()->flash('error', 'Tidak dapat menghapus tipe item ini karena masih ada item yang terkait dengannya.');
                    $this->closeDeleteModal();
                    return;
                }

                // Hapus file gambar menggunakan disk 'public_path_disk'
                if ($typeItem->image_url) {
                    Storage::disk('public_path_disk')->delete($typeItem->image_url);
                }

                TypeItems::destroy($this->typeItemToDeleteId);
                session()->flash('message', 'Tipe item berhasil dihapus!');
            } else {
                session()->flash('error', 'Tipe item tidak ditemukan.');
            }
        }
        $this->closeDeleteModal();
    }

    public function closeModal()
    {
        $this->isModalOpen = false;
        $this->resetValidation();
    }

    public function closeDeleteModal()
    {
        $this->isDeleteModalOpen = false; // Perbaikan typo
        $this->typeItemToDeleteId = null;
    }

    private function resetInputFields()
    {
        $this->typeItemId = null;
        $this->name = '';
        $this->description = '';
        $this->image_url = null;
        $this->new_image = null;
    }

    public function render()
    {
        $typeItems = TypeItems::query()
            ->when($this->search, function ($query) {
                $query->where('name', 'like', '%' . $this->search . '%')
                    ->orWhere('description', 'like', '%' . $this->search . '%');
            })
            ->orderBy($this->sortBy, $this->sortDirection)
            ->paginate(10);

        return view('livewire.type-item-table', [
            'typeItems' => $typeItems,
        ]);
    }
}
