<?php
namespace Domain\Settings;

/**
 * Repozytorium ustawien — wspolne dla admin i frontendu.
 */
class SettingsRepository
{
    private $db;

    public function __construct($db = null)
    {
        if ($db) {
            $this->db = $db;
            return;
        }

        global $mdb;
        $this->db = $mdb;
    }

    /**
     * Zapis ustawien.
     *
     * @param array $values Tablica wartosci z formularza
     * @return array ['status' => string, 'msg' => string]
     */
    public function saveSettings(array $values): array
    {
        $currentSettings = $this->getSettings();

        $settingsToSave = [
            'firm_name' => $values['firm_name'] ?? '',
            'firm_adress' => $values['firm_adress'] ?? '',
            'additional_info' => $values['additional_info'] ?? '',
            'contact_form' => $this->isEnabled($values['contact_form'] ?? null) ? 1 : 0,
            'contact_email' => $values['contact_email'] ?? '',
            'email_host' => $values['email_host'] ?? '',
            'email_port' => $values['email_port'] ?? '',
            'email_login' => $values['email_login'] ?? '',
            'email_password' => $values['email_password'] ?? '',
            'google_maps' => $values['google_maps'] ?? '',
            'facebook_link' => $values['facebook_link'] ?? '',
            'statistic_code' => $values['statistic_code'] ?? '',
            'htaccess' => $values['htaccess'] ?? '',
            'robots' => $values['robots'] ?? '',
            'shop_bank_account_info' => $values['shop_bank_account_info'] ?? '',
            'update' => $this->isEnabled($values['update'] ?? null) ? 1 : 0,
            'boot_animation' => $values['boot_animation'] ?? '',
            // Te pola sa edytowane w module newsletter i musza zostac zachowane.
            'newsletter_header' => $currentSettings['newsletter_header'] ?? '',
            'newsletter_footer' => $currentSettings['newsletter_footer'] ?? '',
            'hotpay_api' => $values['hotpay_api'] ?? '',

            'devel' => $this->isEnabled($values['devel'] ?? null) ? 1 : 0,
            'ssl' => $this->isEnabled($values['ssl'] ?? null) ? 1 : 0,
            'htaccess_cache' => $this->isEnabled($values['htaccess_cache'] ?? null) ? 1 : 0,
            'free_delivery' => $values['free_delivery'] ?? '',
            'przelewy24_sandbox' => $this->isEnabled($values['przelewy24_sandbox'] ?? null) ? 1 : 0,
            'przelewy24_merchant_id' => $values['przelewy24_merchant_id'] ?? '',
            'przelewy24_crc_key' => $values['przelewy24_crc_key'] ?? '',
            'update_key' => $values['update_key'] ?? '',
            'tpay_id' => $values['tpay_id'] ?? '',
            'tpay_sandbox' => $this->isEnabled($values['tpay_sandbox'] ?? null) ? 1 : 0,
            'tpay_security_code' => $values['tpay_security_code'] ?? '',
            'piksel' => $values['piksel'] ?? '',
            'generate_webp' => $this->isEnabled($values['generate_webp'] ?? null) ? 1 : 0,
            'lazy_loading' => $this->isEnabled($values['lazy_loading'] ?? null) ? 1 : 0,
            'orlen_paczka_map_token' => $values['orlen_paczka_map_token'] ?? '',
            'google_tag_manager_id' => $values['google_tag_manager_id'] ?? '',
            'infinitescroll' => $this->isEnabled($values['infinitescroll'] ?? null) ? 1 : 0,
            'own_gtm_js' => $values['own_gtm_js'] ?? '',
            'own_gtm_html' => $values['own_gtm_html'] ?? '',
            'api_key' => $values['api_key'] ?? '',
        ];

        $warehouseMessageZero = $values['warehouse_message_zero'] ?? [];
        if (is_array($warehouseMessageZero)) {
            foreach ($warehouseMessageZero as $key => $value) {
                $settingsToSave['warehouse_message_zero_' . $key] = $value;
            }
        }

        $warehouseMessageNonZero = $values['warehouse_message_nonzero'] ?? [];
        if (is_array($warehouseMessageNonZero)) {
            foreach ($warehouseMessageNonZero as $key => $value) {
                $settingsToSave['warehouse_message_nonzero_' . $key] = $value;
            }
        }

        // Zachowanie zgodne z dotychczasowym flow: pelna podmiana zestawu ustawien.
        $this->db->query('TRUNCATE pp_settings');
        $this->updateSettings($settingsToSave);
        \Shared\Helpers\Helpers::delete_dir('../temp/');

        \Shared\Helpers\Helpers::set_message('Ustawienia zostaly zapisane');

        return ['status' => 'ok', 'msg' => 'Ustawienia zostaly zapisane.'];
    }

    /**
     * Aktualizacja pojedynczego parametru.
     */
    public function updateSetting(string $param, $value): bool
    {
        $this->db->delete('pp_settings', ['param' => $param]);
        $this->db->insert('pp_settings', ['param' => $param, 'value' => $value]);

        return true;
    }

    /**
     * Aktualizacja wielu parametrow przez jedna sciezke.
     */
    public function updateSettings(array $settings): bool
    {
        foreach ($settings as $param => $value) {
            $this->updateSetting((string)$param, $value);
        }

        return true;
    }

    /**
     * Pobranie wszystkich ustawien.
     *
     * @return array Tablica ustawien [param => value]
     */
    public function getSettings(): array
    {
        $results = $this->db->select('pp_settings', '*', ['ORDER' => ['id' => 'ASC']]);
        $settings = [];

        if (is_array($results)) {
            foreach ($results as $row) {
                if (isset($row['param'])) {
                    $settings[$row['param']] = $row['value'] ?? '';
                }
            }
        }

        return $settings;
    }

    /**
     * Pobranie wszystkich ustawien z cache Redis.
     *
     * @param bool $skipCache Pomija cache (np. przy generowaniu htaccess)
     */
    public function allSettings(bool $skipCache = false): array
    {
        $cacheHandler = new \Shared\Cache\CacheHandler();
        $cacheKey = 'Domain\Settings\SettingsRepository::allSettings';

        if (!$skipCache) {
            $objectData = $cacheHandler->get($cacheKey);
            if ($objectData) {
                return unserialize($objectData);
            }
        }

        $results = $this->db->select('pp_settings', '*');
        $settings = [];

        if (is_array($results)) {
            foreach ($results as $row) {
                $settings[$row['param']] = $row['value'];
            }
        }

        $cacheHandler->set($cacheKey, $settings);

        return $settings;
    }

    /**
     * Pobranie pojedynczej wartosci ustawienia po nazwie parametru.
     */
    public function getSingleValue(string $param): string
    {
        $cacheHandler = new \Shared\Cache\CacheHandler();
        $cacheKey = "Domain\Settings\SettingsRepository::getSingleValue:$param";

        $objectData = $cacheHandler->get($cacheKey);
        if ($objectData) {
            return unserialize($objectData);
        }

        $value = $this->db->get('pp_settings', 'value', ['param' => $param]);
        $value = (string)($value ?? '');

        $cacheHandler->set($cacheKey, $value);

        return $value;
    }

    private function isEnabled($value): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        if (is_int($value) || is_float($value)) {
            return (int)$value === 1;
        }

        if (is_string($value)) {
            $normalized = strtolower(trim($value));
            return in_array($normalized, ['1', 'on', 'true', 'yes'], true);
        }

        return false;
    }
}
