<?php

namespace App\Livewire\Studio\Loyalty;

use App\Livewire\Forms\Studio\Loyalty\CustomerForm;
use App\Models\Customer as CustomerModel;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithUpdatedData;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Customer')]
class Customer extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdatedData;

    public CustomerForm $form;

    public string $method = 'create';

    public string $modalTitle = '';

    public array $stats = [];

    public function mount(): void
    {
        $this->stats = [
            [
                'title' => 'Total Customer',
                'value' => CustomerModel::whereDoesntHave('user')->count(),
            ],
            [
                'title' => 'Total Member',
                'value' => CustomerModel::whereHas('user')->count(),
            ],
            [
                'title' => 'Top Member',
                'value' => CustomerModel::whereHas('user')->whereHas('orders')->withCount('orders')->orderByDesc('orders_count')->first()?->name ?? '-',
            ],
        ];
    }

    #[On('modal:open')]
    public function openModal(string $method, string $modalTitle, ?string $id = null): void
    {
        $this->resetValidation();
        $this->resetErrorBag();

        $this->method = $method;
        $this->modalTitle = $modalTitle;

        $id && $this->form->setCustomer(CustomerModel::byHashOrFail($id));
    }

    public function create(): void
    {
        $this->canOrAbort('create customer');

        $this->form->store();

        $this->dispatch('refreshDatatable');

        $this->toast('Customer berhasil ditambahkan.');

        Flux::modals()->close();
    }

    public function update(): void
    {
        $this->canOrAbort('update customer');

        $this->form->update();

        $this->dispatch('refreshDatatable');

        $this->toast('Customer berhasil diperbarui.');

        Flux::modals()->close();
    }

    public function delete(CustomerModel $customer): void
    {
        $this->canOrAbort('delete customer');

        $customer->delete();

        $this->dispatch('refreshDatatable');

        $this->toast('Customer berhasil dihapus.');

        Flux::modals()->close();
    }

    public function render(): View
    {
        return view('livewire.studio.loyalty.customers', [
            'pageTitle' => 'Customer',
        ]);
    }
}
