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

    /**
     * @var array<string, mixed>
     *
     * @see ObjectModel::$definition
     */
    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],
            ],
        ];

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    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<string, mixed>|bool
     *
     * @throws PrestaShopDatabaseException
     */

    /** @phpstan-ignore-next-line */
    public function getWsProducts()
    {
        if ($this->products) {
            $productsId = json_decode($this->products, true);

            //Clean des valeurs (normalement sans risque)
            $productsId = array_map(function ($id) {
                return (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<string, mixed> $products
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    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.');
            }

            array_push($productId, $productInBdd->id);
        }

        $jsonProductId = json_encode($productId);

        if (!$jsonProductId) {
            throw new Exception('Une erreur s\'est produite');
        }

        $this->products = $jsonProductId;

        return true;
    }
}
