<?php

declare(strict_types=1);

class ExportProduct extends ObjectModel
{
    public const TABLE = 'myvetshop_export_product';

    /** @var int */
    public $id_export_product;

    /** @var int */
    public $id_myvetshop_clinique;

    /** @var string */
    public $name;

    /** @var string */
    public $date_start;

    /** @var string */
    public $date_end;

    /** @var string */
    public $products;

    /** @var string */
    public $filters;

    /** @var string Object creation date */
    public $date_add;

    /** @var string Object last modification date */
    public $date_upd;

    /** @var bool */
    public $execute;

    /** @var bool */
    public $deleted;

    /**
     * @see ObjectModel::$definition
     *
     * @var array{fields: array<string, array<mixed>>}
     */
    public static $definition = [
        'table' => self::TABLE,
        'primary' => 'id_export_product',
        'multilang' => false,
        'multilang_shop' => false,
        'fields' => [
            // ID Externe
            'id_myvetshop_clinique' => ['type' => self::TYPE_INT],

            'name' => ['type' => self::TYPE_STRING, 'required' => true],
            'date_start' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false],
            'date_end' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false],
            'products' => ['type' => self::TYPE_STRING, 'validate' => ''],
            // Flag pour la suppression
            'deleted' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => false],
            'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false],
            'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false],
        ],
    ];

    public function __construct($id = null)
    {
        parent::__construct($id);

        $this->webserviceParameters =
            [
                'hidden_fields' => ['products'],
                'fields' => [
                    'id_myvetshop_clinique' => [],
                    'name' => [],
                    'date_start' => [],
                    'date_end' => [],
                    'filters' => [],
                    'date_add' => [],
                    'date_upd' => [],
                ],
                'associations' => [
                    'products' => ['resource' => 'product', 'setter' => false, 'virtual_entity' => true,
                        'fields' => [
                            'id' => [],
                            'name' => [],
                        ],
                    ],
                ],
            ];
    }

    /**
     * @return array<array{id: int, name: string}>|null
     *
     * @throws PrestaShopDatabaseException
     */
    public function getWsProducts(): ?array
    {
        if (!$this->products) {
            return null;
        }
        $productsId = \json_decode($this->products, true);
        if (!\is_array($productsId)) {
            $productsId = [];
        }

        // Clean des valeurs (normalement sans risque)
        $productsId = \array_map(fn ($id) => (int) $id, $productsId);

        $productsId = \implode(', ', $productsId);

        $db = \Db::getInstance();

        $query = '
                    SELECT product.id_product as id, product_lang.name as name  FROM `' . _DB_PREFIX_ . 'product` AS product
                    INNER JOIN `' . _DB_PREFIX_ . 'product_lang` AS product_lang ON product_lang.id_product = product.id_product
                    WHERE product.id_product IN (' . $productsId . ')';

        $result = $db->executeS($query);

        if (!\is_array($result)) {
            $result = [];
        }

        return $result;
    }

    /**
     * @param array<array{id?: int, name?: string}> $products
     *
     * @return bool
     *
     * @throws Exception
     */
    public function setWsProducts(array $products): bool
    {
        $productId = [];

        foreach ($products as $product) {
            if (
                !isset($product['id'])
                || !$product['id']
                || !isset($product['name'])
                || !$product['name']
            ) {
                throw new Exception('Données invalides.');
            }

            $productInBdd = new Product($product['id']);

            if (!$productInBdd->id) {
                throw new Exception('Ce produit n\'existe pas.');
            }

            $productId[] = $productInBdd->id;
        }
        $this->products = \json_encode($productId) ?: '';

        return true;
    }

    public static function install(): bool
    {
        $query = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . static::TABLE . '` (
              `id_export_product` INT(11) NOT NULL AUTO_INCREMENT,
              `id_myvetshop_clinique` INT(11) NOT NULL,
              `name` VARCHAR(50) NOT NULL,
              `date_start` DATE NOT NULL,
              `date_end` DATE NOT NULL,
              `products` TEXT  NOT NULL,
              `date_add` DATE NOT NULL,
              `date_upd` DATE NOT NULL,
              `deleted` BOOL NOT NULL DEFAULT FALSE,

               PRIMARY KEY (`id_export_product`)
            );';

        return Db::getInstance()->execute($query);
    }
}
