<?php

declare(strict_types=1);

class Cart extends CartCore
{
    /**
     * @return array<string, mixed>
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     *
     * {@inheritDoc}
     */
    public function getDeliveryOptionList(Country $default_country = null, $flush = false): array
    {
        require_once _PS_MODULE_DIR_ . 'myvetshopclinique' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'Clinique.php';
        require_once _PS_MODULE_DIR_ . 'myvetshopclinique' . DIRECTORY_SEPARATOR . 'Service' . DIRECTORY_SEPARATOR . 'PostalCodeChecker.php';

        $ret = parent::getDeliveryOptionList($default_country, $flush);

        $customer = new Customer($this->id_customer);
        $clinique_id = Clinique::getCliniqueByGroup($customer->id_default_group);

        if ($clinique_id) {
            $clinique = new Clinique($clinique_id);

            $holidays = Db::getInstance()->getValue(
                'SELECT (CURDATE() BETWEEN mch.date_debut AND mch.date_fin) FROM `' . _DB_PREFIX_ . 'myvetshop_clinique_holidays` mch 
                        WHERE mch.id_myvetshop_clinique = ' . (int) $clinique_id . ' AND (
                            CURDATE() BETWEEN mch.date_debut AND mch.date_fin
                            OR
                            CURDATE() BETWEEN mch.date_alerte AND mch.date_debut
                        )'
            );

            // Si demandé, on bloque la livraison en clinique
            if ($holidays) {
                foreach ($ret as $id_address => &$deliveries) {
                    $deliveries = array_filter(
                        $deliveries,
                        function ($key) use ($clinique) {
                            return !in_array($clinique->id_carrier, explode(',', $key));
                        },
                        ARRAY_FILTER_USE_KEY
                    );
                }
            }
        }

        // Vérifie si le code postal est valide pour une livraison à domicile sinon retire la livraison à domicile

        $postalCodeChecker = new PostalCodeChecker();
        foreach ($ret as $id_address => $deliveries) {
            foreach ($deliveries as $keyCarrier => $delivery) {
                $idDelivery = (int) str_replace(',', '', $keyCarrier);

                $carrier = new Carrier($idDelivery);

                if ($carrier->domicile) {
                    $address = new Address($id_address);

                    if ('France' == $address->country) {
                        try {
                            $postalCodeChecker->check($address->postcode);
                        } catch (Exception $exception) {
                            unset($ret[$id_address][$keyCarrier]);
                        }
                    }
                }
            }
        }

        return $ret;
    }
}
