<?php

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

use Myvetshop\Module\Clinique\Import\Kalivet\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':
                $warehouseName = 'ALCYON LYON';
                break;

            case 'PAU':
                $warehouseName = 'ALCYON PAU';
                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 = 'alcyon';
        $clinic->id_warehouse = $warehouseId ?: 1;
        $clinic->code_client = $clinicModel->codeAlcyonMyvetshop;
        $clinic->mdp = '';
        $clinic->code_filiere = '';
        $clinic->name = $clinicModel->name;
        $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->jours_livraison = \implode(',', $joursLivraison);
        $clinic->deleted = false;
        $clinic->don = false;

        // Import de la clinique
        $clinic->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();
        }

        return $clinic;
    }
}
