<?php
/**
 * CAI CP v.0.9
 * Core class
 * 
 * build date  2017-06-17
 *
 * @package   : System
 * @author    : Alexander I. Chebykin <alex.chebykin@gmail.com>
 * @copyright : Copyright (c) 2017 Alexander I. Chebykin
 * @version   : 0.9
 * @license   : MIT
 * @link      : https://github.com/CAI79/CAI-CP
 ******************************************************************/

namespace CAI\CAICP;

class Settings
{
    protected $user_settings = array();
    protected $cp_root = '';
    
    /**
     * Constructor
     * 
     * @param string $root_dir Control panel's root directory
     */
    function __construct($root_dir)
    {
        $this->cp_root = filter_input(INPUT_SERVER, 'DOCUMENT_ROOT') . $root_dir;
        $this->load();
    }

    /**
     * Read settings from disk
     */
    private function load()
    {
        $this->user_settings  = json_decode(
                file_get_contents($this->cp_root . '/system/json/settings.json'),
                true);
    }

    /**
     * Save settings to disk
     * 
     * @return false|written bytes count
     */
    public function save()
    {
        return file_put_contents($this->cp_root . '/system/json/settings.json',
                        html_entity_decode(json_encode($this->user_settings)));
    }
    
    /**
     * Return array with settings
     * 
     * @return array
     */
    public function get()
    {
        return $this->user_settings;
    }
    
    /**
     * Return string with settings in JSON format
     * 
     * @return string
     */
    public function get_json()
    {
        return html_entity_decode(json_encode($this->get()));
    }
    
    /**
     * Return option value
     * 
     * @param string $option_name Option name
     * 
     * @return variant|boolean
     */
    public function get_value($option_name)
    {
        if (trim($option_name) !== '') {
            return $this::user_settings[$option_name];
        } else {
            return false;
        }
    }
    
    /**
     * Set all settings
     * 
     * @param array $values Array with settings
     */
    public function set($values)
    {
        $this->user_settings = $values;
    }

    /**
     * Set all settings
     * 
     * @param string $json Settings in JSON format
     */
    public function set_json($json)
    {
        $this->set(json_decode($json, true));
    }
    
    /**
     * Set option value
     * 
     * @param string  $option_name Option name
     * @param variant $value       New value
     */
    public function set_value($option_name, $value)
    {
        if (trim($option_name) !== '') {
            $this->user_settings[$option_name] = $value;
        }
    }
}
