<?php

namespace App\Livewire\Admin;

use App\Models\Plan;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;

class DeletePlanModal extends Component
{
    #[Locked]
    public $planId;

    public $planName;

    public $showModal = false;

    #[On('delete-plan')]
    public function confirmDelete($id, $name)
    {
        $this->planId = $id;
        $this->planName = $name;
        $this->showModal = true;
    }

    public function delete()
    {
        if (config('app.demo')) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.demo_mode_deletion_disabled')
            );
            $this->closeModal();

            return;
        }

        if ($this->planId) {
            $plan = Plan::findOrFail($this->planId);

            // Prevent deletion of default plan
            if ($plan->is_default) {
                $this->dispatch('show-toast',
                    type: 'error',
                    message: __('common.cannot_delete_default_plan')
                );
                $this->closeModal();

                return;
            }

            $plan->delete();
            $this->dispatch('show-toast',
                type: 'success',
                message: __('common.item_deleted', ['item' => 'Plan'])
            );
            $this->closeModal();
            $this->dispatch('planUpdated');
            $this->dispatch('closePlanForm');
        }
    }

    public function closeModal()
    {
        $this->showModal = false;
        $this->planId = null;
        $this->planName = null;
    }

    public function render()
    {
        return view('livewire.admin.delete-plan-modal');
    }
}
