<?php

namespace App\Rules\SoftwareLicense;

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

class LicenseKeysCount implements ValidationRule
{

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(protected $licensePurchased = 0, protected $count = null)
    {
    }

    /**
     * Run the validation rule.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!$value) {
            return;
        }

        $word = explode(PHP_EOL, $value);
        foreach ($word as $individualKey) {
            if (str_replace([PHP_EOL, ' ', ',', "\n", "\r"], '', $individualKey) == '') {
                if ($key = array_search($individualKey, $word)) {
                    unset($word[$key]);
                }
            }
        }
        if (count($word) > $this->licensePurchased) {
            if ($this->count) {
                $fail('Line no ' . $this->count . ' : The # of keys must be less than or equal to licenses purchased');
                return;
            }
            $fail('The # of keys must be less than or equal to licenses purchased');
            return;
        }
    }
}
