<?php

namespace App\Traits;

use App\Services\PinService;
use Illuminate\Validation\ValidationException;

trait RequiresConfirmation
{
    public array $prevalidatedData = [];

    /**
     * Step 1: Prevalidate form data and open confirmation modal
     */
    public function validateAndConfirm(array $data, array $rules = [], array $messages = [])
    {
        if (!empty($rules)) {
            $this->validate($rules, $messages);
        }

        $this->prevalidatedData = $data;
        $this->dispatch('open-confirmation-modal');
    }


    /**
     * Step 2: Confirm action callback
     * The actual action is executed in the closure from the component
     */
    public function confirmAction(\Closure $callback)
    {
        if (!$this->prevalidatedData) {
            $this->addError('error', 'No action to confirm.');
            return;
        }

        $callback($this->prevalidatedData);

        $this->dispatch('confirmation-success');

        // Clear prevalidated snapshot
        $this->prevalidatedData = [];
    }

    /**
     * Cancel confirmation
     */
    public function cancelConfirmation()
    {
        $this->prevalidatedData = [];
        $this->dispatch('close-confirmation-modal');
    }

}