<?php

namespace App\Rules;

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

class Base64FileValidation implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!is_array($value)) {
            $fail("The $attribute must be an array of valid files in either JPEG, PNG, JPG, HEIC, HEIF, or PDF format, and each file should be at most 10MB in size.");
            return;
        }

        foreach ($value as $file) {
            $decodedData = base64_decode($file, true);

            if (
                !preg_match('/^data:(image\/(jpeg|png|jpg|heic|heif)|application\/pdf);base64,/', $file) ||
                strlen($decodedData) > 5 * 1024 * 1024 // 5MB
            ) {
                $fail("Each file in $attribute must be a valid file in either JPEG, PNG, JPG, HEIC, HEIF, or PDF format, and should be at most 5MB in size.");
            }
        }
    }
}
