<?php

namespace App\Validators;

use Illuminate\Support\Facades\View;

class Base64Validator
{
	/**
	 * Check if the file is in base64 image
	 */
	public function validateBase64($attribute, $value, $parameters, $validator)
	{
		if ($value === null || $value === '') {
			return true;
		}

		$explode = $this->explodeString($value);
		if (count($explode) < 2) {
			return false;
		}

		$allow = $this->allowedFormat();
		$format = $this->dataFormat($explode);

		// check file format
		if (!in_array($format, $allow)) {
			return false;
		}

		// check base64 format
		if (!preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $explode[1])) {
			return false;
		}

		$maxBytes = $this->maxSizeBytes();
		if ($maxBytes !== null) {
			$data = base64_decode($explode[1], true);
			if ($data === false || strlen($data) > $maxBytes) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Max upload size in bytes from site_settings (max_allowed_image_size is in KB).
	 */
	protected function maxSizeBytes(): ?int
	{
		$settings = View::shared('getSettings');
		if (!is_array($settings) || !isset($settings['max_allowed_image_size'])) {
			return null;
		}
		$kb = (int) $settings['max_allowed_image_size'];
		return $kb > 0 ? $kb * 1024 : null;
	}

	/**
	 * Check the data format
	 */
	public function dataFormat($explode)
	{
		return str_replace(
			[
					'data:image/',
					';',
					'base64',
			],
			[
					'', '', '',
			],
			$explode[0]
		);
	}

	/**
	 * The allowed format in base 64 image
	 */
	public function allowedFormat()
	{
		return ['gif', 'jpg', 'jpeg', 'png','webp'];
	}

	/**
	 * Explode base 64 image
	 */
	public function explodeString($value)
	{
		return explode(',', $value);
	}
}