<?php

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

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

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;
        }

        $warehouseName = 'CoVeto Lyon';

        $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->codeCoveto;
        $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);
        // @phpstan-ignore-next-line
        $store->website = $clinicModel->siteInternet;
        $languages = \Language::getLanguages(true, false, true);
        // @phpstan-ignore-next-line
        $store->hours = [];
        foreach ($languages as $langId) {
            // @phpstan-ignore-next-line
            $store->hours[$langId] = [[''], [''], [''], [''], [''], [''], ['']];
        }

        /** @var int[] $languages */
        $languages = \Language::getLanguages(true, false, true);
        foreach ($languages as $idLang) {
            $store->address1[$idLang] = $clinicModel->adresse1;
            $store->address2[$idLang] = $clinicModel->adresse2;
        }

        $store->postcode = $clinicModel->codePostal;
        $store->city = $clinicModel->ville;
        $latitude = \substr(\trim($clinicModel->latitude), 0, 13);
        if (\preg_match('/^(-?[0-9]{1,8}\.[0-9]{1,8})/s', $latitude, $matches)) {
            $store->latitude = \floatval($matches[1]);
        }
        $longitude = \substr(\trim($clinicModel->longitude), 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 = $clinicModel->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();

        $dispatchedFile = $this->dispatchFolder . $clinicModel->codeCoveto . '.json';
        if (\is_file($dispatchedFile)) {
            $storeJson = \json_decode(\file_get_contents($dispatchedFile) ?: '', true);
            if (!\is_array($storeJson)) {
                $storeJson = [
                    'store_id' => '',
                ];
            }

            $logoFileName = _PS_IMG_DIR_ . 'e/' . $clinic->id_employee . '.jpg';

            if ($storeJson['store_id'] && !\is_file($logoFileName)) {
                $logoUrl = 'https://10petitszebres.com/img/st/' . $storeJson['store_id']
                    . '/logo_' . $storeJson['store_id'] . '.jpg';

                // Import du logo
                \copy($logoUrl, $logoFileName);
            }
        }

        // Import logo depuis 10Ptz
        // X = id_store
        // https://10petitszebres.com/img/st/X/logo_X.jpg

        return $clinic;
    }
}
