<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Setting_model — global key/value settings store.
 */
#[\AllowDynamicProperties]
class Setting_model extends MY_Model {

	protected $table = 'settings';

	/** Return all settings as a flat key => value map. */
	public function all()
	{
		$rows = $this->db->get($this->table)->result_array();
		$map  = array();
		foreach ($rows as $r)
		{
			$map[$r['key']] = $r['value'];
		}
		return $map;
	}

	/** Return settings grouped by their `group` column, for the admin form. */
	public function grouped()
	{
		$rows = $this->db->order_by('group', 'ASC')->order_by('id', 'ASC')
			->get($this->table)->result_array();
		$out = array();
		foreach ($rows as $r)
		{
			$out[$r['group']][] = $r;
		}
		return $out;
	}

	/** Fetch a single value. */
	public function value($key, $default = '')
	{
		$row = $this->get_by(array('key' => $key));
		return ($row && $row['value'] !== '') ? $row['value'] : $default;
	}

	/** Persist a batch of key => value pairs. */
	public function save_many($pairs)
	{
		foreach ($pairs as $key => $value)
		{
			$this->db->where('key', $key)
				->update($this->table, array('value' => $value));
		}
		return TRUE;
	}
}
