<?php
/*
 * Software Name: Eorisis Pixels
 * Software URI: https://eorisis.com/shop/software/joomla/pixels
 * Author: Eorisis
 * Author URI: https://eorisis.com
 * Copyright: Copyright (C) 2011-2025 EORISIS. All Rights Reserved.
 * License: GNU General Public License version 2; See https://eorisis.com/gpl
 * Terms of Service: https://eorisis.com/tos
 */
namespace com_eorisis_pixels\framework\lib\core\model;
\defined('_JEXEC') or die;

use array_key_exists, json_decode;
use com_eorisis_pixels\framework\lib\core\app\config as app_config;
use com_eorisis_pixels\framework\lib\core\cms\application;
use com_eorisis_pixels\framework\lib\core\model\database;

class section
{
    private static $params = [];

	// --------------------------------------------------

	public function __construct() {}

	// --------------------------------------------------

	public static function params(string $section) : array
	{
		if (array_key_exists($section, self::$params))
		{
			return self::$params[$section];
		}

		$table = app_config::TABLE_SECTIONS;
		$dbo = application::dbo();
		$query = $dbo->getQuery(true);
		$query->select($dbo->quoteName('params'));
		$query->from($dbo->quoteName('#__'.$table));
		$query->where($dbo->quoteName('name').'='.$dbo->quote($section));
		$dbo->setQuery($query);
		$result = database::get_first_result($dbo);
		if ($result['error'])
		{
			return [];
		}

		self::$params[$section] = (array)json_decode((string)$result['record'], true);
		return self::$params[$section];
	}

	// --------------------------------------------------

	public static function id(string $view_name) : int
	{
		$table = app_config::TABLE_SECTIONS;
		$dbo = application::dbo();
		$query = $dbo->getQuery(true);
		$query->select($dbo->quoteName('id'));
		$query->from($dbo->quoteName('#__'.$table));
		$query->where($dbo->quoteName('name').'='.$dbo->quote($view_name));
		$dbo->setQuery($query);
		$result = database::get_first_result($dbo);
		return (int)$result['record'];
	}

	// --------------------------------------------------

	public static function primary_key(string $extention_name) : int
	{
		// Get the id from the database
		$table = app_config::TABLE_SECTIONS;
		$dbo = application::dbo();
		$query = $dbo->getQuery(true);
		$query->select($dbo->quoteName('id'));
		$query->from($dbo->quoteName('#__'.$table));
		$query->where($dbo->quoteName('name').'='.$dbo->quote($extention_name));
		$dbo->setQuery($query);
		$result = database::get_array($dbo);
		if ($result['error'] or !isset($result['record']['id']))
		{
			return 0;
		}

		$primary_key = (int)$result['record']['id'];
		return $primary_key > 0 ? $primary_key : 0;
	}
}
