<?php

namespace Digitanie\Component\Leaflet\Site\Model;

defined('_JEXEC') or die;

use Joomla\CMS\MVC\Model\ItemModel;
use Joomla\CMS\Factory;

/**
 * Leaflet Model
 */
class LeafletModel extends ItemModel {
	/**
	 * @var string message
	 */
	protected $message;

	/**
     * Returns a message for display
     * @param integer $pk Primary key of the "message item", currently unused
     * @return object Message object
     */
    public function getItem($pk= null): object {

        // Utiliser la méthode getState pour obtenir l'ID de l'élément si $pk n'est pas fourni
        $pk = !empty($pk) ? $pk : $this->getState($this->getName() . '.id');

        // Vérifiez si l'ID est null
        if ($pk === null) {
            return false;
        }


        // Charger l'élément depuis la base de données
        $table = $this->getTable();

        // Tenter de charger l'élément avec l'ID fourni
        if (!$table->load($pk)) {
            $this->setError($table->getError());
            return false;
        }

        // Retourne l'objet de l'élément chargé
        return $table;
    }

	//------------------- ID CATEGORIES
    public function getCategory()
	{
		try 
		{
			$db    = Factory::getDbo();
			$query = $db
				->getQuery(true)
				->select('id')
				->from($db->quoteName('q8x14_categories'))
				->where($db->quoteName('alias') . " = " . $db->quote('experiences'), 'OR')
				->where($db->quoteName('alias') . " = " . $db->quote('appel-a-projet-dt'), 'OR')
				->where($db->quoteName('alias') . " = " . $db->quote('savoir-faire-siae'));

			$db->setQuery($query);
			$results = $db->loadColumn();
			
		}
		catch (Exception $e)
		{
			$msg = $e->getMessage();
			Factory::getApplication()->enqueueMessage($msg, 'error'); 
			$results = null;
		}

		return $results; 
	}
	//--------------------- EOF ID CATEGORIES

	//--------------------- VALEURS 
	public function getTerritoires()
	{
		try 
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true);

			$query->select($db->quoteName(array('id', 'title', 'name', 'fieldparams')));
			$query->from($db->quoteName('q8x14_fields'));
			$query->where($db->quoteName('name') . " = " . $db->quote('departement'));
			$db->setQuery($query);
			$results = $db->loadAssoc();
		}
		catch (Exception $e)
		{
			$msg = $e->getMessage();
			Factory::getApplication()->enqueueMessage($msg, 'error'); 
			$results = null;
		}

		return $results; 
	}

	public function getCategoriesExperience()
	{
		try 
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true);

			$query->select($db->quoteName(array('id', 'title', 'name', 'fieldparams')));
			$query->from($db->quoteName('q8x14_fields'));
			/*NOM SUJET A EVOLUTION THOMAS*/
			$query->where($db->quoteName('name') . " = " . $db->quote('categorie'));
			$db->setQuery($query);
			$results = $db->loadAssoc();

		}
		catch (Exception $e)
		{
			$msg = $e->getMessage();
			Factory::getApplication()->enqueueMessage($msg, 'error'); 
			$results = null;
		}

		return $results; 
	}

	public function getActivite()
	{
		try 
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true);

			$query->select($db->quoteName(array('id', 'title', 'name', 'fieldparams')));
			$query->from($db->quoteName('q8x14_fields'));
			$query->where($db->quoteName('name') . " = " . $db->quote('activite'));
			$db->setQuery($query);
			$results = $db->loadAssoc();

		}
		catch (Exception $e)
		{
			$msg = $e->getMessage();
			Factory::getApplication()->enqueueMessage($msg, 'error'); 
			$results = null;
		}

		return $results; 
	}
	//------------------------- EOF VALEURS

	public function getMarkers($catId)
	{
		try 
		{
			$db    = Factory::getDbo();

			$query = $db->getQuery(true);
			$groupId = 4;

			//On récupère les noms et id des custom fields
			$query->select($db->quoteName(array('f.id', 'f.name')));
			$query->from($db->quoteName('q8x14_fields_groups', 'g'));
			$query->join('INNER', $db->quoteName('q8x14_fields', 'f') . ' ON ' . $db->quoteName('g.id') . ' = ' . $db->quoteName('f.group_id'));
			$query->where($db->quoteName('g.id') . ' = ' . $groupId);
			//test offset pour voir si la premiere entrée est problématique
			//$query->setLimit(27, 1);
			$db->setQuery($query);
			$fields = $db->loadObjectList();

			$fieldsSelect = array('c.id',
			'c.title',
			'c.alias',
			'c.state',
			'c.introtext');
			foreach($fields as $field) {
				array_push($fieldsSelect, 'GROUP_CONCAT(DISTINCT IF(field_id = ' . $field->id . ', value, NULL) SEPARATOR ",") AS ' . $field->name);
			}
			$stateValue = 1;
			$query->clear();
			$query->select($fieldsSelect);
			$query->from($db->quoteName('q8x14_content', 'c'));
			$query->join('INNER', $db->quoteName('q8x14_fields_values', 'f') . ' ON ' . $db->quoteName('c.id') . ' = ' . $db->quoteName('f.item_id'));
			$query->where($db->quoteName('c.catid') . ' = ' . $catId); // projects
			$query->where($db->quoteName('c.state') . " = " . $stateValue);
			$query->group($db->quoteName('c.id'));

			$db->setQuery($query);
			$results = $db->loadObjectList(); 

			// NEED TO REVIEW GROUP CONCAT TO SEE IF WE CAN GET ARRAY DIRECTLY
			foreach($results as $content) {
				$content->departement = explode(',', $content->departement);
				$content->categorie = explode(',', $content->categorie);
				$content->activite = explode(',', $content->activite);
				
				
			}
		}
		catch (Exception $e)
		{
			$msg = $e->getMessage();
			Factory::getApplication()->enqueueMessage($msg, 'error'); 
			$results = null;
		}

		return $results; 
	}
}