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

class App_config_model extends CI_Model
{
	public function __construct()
	{
		parent::__construct();
		$this->crear_tabla_si_no_existe();
	}

	public function obtener()
	{
		$row = $this->db->where('id', 1)->limit(1)->get('app_config')->row_array();
		if (!$row) {
			$this->db->insert('app_config', array(
				'id' => 1,
				'app_name' => 'BellaIdea',
				'logo_path' => NULL
			));
			$row = $this->db->where('id', 1)->limit(1)->get('app_config')->row_array();
		}

		return array(
			'app_name' => !empty($row['app_name']) ? $row['app_name'] : 'BellaIdea',
			'logo_path' => !empty($row['logo_path']) ? $row['logo_path'] : ''
		);
	}

	public function guardar($app_name, $logo_path = NULL)
	{
		$actual = $this->obtener();
		$data = array(
			'app_name' => $app_name
		);

		if ($logo_path !== NULL) {
			$data['logo_path'] = $logo_path;
		} else {
			$data['logo_path'] = $actual['logo_path'];
		}

		return $this->db->where('id', 1)->update('app_config', $data);
	}

	private function crear_tabla_si_no_existe()
	{
		$sql = "CREATE TABLE IF NOT EXISTS app_config (
			id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
			app_name VARCHAR(100) NOT NULL,
			logo_path VARCHAR(255) NULL,
			actualizado_en TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
		) ENGINE=InnoDB DEFAULT CHARSET=utf8";

		$this->db->query($sql);
	}
}
