<?php

namespace Opencart\Admin\Model\Extension\Alsendo\Module;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/Entity/OrderDetailsEntityFactoryInterface.php');
require_once(DIR_EXTENSION . 'alsendo/src/DTO/Entity/Apaczka/ApaczkaOrderDetailsEntityFactory.php');

use Opencart\Extension\Alsendo\DTO\Entity\AbstractOrderDetailsPackageEntity;
use Opencart\Extension\Alsendo\DTO\Entity\OrderDetailsEntityFactoryInterface;
use Opencart\Extension\Alsendo\DTO\Entity\Apaczka\ApaczkaOrderDetailsEntityFactory;
use Opencart\System\Engine\Model;
use Opencart\System\Engine\Registry;

class AlsendoOrderDetailsPackage extends Model
{
    public function __construct(Registry $registry)
    {
        parent::__construct($registry);
    }

    public function populate(): void
    {
        $this->db->query("
            CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "alsendo_order_details_packages` (
                `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                `order_details_package_details_id` INT(11) UNSIGNED DEFAULT NULL,
                `template_id` INT(11) NULL DEFAULT NULL,
                `template_name` VARCHAR(255) NULL DEFAULT NULL,
                `package_height` INT(11) NULL DEFAULT NULL,
                `package_width` INT(11) NULL DEFAULT NULL,
                `package_length` INT(11) NULL DEFAULT NULL,
                `package_weight` DOUBLE NULL DEFAULT NULL,
                `package_shipment_packaging` VARCHAR(255) NULL DEFAULT NULL,
                `non_standard` TINYINT(1) NULL DEFAULT NULL,
                PRIMARY KEY (`id`),
                CONSTRAINT `fk_alsendo_order_details_packages_package_details`
                    FOREIGN KEY (`order_details_package_details_id`)
                    REFERENCES `" . DB_PREFIX . "alsendo_order_details_package_details` (`id`)
                    ON DELETE CASCADE,
                CONSTRAINT `fk_alsendo_order_details_packages_template`
                    FOREIGN KEY (`template_id`)
                    REFERENCES `" . DB_PREFIX . "alsendo_shipping_settings_templates` (`id`)
                    ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        ");
    }

    public function getPackagesByOrderDetailsPackageDetailsId(int $orderDetailsPackageDetailsId, ?OrderDetailsEntityFactoryInterface $factory = null): array
    {
        $query = $this->db->query("
            SELECT *
            FROM `" . DB_PREFIX . "alsendo_order_details_packages`
            WHERE order_details_package_details_id = '" . (int)$orderDetailsPackageDetailsId . "'
        ");
        $factory = $factory ?? new ApaczkaOrderDetailsEntityFactory();
        $result = [];
        foreach ($query->rows as $row) {
            $result[] = $factory->createPackageFromArray($row);
        }
        return $result;
    }

    public function insertPackage(int $orderDetailsPackageDetailsId, array $data): void
    {
        $templateId = array_key_exists('package_template_id', $data) ? $data['package_template_id'] : (array_key_exists('template_id', $data) ? $data['template_id'] : null);
        $templateIdSql = ($templateId !== null && $templateId !== '') ? "'" . (int)$templateId . "'" : "NULL";
        $templateNameSql = array_key_exists('template_name', $data) ? ($data['template_name'] === null ? "NULL" : "'" . $this->db->escape($data['template_name']) . "'") : "NULL";
        $heightSql = (array_key_exists('package_height', $data) && $data['package_height'] !== null && $data['package_height'] !== '') ? "'" . (int)$data['package_height'] . "'" : "NULL";
        $widthSql = (array_key_exists('package_width', $data) && $data['package_width'] !== null && $data['package_width'] !== '') ? "'" . (int)$data['package_width'] . "'" : "NULL";
        $lengthSql = (array_key_exists('package_length', $data) && $data['package_length'] !== null && $data['package_length'] !== '') ? "'" . (int)$data['package_length'] . "'" : "NULL";
        $weightSql = (array_key_exists('package_weight', $data) && $data['package_weight'] !== null && $data['package_weight'] !== '') ? "'" . (float)$data['package_weight'] . "'" : "NULL";
        $packagingSql = array_key_exists('package_shipment_packaging', $data) ? ($data['package_shipment_packaging'] === null ? "NULL" : "'" . $this->db->escape($data['package_shipment_packaging']) . "'") : "NULL";
        $nonStandardSql = array_key_exists('non_standard', $data) ? "'" . ((bool)$data['non_standard'] ? '1' : '0') . "'" : "NULL";
        $this->db->query("
            INSERT INTO `" . DB_PREFIX . "alsendo_order_details_packages`
            SET `order_details_package_details_id` = '" . (int)$orderDetailsPackageDetailsId . "',
                `template_id` = " . $templateIdSql . ",
                `template_name` = " . $templateNameSql . ",
                `package_height` = " . $heightSql . ",
                `package_width` = " . $widthSql . ",
                `package_length` = " . $lengthSql . ",
                `package_weight` = " . $weightSql . ",
                `package_shipment_packaging` = " . $packagingSql . ",
                `non_standard` = " . $nonStandardSql . "
        ");
    }

    public function deleteByPackageDetailsId(int $packageDetailsId): void
    {
        $this->db->query("
            DELETE FROM `" . DB_PREFIX . "alsendo_order_details_packages`
            WHERE order_details_package_details_id = '" . (int)$packageDetailsId . "'
        ");
    }
}
