<?php

namespace App\Livewire\Customer;

use App\Livewire\Forms\CustomerForm;
use App\Models\Customer;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public CustomerForm $form;

    public bool $isEditing = false;

    public string $filterStatus = 'active'; // 'active', 'trashed', 'all'

    public function create()
    {
        $this->isEditing = false;
        $this->form->reset();
        $this->dispatch('open-modal');
    }

    public function edit(Customer $customer)
    {
        $this->isEditing = true;
        $this->form->setCustomer($customer);
        $this->dispatch('open-modal');
    }

    public function save()
    {
        if ($this->isEditing) {
            $this->form->update();
        } else {
            $this->form->store();
        }

        $this->dispatch('close-modal');
        session()->flash('flash.banner', 'Customer saved successfully!');
    }

    public function delete(Customer $customer)
    {
        $customer->delete();
        session()->flash('flash.banner', 'Customer deleted successfully.');
    }

    public function restore($customerId)
    {
        $customer = Customer::withTrashed()->findOrFail($customerId);
        $customer->restore();
        session()->flash('flash.banner', 'Customer restored successfully!');
    }

    public function forceDelete($customerId)
    {
        $customer = Customer::withTrashed()->findOrFail($customerId);
        $customer->forceDelete();
        session()->flash('flash.banner', 'Customer permanently deleted!');
    }

    public function render()
    {
        $query = Customer::query();

        if ($this->filterStatus === 'trashed') {
            $query->onlyTrashed();
        } elseif ($this->filterStatus === 'all') {
            $query->withTrashed();
        }

        $customers = $query->latest()->paginate(10);

        return view('livewire.customer.index', [
            'customers' => $customers,
        ]);
    }
}
