<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Validation\Rule;

class CommaSeparatedFields implements ValidationRule
{
    public function __construct(
        protected mixed $model = null,
        protected bool $checkIfFieldExists = false
    ) {}

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $values = explode(',', $value);

        foreach ($values as $value) {
            if (empty($value) || is_numeric($value)) {

            } else {
                if (validator(
                    data: ['key' => $value],
                    rules: [
                        'key' => ['required', 'string', 'alpha_dash:ascii'],
                    ]
                )->fails()
                ) {
                    info([
                        'failed' => $value,
                    ]);
                } else {
                    info([
                        'passed' => $value,
                    ]);
                }
            }
        }

        // $fields = (new $this->model)->getFillable();

        // if ($this->checkIfFieldExists) {
        //     foreach ($values as $value) {
        //         if (! empty($value) && ! in_array($value, $fields)) {
        //             $fail(sprintf(
        //                 "Field '%s' does not exit in table, available fields: %s",
        //                 $value,
        //                 implode(', ', $fields),
        //             ));
        //         }
        //     }
        // }
    }
}
