<?php

namespace WPIS;

class SettingsManager {

    static private $table = 'wpis_settings';

    static public function init(){

        foreach(self::getDefaultSettings() as $name => $value){
            self::set($name, $value);
        }
    }

    static public function getDefaultSettings(){
        $defaultSettings = [
            'enableImportSystem' => 0,
            'enableProjectManagement' => 0,
            'enableAgentManagement' => 0,
            'enableVueShortcodes' => 0,
            'enableImportCustomPostType' => 0,
            'formEnableContactSaving' => true,
            'formEnableRecipientEmail' => true,
            'formEnableClientEmail' => true,
            'formEmailDefaultReceiver' => get_bloginfo('admin_email'),
            'formEmailDefaultSender' => get_bloginfo('admin_email'),
            'formEmailDefaultSenderName' => get_bloginfo('name')
        ];

        return $defaultSettings;
    }

    static public function get( $name, $default = null ) {

        if( file_exists(get_stylesheet_directory() . '/wpis-settings.json' ) ){
            $content = file_get_contents(get_stylesheet_directory() . '/wpis-settings.json');
            $settings = json_decode($content);
            if( isset( $settings->{$name} ) ){
                return $settings->{$name};
            }
        }

        $wpdb = $GLOBALS['wpdb'];
        $table = $wpdb->prefix . self::$table;
        $result = $wpdb->get_row("SELECT name, value FROM $table WHERE name = '$name'");

        return !is_null($result) ? $result->value : $default;
    }

    static public function getAll() {
        $wpdb = $GLOBALS['wpdb'];
        $table = $wpdb->prefix . self::$table;
        $result = $wpdb->get_results("SELECT name, value FROM $table");
        $settings = [];

        foreach( $result as $row ){
            $settings[$row->name] = $row->value;
        }

        return $settings;
    }

    static public function getDefault() {
        return self::getDefaultSettings();
    }

    static public function set($name, $value) {

        $wpdb = $GLOBALS['wpdb'];
        $table = $wpdb->prefix . self::$table;

        $results = $wpdb->get_results("SELECT name, value FROM $table WHERE name = '$name'");

        if( ! isset($results[0]) ){
            $wpdb->insert($table, ['name' => $name, 'value' => $value]);
        }
        else {
            $wpdb->update($table, ['value' => $value ], ['name' => $name] );
        }
    }

}