<?php
/**
 * Firewall Config Model Class
 *
 * @package VMPFence
 * @since 2.0.0
 */
if (!defined('ABSPATH')) exit;

class VMPFence_Firewall_Config {
    
    private $cache = array();
    
    public function is_feature_enabled($feature) {
        $value = $this->get_setting($feature);
        return !empty($value);
    }
    
    public function get_setting($key) {
        if (isset($this->cache[$key])) {
            return $this->cache[$key];
        }
        
        global $wpdb;
        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_CONFIG);
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT val FROM $table_name WHERE name = %s",
            $key
        ));
        
        $value = $row ? $row->val : '';
        $this->cache[$key] = $value;
        return $value;
    }
    
    public function set_setting($key, $value) {
        global $wpdb;
        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_CONFIG);
        
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT val FROM $table_name WHERE name = %s",
            $key
        ));
        
        if ($existing !== null) {
            $wpdb->update(
                $table_name,
                array('val' => $value),
                array('name' => $key)
            );
        } else {
            $wpdb->insert(
                $table_name,
                array('name' => $key, 'val' => $value)
            );
        }
        
        $this->cache[$key] = $value;
    }
    
    public function get_all_settings() {
        global $wpdb;
        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_CONFIG);
        $rows = $wpdb->get_results("SELECT name, val FROM $table_name");
        
        $settings = array();
        foreach ($rows as $row) {
            $settings[$row->name] = $row->val;
        }
        return $settings;
    }
}
