<?php

namespace Garradin\Plugin\Facturation;

use Garradin\DB;
use Garradin\UserException;
use Garradin\Utils;
use Garradin\Plugin\Facturation\Facture;

class Config
{
	protected $fields_types = null;
	protected $config = null;
	protected $modified = [];

	static protected $_instance = null;

	/**
	 * Singleton simple
	 * @return Config
	 */
	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new Config;
	}

	static public function deleteInstance()
	{
		self::$_instance = null;
	}

	/**
	 * Empêche de cloner l'objet
	 * @return void
	 */
	private function __clone()
	{
	}

	public function __construct()
	{
		// Définition des types de données stockées
		$string = '';
		$bool = false;
		// $int = 0;
		// $float = 0.0;
		// $array = [];
		// $object = new \stdClass;

		$this->fields_types = [
			'siret_asso'			=>  $string,
			'validate_cp'			=>  $bool,
			'unique_client_name'	=>  $bool,
			'footer'				=>  $string
		];

		$db = DB::getInstance();

		$this->config = $db->getAssoc('SELECT cle, valeur FROM plugin_facturation_config ORDER BY cle;');

		foreach ($this->config as $key=>&$value)
		{
			if (!array_key_exists($key, $this->fields_types))
			{
				// Ancienne clé de config qui n'est plus utilisée
				continue;
			}

			if (is_array($this->fields_types[$key]))
			{
				$value = explode(',', $value);
			}
			else
			{
				settype($value, gettype($this->fields_types[$key]));
			}
		}
	}

	public function save()
	{
		if (empty($this->modified))
			return true;

		$values = [];
		$db = DB::getInstance();
		// $db->begin();

		foreach ($this->modified as $key=>$modified)
		{
			$value = $this->config[$key];

			if (is_array($value))
			{
				$value = implode(',', $value);
	    }
	    elseif (is_object($value))
	    {
		    $value = (string) $value;
	    }

	    $db->exec('INSERT OR REPLACE INTO plugin_facturation_config (cle, valeur) VALUES (\''.$key.'\', \''.$value.'\');');
		}

	// $db->commit();

	$this->modified = [];

	return true;
	}

	public function set($key, $value)
	{
		if (!array_key_exists($key, $this->fields_types))
		{
			throw new \OutOfBoundsException('Ce champ est inconnu.');
	}

	if (is_array($this->fields_types[$key]))
	{
		$value = !empty($value) ? (array) $value : [];
	}
	elseif (is_int($this->fields_types[$key]))
	{
		$value = (int) $value;
	}
	elseif (is_float($this->fields_types[$key]))
	{
		$value = (float) $value;
	}
	elseif (is_bool($this->fields_types[$key]))
	{
		$value = (bool) $value;
	}
	elseif (is_string($this->fields_types[$key]))
	{
		$value = (string) $value;
	}

	// switch ($key)
	// {
	//     case 'siret_asso':
	//     {
	//         if (!trim($value))
	//         {
	//             throw new UserException('Le nom de l\'association ne peut rester vide.');
	//         }
	//         break;
	// 	}
	// 	case 'footer':
	// 		break;
	//     default:
	//         break;
	// }

	if (!isset($this->config[$key]) || $value !== $this->config[$key])
	{
		$this->config[$key] = $value;
		$this->modified[$key] = true;
	}

	return true;
	}

	public function get($key)
	{
		if (!array_key_exists($key, $this->fields_types))
		{
			throw new \OutOfBoundsException('Ce champ est inconnu.');
	}

	if (!array_key_exists($key, $this->config))
	{
		return null;
	}

	return $this->config[$key];
	}

    public function getFieldsTypes()
    {
	    return $this->fields_types;
    }

    public function getConfig()
    {
	    return $this->config;
    }
}
