<?php

namespace Opencart\Extension\Alsendo\Repositories;

require_once(DIR_EXTENSION . 'alsendo/src/Models/ShippingSettingsTemplate.php');

use Opencart\Extension\Alsendo\Models\ShippingSettingsTemplate;

class ShippingSettingsRepository
{
    private $db;
    private string $tablePrefix;

    public function __construct($db, string $tablePrefix)
    {
        $this->db = $db;
        $this->tablePrefix = $tablePrefix;
    }

    public function getIdNameMap(): array
    {
        $query = $this->db->query("SELECT `id`, `name` FROM `" . $this->tablePrefix . "alsendo_shipping_settings_templates`");
        $map = [];
        foreach ($query->rows as $row) {
            $map[(int)$row['id']] = $row['name'];
        }
        return $map;
    }

    public function getAllTemplates(): array
    {
        $query = $this->db->query("SELECT * FROM `" . $this->tablePrefix . "alsendo_shipping_settings_templates` ORDER BY `main` DESC, `id` DESC");
        $templates = [];
        
        foreach ($query->rows as $row) {
            $templates[] = new ShippingSettingsTemplate($row);
        }
        
        return $templates;
    }

    public function getTemplateById(int $id): ?ShippingSettingsTemplate
    {
        $query = $this->db->query("SELECT * FROM `" . $this->tablePrefix . "alsendo_shipping_settings_templates` WHERE `id` = '" . (int)$id . "'");
        
        if ($query->num_rows) {
            return new ShippingSettingsTemplate($query->row);
        }
        
        return null;
    }

    public function getMainTemplate(): ?ShippingSettingsTemplate
    {
        $query = $this->db->query("SELECT * FROM `" . $this->tablePrefix . "alsendo_shipping_settings_templates` WHERE `main` = 1 LIMIT 1");
        
        if ($query->num_rows) {
            return new ShippingSettingsTemplate($query->row);
        }
        
        return null;
    }

    public function saveTemplate(array $data): int
    {
        $defaultContent = $data['shipment_content'] ?? '';

        $defaultContentCustomText = null;
        if (!empty($data['default_content_custom_text']) && $defaultContent === 'custom_text') {
            $defaultContentCustomText = $this->db->escape($data['default_content_custom_text']);
        }

        $cashOnDelivery = null;
        if (!empty($data['cash_on_delivery'])) {
            $cashOnDelivery = (int) $data['cash_on_delivery'];
        }

        $declaredValue = null;
        if (!empty($data['declared_value'])) {
            $declaredValue = (int) $data['declared_value'];
        }
        $nonStandard = (int)(isset($data['non_standard']) && $data['non_standard']);
        $this->clearMainFlag();
        $this->db->query("INSERT INTO `" . $this->tablePrefix . "alsendo_shipping_settings_templates` SET 
        `name` = '" . $this->db->escape($data['name']) . "',
        `package_type` = '" . $this->db->escape($data['package_type']) . "',
        `length` = '" . (int)$data['length'] . "',
        `width` = '" . (int)$data['width'] . "',
        `height` = '" . (int)$data['height'] . "',
        `weight` = '" . (int)$data['weight'] . "',
        `default_content` = '" . $this->db->escape($defaultContent) . "',
        `default_content_custom_text` = " . (($defaultContentCustomText === null) ? "NULL" : "'" . $defaultContentCustomText . "'") . ",
        `pickup_type` = '" . $this->db->escape($data['pickup_type']) . "',
        `cash_on_delivery` = '" . $cashOnDelivery . "',
        `declared_value` = '" . $declaredValue . "',
        `non_standard` = '" . $nonStandard . "',
        `main` = '1'");

        return $this->db->getLastId();
    }

    public function updateTemplate(int $id, array $data): bool
    {
        $defaultContent = $data['shipment_content'] ?? '';

        $defaultContentCustomText = null;
        if (!empty($data['default_content_custom_text']) && $defaultContent === 'custom_text') {
            $defaultContentCustomText = $data['default_content_custom_text'];
        }

        $cashOnDelivery = null;
        if (!empty($data['cash_on_delivery'])) {
            $cashOnDelivery = (int) $data['cash_on_delivery'];
        }

        $declaredValue = null;
        if (!empty($data['declared_value'])) {
            $declaredValue = (int) $data['declared_value'];
        }
        $nonStandard = (int)(isset($data['non_standard']) && $data['non_standard']);

        $this->db->query("UPDATE `" . $this->tablePrefix . "alsendo_shipping_settings_templates` SET 
        `name` = '" . $this->db->escape($data['name']) . "',
        `package_type` = '" . $this->db->escape($data['package_type']) . "',
        `length` = '" . (int)$data['length'] . "',
        `width` = '" . (int)$data['width'] . "',
        `height` = '" . (int)$data['height'] . "',
        `weight` = '" . (int)$data['weight'] . "',
        `default_content` = '" . $this->db->escape($defaultContent) . "',
        `default_content_custom_text` = " . (($defaultContentCustomText === null) ? "NULL" : "'" . $this->db->escape($defaultContentCustomText) . "'") . ",
        `pickup_type` = '" . $this->db->escape($data['pickup_type']) . "',
        `cash_on_delivery` = '" . $cashOnDelivery . "',
        `declared_value` = '" . $declaredValue . "',
        `non_standard` = '" . $nonStandard . "'
        WHERE `id` = '" . (int)$id . "'");

        return true;
    }

    public function deleteTemplate(int $id): bool
    {
        $this->db->query("DELETE FROM `" . $this->tablePrefix . "alsendo_shipping_settings_templates` WHERE `id` = '" . (int)$id . "'");
        return true;
    }

    public function setAsMain(int $id): bool
    {
        $this->db->query("UPDATE `" . $this->tablePrefix . "alsendo_shipping_settings_templates` SET `main` = '0'");
        $this->db->query("UPDATE `" . $this->tablePrefix . "alsendo_shipping_settings_templates` SET `main` = '1' WHERE `id` = '" . (int)$id . "'");
        return true;
    }

    public function hasMainTemplate(): bool
    {
        $query = $this->db->query("SELECT COUNT(*) as total FROM `" . $this->tablePrefix . "alsendo_shipping_settings_templates` WHERE `main` = 1");
        return $query->row['total'] > 0;
    }

    private function clearMainFlag(): void
    {
        $this->db->query("UPDATE `" . $this->tablePrefix . "alsendo_shipping_settings_templates` SET `main` = 0");
    }
} 