<?php declare(strict_types=1);

namespace App\Services\Captcha;

use App\Captcha\Dto\Coordinators;

final readonly class CheckingCommand
{

    /**
     * @param array $captchaCoordinators
     * @param array $userCoordinators
     * @return bool
     */
    public function execute(array $captchaCoordinators, array $userCoordinators): bool
    {
        foreach ($captchaCoordinators as $index => $coordinators) {
            /**
             * @var Coordinators $coordinators
             */

            if (empty($userCoordinators[$index]) || !isset($userCoordinators[$index]['x']) || !isset($userCoordinators[$index]['y'])) {
                return false;
            }

            if (!$this->isInside($coordinators, $userCoordinators[$index])) {
                return false;
            }
        }

        return true;
    }

    private function isInside(Coordinators $captchaCoordinators, array $userCoordinators): bool
    {
        $xMin = min($captchaCoordinators->getX1(), $captchaCoordinators->getX2(), $captchaCoordinators->getX3(), $captchaCoordinators->getX4());
        $xMax = max($captchaCoordinators->getX1(), $captchaCoordinators->getX2(), $captchaCoordinators->getX3(), $captchaCoordinators->getX4());

        $yMin = min($captchaCoordinators->getY1(), $captchaCoordinators->getY2(), $captchaCoordinators->getY3(), $captchaCoordinators->getY4());
        $yMax = max($captchaCoordinators->getY1(), $captchaCoordinators->getY2(), $captchaCoordinators->getY3(), $captchaCoordinators->getY4());

        if (
            $xMin > $userCoordinators['x']
            || $xMax < $userCoordinators['x']
            || $yMin > $userCoordinators['y']
            || $yMax < $userCoordinators['y']
        ) {
            return false;
        }

        return true;
    }
}
