<?php

namespace Opencart\Extension\Alsendo\Repositories;

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

use Opencart\Extension\Alsendo\Models\Config;

class ConfigRepository
{
    private object $db;
    private string $tablePrefix;

    public function __construct(object $db, string $tablePrefix = '')
    {
        $this->db = $db;
        $this->tablePrefix = $tablePrefix ?: (defined('\DB_PREFIX') ? \DB_PREFIX : '');
    }

    public function getConfig(): Config
    {
        $region = $this->getSetting('region');
        $apiConfig = [
            'app_id' => $this->getSetting('app_id'),
            'app_secret' => $this->getSetting('app_secret'),
            'sandbox' => $this->getSetting('sandbox'),
            'ro_sandbox' => $this->getSetting('ro_sandbox'),
            'cz_sandbox' => $this->getSetting('cz_sandbox'),
            'token' => $this->getSetting('token'),
            'api_key' => $this->getSetting('api_key'),
            'ro_client_id' => $this->getSetting('ro_client_id'),
            'ro_client_secret' => $this->getSetting('ro_client_secret'),
            'ro_client_oauth_code' => $this->getSetting('ro_client_oauth_code'),
            'ro_client_oauth_access_token' => $this->getSetting('ro_client_oauth_access_token'),
            'ro_client_oauth_refresh_token' => $this->getSetting('ro_client_oauth_refresh_token'),
            'ro_client_oauth_expires_at' => $this->getSetting('ro_client_oauth_expires_at')
        ];

        return new Config($region, $apiConfig);
    }

    public function saveRegion(string $region): void
    {
        $this->deleteSetting('region');
        $this->saveSetting('region', $region);
    }

    public function upsert(string $code, string $key, string $value): void
    {
        $store_id = 0;
        $escaped_code = $this->db->escape($code);
        $escaped_key = $this->db->escape($key);
        $escaped_value = $this->db->escape($value);

        $query = $this->db->query("
            SELECT `setting_id` FROM `" . $this->tablePrefix . "setting` 
            WHERE `store_id` = '$store_id' AND `code` = '$escaped_code' AND `key` = '$escaped_key'
        ");

        if ($query->num_rows) {
            $setting_id = (int)$query->row['setting_id'];
            $this->db->query("UPDATE `" . $this->tablePrefix . "setting` 
            SET `value` = '$escaped_value' 
            WHERE `setting_id` = $setting_id");
        } else {
            $this->db->query("INSERT INTO `" . $this->tablePrefix . "setting` 
            SET `store_id` = '$store_id', 
                `code` = '$escaped_code', 
                `key` = '$escaped_key', 
                `value` = '$escaped_value', 
                `serialized` = '0'");
        }
    }

    public function saveApiConfig(array $apiConfig): void
    {
        foreach ($apiConfig as $key => $value) {
            if (isset($value) && $value !== '') {
                $this->saveSetting($key, $value);
            }
        }
    }

    public function saveApiKeys(string $appId, string $appSecret): void
    {
        $this->saveApiConfig(['app_id' => $appId, 'app_secret' => $appSecret]);
    }

    public function getSetting(string $key): string
    {
        $query = $this->db->query("SELECT `value` FROM `" . $this->tablePrefix . "setting` WHERE `code` = 'alsendo' AND `key` = '" . $this->db->escape($key) . "'");
        
        return $query->num_rows ? $query->row['value'] : '';
    }

    private function saveSetting(string $key, string $value): void
    {
        $escapedKey = $this->db->escape($key);
        $escapedValue = $this->db->escape($value);

        $query = $this->db->query("SELECT setting_id FROM `{$this->tablePrefix}setting` WHERE `code` = 'alsendo' AND `key` = '{$escapedKey}' LIMIT 1");

        if ($query->num_rows) {
            $this->db->query("UPDATE `{$this->tablePrefix}setting` 
            SET `value` = '{$escapedValue}' 
            WHERE `code` = 'alsendo' AND `key` = '{$escapedKey}'");
        } else {
            $this->db->query("INSERT INTO `{$this->tablePrefix}setting` 
            SET `store_id` = '0', 
                `code` = 'alsendo', 
                `key` = '{$escapedKey}', 
                `value` = '{$escapedValue}', 
                `serialized` = '0'");
        }
    }

    private function deleteSetting(string $key): void
    {
        $this->db->query("DELETE FROM `" . $this->tablePrefix . "setting` WHERE `code` = 'alsendo' AND `key` = '" . $this->db->escape($key) . "'");
    }
} 