<?php

namespace Myvetshop\Module\Clinique\Import\Kalivet\Clinic;

use Myvetshop\Module\Clinique\Import\ImportFile\ImportDispatcher;
use Myvetshop\Module\Clinique\Import\Kalivet\Model\ClinicModel;

class ClinicImporter
{
    protected \Db $db;

    protected string $dispatchFolder;

    public function __construct(\Db $db)
    {
        $this->db = $db;
        $this->dispatchFolder = sys_get_temp_dir() . DIRECTORY_SEPARATOR
            . ImportDispatcher::DISPATCH_FOLDER_NAME . DIRECTORY_SEPARATOR;
    }

    public function import(ClinicModel $clinicModel): \Clinique
    {
        $clinic = \Clinique::getByCodePrivilege($clinicModel->codePrivilege);

        if (!$clinic) {
            $clinic = new \Clinique();
            $clinic->code_privilege = $clinicModel->codePrivilege;
        }

        switch (\trim($clinicModel->entrepot)) {
            case 'ARRAS':
                $warehouseName = 'ALCYON ARRAS';
                break;

            case 'LAND':
                $warehouseName = 'ALCYON LANDERNEAU';
                break;

            case 'LYON':
                if ($clinicModel->centrale === 'coveto') {
                    $warehouseName = 'CoVeto Lyon';
                } else {
                    $warehouseName = 'ALCYON LYON';
                }
                break;

            case 'PAU':
                $warehouseName = 'ALCYON PAU';
                break;

            case 'PLANCOET':
                $warehouseName = 'CENTRAVET PLANCOET';
                break;

            case 'LAPALISSE':
                $warehouseName = 'CENTRAVET LAPALISSE';
                break;

            case 'NANCY':
                $warehouseName = 'CENTRAVET NANCY';
                break;

            case 'SUD OUEST':
                $warehouseName = 'CENTRAVET SUD OUEST';
                break;

            case 'CASTELNAUDARY':
                $warehouseName = 'CENTRAVET CASTELNAUDARY';
                break;

            case 'ALFORT':
                $warehouseName = 'CENTRAVET ALFORT';
                break;

            default:
                throw new \Exception('Entrepot inconnu : ' . $clinicModel->entrepot);
        }

        $warehouseId = \intval(
            $this->db->getValue(
                'SELECT id_warehouse'
                . ' FROM ' . _DB_PREFIX_ . 'warehouse'
                . ' WHERE name = "' . $this->db->escape($warehouseName) . '"'
                . ' AND deleted = 0'
            )
        );

        $clinic->centrale = $clinicModel->centrale;
        $clinic->id_warehouse = $warehouseId ?: 1;
        $clinic->code_client = $clinicModel->codeAlcyonMyvetshop;
        $clinic->mdp = '';
        $clinic->code_filiere = '';
        $clinic->name = $clinicModel->nomMyvetshop;
        $clinic->email_original = $clinicModel->email;

        $jours = [
            'lundi',
            'mardi',
            'mercredi',
            'jeudi',
            'vendredi',
            'samedi',
            'dimanche',
        ];

        $joursLivraison = [];
        foreach ($jours as $jour) {
            $property = 'livraison' . \ucfirst($jour);

            if (!empty($clinicModel->$property)) {
                $joursLivraison[] = $jour;
            }
        }

        $clinic->deleted = false;
        $clinic->don = false;

        // Import de la clinique
        $clinic->save();

        $shipping = $clinic->getShipping();
        if (!$shipping->id_myvetshop_clinique) {
            $shipping->id_myvetshop_clinique = (int) $clinic->id;
        }
        if (\in_array('lundi', $joursLivraison)) {
            $shipping->monday = true;
        }
        if (\in_array('mardi', $joursLivraison)) {
            $shipping->tuesday = true;
        }
        if (\in_array('mercredi', $joursLivraison)) {
            $shipping->wednesday = true;
        }
        if (\in_array('jeudi', $joursLivraison)) {
            $shipping->thursday = true;
        }
        if (\in_array('vendredi', $joursLivraison)) {
            $shipping->friday = true;
        }
        if (\in_array('samedi', $joursLivraison)) {
            $shipping->saturday = true;
        }
        if (\in_array('dimanche', $joursLivraison)) {
            $shipping->sunday = true;
        }
        $shipping->save();

        $store = new \Store($clinic->id_store);
        $languages = \Language::getLanguages(true, false, true);
        // @phpstan-ignore-next-line
        $store->hours = [];
        foreach ($languages as $langId) {
            // @phpstan-ignore-next-line
            $store->hours[$langId] = [[''], [''], [''], [''], [''], [''], ['']];
        }

        $horairesFile = $this->dispatchFolder . $clinicModel->codeAlcyonKalivet . '.json';
        if (\is_file($horairesFile)) {
            $storeJson = \json_decode(\file_get_contents($horairesFile) ?: '', true);
            if (!\is_array($storeJson)) {
                $storeJson = [
                    'hours' => '',
                    'clin_adresse1' => '',
                    'clin_adresse2' => '',
                    'cp' => '',
                    'ville' => '',
                    'veto_lat' => '',
                    'veto_long' => '',
                ];
            }

            /** @var int[] $languages */
            $languages = \Language::getLanguages(true, false, true);
            $address1 = \trim($storeJson['clin_adresse1'] ?? '');
            if (!$address1) {
                $address1 = 'Inconnu';
            }
            $address2 = $storeJson['clin_adresse2'] ?? '';
            foreach ($languages as $idLang) {
                $store->address1[$idLang] = $address1;
                $store->address2[$idLang] = $address2;
            }

            $store->postcode = $storeJson['cp'] ?? '';
            $store->city = $storeJson['ville'] ?? '';
            $latitude = \substr(\trim($storeJson['veto_lat'] ?? ''), 0, 13);
            if (\preg_match('/^(-?[0-9]{1,8}\.[0-9]{1,8})/s', $latitude, $matches)) {
                $store->latitude = \floatval($matches[1]);
            }
            $longitude = \substr(\trim($storeJson['veto_long'] ?? ''), 0, 13);
            if (\preg_match('/^(-?[0-9]{1,8}\.[0-9]{1,8})/s', $longitude, $matches)) {
                $store->longitude = \floatval($matches[1]);
            }
            // Hard-coded France
            $store->id_country = 8;

            $hours = \unserialize(\strval($storeJson['hours']));
            if (\is_array($hours)) {
                foreach ($languages as $langId) {
                    foreach ($hours as $i => $hour) {
                        $store->hours[$langId][$i] = [$hour];
                    }
                }

                // @phpstan-ignore-next-line
                $store->hours = \array_map(fn ($hour) => \json_encode($hour) ?: '', $store->hours);
            }

            $store->save();
        }

        // Logo par défaut
        $logoFileName = _PS_IMG_DIR_ . 'e/' . $clinic->id_employee . '.jpg';
        $defaultLogoFile = _PS_MODULE_DIR_ . 'myvetshopclinique/img/logo-kalivet-defaut.jpg';
        if (!\is_file($logoFileName) && \is_file($defaultLogoFile)) {
            \copy($defaultLogoFile, $logoFileName);
        }

        return $clinic;
    }
}
