<?php

namespace inpost_shipping\Model\Validator;

class InpostRequestValidator
{
    /**
     * @param array $request
     * @param $ocRegistry
     *
     * @return string
     */
    public function validateShippingMethodSaveRequest(array $request, $ocRegistry): string
    {
        $idMethod = (int)str_replace('inpost_shipping_', '', explode('.', $request['shipping_method'])[0]);
        $methodData = $ocRegistry->db
            ->query("SELECT * FROM `".DB_PREFIX."inpost_shipping_methods` WHERE id_shipping_method = '".$idMethod."'")
            ->row;

        $response = '';


        if (empty($methodData['fk_delivery_service']) || $methodData['fk_delivery_service'] == 0) {
            return $response;
        }

        $deliveryServiceData = $ocRegistry->db
            ->query("SELECT * FROM `".DB_PREFIX."inpost_shipping_delivery_services` WHERE id_delivery_service = '".(int)$methodData['fk_delivery_service']."'")
            ->row;

        if (empty($deliveryServiceData)) {
            $response = 'This shipping method is not available. Please, contact a support team.';
        }

        $lockerServices = [
            'inpost_locker_standard',
            'inpost_locker_allegro',
            'inpost_locker_pass_thru',
            'inpost_courier_c2c',
        ];

        if (in_array($deliveryServiceData['deliveryService'], $lockerServices) && empty($request['parcelLocker'])) {
            $response = 'Please, select a parcel locker';
        }

        return $response;
    }
}