<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_Fulfillment_Settings {

    
    private static $cache = null;

    private static function table() {
        global $wpdb;
        return $wpdb->prefix . 'aieo_dmm_fulfillment_settings';
    }

    
    public static function all() {
        if (self::$cache !== null) { return self::$cache; }

        global $wpdb;
        $rows = $wpdb->get_results('SELECT setting_key, setting_value FROM ' . self::table(), ARRAY_A);
        $out  = array();
        foreach ((array) $rows as $row) {
            $key = (string) $row['setting_key'];
            $val = (string) $row['setting_value'];
            $decoded = json_decode($val, true);
            $out[$key] = (json_last_error() === JSON_ERROR_NONE) ? $decoded : $val;
        }
        self::$cache = $out;
        return $out;
    }

    
    public static function get($key, $default = null) {
        $all = self::all();
        if (strpos($key, '.') === false) {
            return array_key_exists($key, $all) ? $all[$key] : $default;
        }
        list($group, $sub) = explode('.', $key, 2);
        if (!isset($all[$group]) || !is_array($all[$group])) { return $default; }
        return array_key_exists($sub, $all[$group]) ? $all[$group][$sub] : $default;
    }

    
    public static function set($key, $value) {
        global $wpdb;
        $key  = sanitize_key($key);
        if ($key === '') { return false; }
        $val  = is_scalar($value) ? (string) $value : (string) wp_json_encode($value);
        $rows = $wpdb->replace(self::table(), array('setting_key' => $key, 'setting_value' => $val), array('%s', '%s'));
        self::$cache = null;
        return $rows !== false;
    }

    
    public static function set_many(array $items) {
        $n = 0;
        foreach ($items as $k => $v) {
            if (self::set($k, $v)) { $n++; }
        }
        return $n;
    }

    
    public static function signing_secret() {
        $secret = self::get('general.signing_secret', '');
        if (is_string($secret) && strlen($secret) >= 64) { return $secret; }

        $new_secret = bin2hex(random_bytes(32));
        $general = self::get('general', array());
        if (!is_array($general)) { $general = array(); }
        $general['signing_secret'] = $new_secret;
        self::set('general', $general);
        return $new_secret;
    }

    
    public static function flush_cache() {
        self::$cache = null;
    }
}
