<?php

namespace Myvetshop\Module\Clinique\Command\Sync;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;

class SyncCategoriesCommand extends Command
{
    public function __construct()
    {
        parent::__construct('app:sync:categories');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('Syncing categories');

        /** @var array{categories: list<array<mixed>>} $categories */
        $categories = Yaml::parseFile(\dirname(__DIR__, 3) . '/data/categories.yaml');
        $parentCat = \Category::getRootCategory();

        /** @var array{id: int, name: string, position: int, children?: list<array<mixed>>} $category */
        foreach ($categories['categories'] as $category) {
            $this->syncCategory($category, $parentCat);
        }

        return 0;
    }

    /**
     * @param array{id: int, name: string, position: int, children?: list<array<mixed>>} $category
     *
     * @return void
     */
    private function syncCategory(array $category, \Category $parent): void
    {
        $now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');

        $idCategory = \Db::getInstance()->getValue(
            'SELECT id_category FROM ' . _DB_PREFIX_ . 'category WHERE id_category = ' . (int) $category['id'],
            false
        );
        if (!$idCategory) {
            $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'category (id_category, id_parent, id_shop_default, date_add, date_upd)'
                . ' VALUES (' . (int) $category['id']
                . ', ' . (int) $parent->id
                . ', ' . (int) $parent->id_shop_default
                . ', "' . $now . '", "' . $now . '"' . ')';

            \Db::getInstance()->execute(
                $sql,
                false
            );
        }

        $categoryObj = new \Category($category['id']);

        $categoryObj->name = [1 => $category['name']];
        $categoryObj->link_rewrite = [1 => \Tools::link_rewrite($category['name'])];
        $categoryObj->position = $category['position'];
        $categoryObj->id_parent = (int) $parent->id;
        $categoryObj->active = true;
        $actualGroups = $categoryObj->getGroups();
        if (!\is_array($actualGroups)) {
            $actualGroups = [];
        }
        $missingGroups = \array_values(\array_diff([1, 2, 3], $actualGroups));
        if (!empty($missingGroups)) {
            $categoryObj->addGroups($missingGroups);
        }

        try {
            $saved = $categoryObj->save();
        } catch (\Exception $e) {
            throw new \Exception('Error while saving category : ' . $category['id'] . ' : ' . $e->getMessage());
        }
        if (!$saved) {
            throw new \Exception('Error while saving category : ' . $category['id']);
        }

        if (isset($category['children'])) {
            /** @var array{id: int, name: string, position: int, children?: list<array<mixed>>} $child */
            foreach ($category['children'] as $child) {
                $this->syncCategory($child, $categoryObj);
            }
        }
    }
}
