<?php

namespace App\Livewire;

use App\Models\TypeItems;
use Livewire\Component;
use Livewire\WithPagination;

class TypeItemTable extends Component
{
    use WithPagination;

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

    // Properti untuk form Create/Edit TypeItem
    public $typeItemId;
    public $name;
    public $description;

    public $isModalOpen = false;
    public $isDeleteModalOpen = false;
    public $typeItemToDeleteId;

    // Aturan validasi
    protected $rules = [
        'name' => 'required|string|max:255|unique:type_items,name', // Name harus unik
        'description' => 'nullable|string',
    ];

    // Reset halaman pagination setiap kali properti pencarian berubah
    public function updatingSearch()
    {
        $this->resetPage();
    }

    // Metode untuk mengubah kolom sorting
    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDirection = 'asc';
        }
    }

    // Metode untuk membuka modal Create TypeItem
    public function create()
    {
        $this->resetInputFields();
        $this->isModalOpen = true;
    }

    // Metode untuk mengisi form edit dan membuka modal
    public function edit($id)
    {
        $typeItem = TypeItems::findOrFail($id);
        $this->typeItemId = $typeItem->id;
        $this->name = $typeItem->name;
        $this->description = $typeItem->description;
        $this->isModalOpen = true;
    }

    // Metode untuk menyimpan atau memperbarui TypeItem
    public function store()
    {
        $rules = $this->rules;
        if ($this->typeItemId) {
            // Untuk update, 'name' harus unique kecuali jika itu adalah nama dari type item yang sedang diedit
            $rules['name'] = 'required|string|max:255|unique:type_items,name,' . $this->typeItemId;
        }
        $this->validate($rules);

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

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

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

    // Metode untuk membuka modal konfirmasi hapus
    public function confirmDelete($id)
    {
        $this->typeItemToDeleteId = $id;
        $this->isDeleteModalOpen = true;
    }

    // Metode untuk menghapus TypeItem
    public function delete()
    {
        if ($this->typeItemToDeleteId) {
            // Cek apakah ada item yang terkait dengan type item ini
            // (Ini penting karena di database ada ON DELETE RESTRICT)
            $typeItem = TypeItems::find($this->typeItemToDeleteId);
            if ($typeItem && $typeItem->items()->count() > 0) {
                session()->flash('error', 'Tidak dapat menghapus tipe item ini karena masih ada item yang terkait dengannya.');
                $this->closeDeleteModal();
                return;
            }

            TypeItems::destroy($this->typeItemToDeleteId); // Menggunakan destroy untuk menghapus
            session()->flash('message', 'Tipe item berhasil dihapus!');
        }
        $this->closeDeleteModal();
    }

    // Tutup modal create/edit
    public function closeModal()
    {
        $this->isModalOpen = false;
    }

    // Tutup modal konfirmasi hapus
    public function closeDeleteModal()
    {
        $this->isDeleteModalOpen = false;
        $this->typeItemToDeleteId = null;
    }

    // Reset semua input form
    private function resetInputFields()
    {
        $this->typeItemId = null;
        $this->name = '';
        $this->description = '';
    }

    // Metode render komponen Livewire
    public function render()
    {
        // Query untuk mengambil data type items
        $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); // Paginate 10 item per halaman
        return view('livewire.type-item-table', [
            'typeItems' => $typeItems,
        ]);
    }
}
