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

        $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' => ''];
            }
            $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;
    }
}
