<?php
     
class PhonalisaConfig
{	
	public static function updateSettingsCacheFile() {
		
            $model = new Sysconfig();
            $allItems = $model->getConfigItemsArray();
            $defaultConfigs = array();
            foreach ($allItems as $section ) {
                foreach ($section as $key => $values) {

                    $defaultConfigs[$key] = $values['defaultValue'];
                }

            }
		
            $allSysConfigs = array();
            $models = array();
            $domain = getPhonalisaDomain();
            $filePath = Yii::app()->runtimePath. "/".$domain."-SystemGlobalsArray.ini";
            $limit = 100;
            $offset = 0;

            do {
                $models = Sysconfig::model()->findAll('', array('limit'=>$limit, 'offset'=>$offset));
                $allSysConfigs = array_merge($allSysConfigs, $models);
                $offset = $offset+$limit;

            } while (count($models) == $limit);

            foreach ($allSysConfigs as $settings) {
                            $defaultConfigs[$settings->key]= $settings->value;	
            }

            PhonalisaIniWriter::writeIniFile($defaultConfigs, $filePath);
		
	}

	public static function cfg($key) {
				
		$domain = getPhonalisaDomain();
		$filePath = Yii::app()->runtimePath. "/".$domain."-SystemGlobalsArray.ini";

                
		if (file_exists($filePath)) {
                        $configContent = parse_ini_file($filePath);
			//$configContent = include ($filePath);
			return isset($configContent[$key]) ? $configContent[$key] : null;

		} else {
			$model = Sysconfig::model()->findByAttributes(array('key'=>$key));
			if (!$model){
				$model = new Sysconfig();
				return $model->getDefaultValueForKey($key);
			} else {
				PhonalisaConfig::updateSettingsCacheFile();
                                $configContent = parse_ini_file($filePath);
				//$configContent = include ($filePath);
				return $configContent[$key];
            }
	
		}
	
        return $model->value;
	}
	
	public static function setCfg($key, $value){
	    $model = Sysconfig::model()->findByAttributes(array('key'=>$key));
	    
        if (!$model)
            $model = new Sysconfig();
	
    	$model->key = $key;
    	$model->value = $value;
    	
    	if($model->save()){
        	PhonalisaConfig::updateSettingsCacheFile();
        	return true;
    	}
    	
    	return false;
	}
}