<?php

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Table\Table;
use Joomla\Component\Finder\Administrator\Indexer\Adapter;
use Joomla\Component\Finder\Administrator\Indexer\Helper;
use Joomla\Component\Finder\Administrator\Indexer\Indexer;
use Joomla\Component\Finder\Administrator\Indexer\Result;
use Joomla\Database\DatabaseQuery;
use Joomla\Registry\Registry;

\defined('_JEXEC') or die;

require_once(JPATH_SITE.'/components/com_jshopping/bootstrap.php'); 

class PlgFinderJoomshopping extends Adapter {
    
    public function __construct(&$subject, $config)
    {
        // Call the parent constructor.
        parent::__construct($subject, $config);

        // Get the type id.
        $this->type_id = $this->getTypeId();        

        // Add the content type if it doesn't exist and is set.
        if (empty($this->type_id) && !empty($this->type_title)) {
            $this->type_id = Helper::addContentType($this->type_title, $this->mime);
        }

        // Check for a layout override.
        if ($this->params->get('layout')) {
            $this->layout = $this->params->get('layout');
        }

        // Get the indexer object
        $this->indexer = new Indexer($this->db);
    }

    /**
     * The plugin identifier.
     *
     * @var    string
     * @since  3.1
     */
    protected $context = 'Shop';

    /**
     * The extension name.
     *
     * @var    string
     * @since  3.1
     */
    protected $extension = 'com_jshopping';

    /**
     * The sublayout to use when rendering the results.
     *
     * @var    string
     * @since  3.1
     */
    protected $layout = 'shop';

    /**
     * The type of content that the adapter indexes.
     *
     * @var    string
     * @since  3.1
     */
    protected $type_title = 'Shop';

    /**
     * The table name.
     *
     * @var    string
     * @since  3.1
     */
    protected $table = '#__jshopping_products';

    /**
     * Load the language file on instantiation.
     *
     * @var    boolean
     * @since  3.1
     */
    protected $autoloadLanguage = true;

    /**
     * The field the published state is stored in.
     *
     * @var    string
     * @since  3.1
     */
    protected $state_field = 'product_publish';

    /**
     * Method to remove the link information for items that have been deleted.
     *
     * @param   string  $context  The context of the action being performed.
     * @param   Table   $table    A Table object containing the record to be deleted
     *
     * @return  void
     *
     * @since   3.1
     * @throws  Exception on database error.
     */
    public function onFinderAfterDelete($context, $table): void
    {        
        if ($context === 'com_finder.index') {
            $id = $table->link_id;
        } else {
            return;
        }

        // Remove the items.
        $this->remove($id);
    }

    /**
     * Method to determine if the access level of an item changed.
     *
     * @param   string   $context  The context of the content passed to the plugin.
     * @param   Table    $row      A Table object
     * @param   boolean  $isNew    If the content has just been created
     *
     * @return  void
     *
     * @since   3.1
     * @throws  Exception on database error.
     */
    public function onFinderAfterSave($context, $row, $isNew): void
    {        
    }

    /**
     * Method to reindex the link information for an item that has been saved.
     * This event is fired before the data is actually saved so we are going
     * to queue the item to be indexed later.
     *
     * @param   string   $context  The context of the content passed to the plugin.
     * @param   Table    $row      A Table object
     * @param   boolean  $isNew    If the content is just about to be created
     *
     * @return  boolean  True on success.
     *
     * @since   3.1
     * @throws  Exception on database error.
     */
    public function onFinderBeforeSave($context, $row, $isNew)
    {
        return true;
    }

    public function onFinderGarbageCollection() {
        return 0;
    }

    /**
     * Method to update the link information for items that have been changed
     * from outside the edit screen. This is fired when the item is published,
     * unpublished, archived, or unarchived from the list view.
     *
     * @param   string   $context  The context for the content passed to the plugin.
     * @param   array    $pks      A list of primary key ids of the content that has changed state.
     * @param   integer  $value    The value of the state that the content has been changed to.
     *
     * @return  void
     *
     * @since   3.1
     */
    public function onFinderChangeState($context, $pks, $value)
    {

    }

    /**
     * Method to index an item. The item must be a Result object.
     *
     * @param   Result  $item  The item to index as a Result object.
     *
     * @return  void
     *
     * @since   3.1
     * @throws  Exception on database error.
     */
    protected function index(Result $item)
    {
        // Check if the extension is enabled
        if (ComponentHelper::isEnabled($this->extension) === false) {
            return;
        }

        $item->setLanguage();

        // Initialize the item parameters.
        $registry = new Registry($item->params);
        $item->params = clone ComponentHelper::getParams('com_jshopping', true);
        $item->params->merge($registry);

        $item->metadata = new Registry($item->metadata);

        // Create a URL as identifier to recognise items again.
		$url = $this->getUrl($item->id, $this->extension, $this->layout);
        $item->url = $url."&lang=".$item->language;

        // Build the necessary route and path information.
        $mid = \JSHelper::getDefaultItemid($url);
        $item->route = $url."&Itemid=".$mid;

        // Get the menu title if it exists.
        $title = $this->getItemMenuTitle($item->url);

        // Adjust the title if necessary.
        if (!empty($title) && $this->params->get('use_menu_title', true)) {
            $item->title = $title;
        }

        // Add the meta author.
        //$item->metaauthor = $item->metadata->get('author');

        // Handle the link to the metadata.
        $item->addInstruction(Indexer::META_CONTEXT, 'link');
        $item->addInstruction(Indexer::META_CONTEXT, 'metakey');
        $item->addInstruction(Indexer::META_CONTEXT, 'metadesc');
        //$item->addInstruction(Indexer::META_CONTEXT, 'metaauthor');
        //$item->addInstruction(Indexer::META_CONTEXT, 'author');
        //$item->addInstruction(Indexer::META_CONTEXT, 'created_by_alias');

        // Add the type taxonomy data.
        $item->addTaxonomy('Type', 'Shop');

        // Add the language taxonomy data.
        $item->addTaxonomy('Language', $item->language);

        // Get content extras.
        Helper::getContentExtras($item);

        // Index the item.
        $this->indexer->index($item);
    }
    
    protected function setup()
    {
        return true;
    }

    /**
     * Method to get the SQL query used to retrieve the list of content items.
     *
     * @param   mixed  $query  A DatabaseQuery object or null.
     *
     * @return  DatabaseQuery  A database object.
     *
     * @since   3.1
     */
    protected function getListQuery($query = null)
    {
        $db = $this->db;
        $lang = \JFactory::getLanguage()->getTag();
		$curlang = $lang;
        
		$_lang = \JSFactory::getModel("languages");
        $languages = $_lang->getAllLanguages(1);
		
		$query = $query instanceof DatabaseQuery ? $query : $db->getQuery(true);
		
		$query
            ->select('a.product_id as id, a.`name_'.$lang.'` as title, a.`alias_'.$lang.'` as alias, a.`description_'.$lang.'` as  summary')
            ->select('a.product_date_added AS start_date, 0 AS created_by')
            ->select('a.`meta_keyword_'.$lang.'` as metakey, `meta_description_'.$lang.'` as metadesc, a.`meta_title_'.$lang.'` as metadata, "'.$lang.'" as language')
            ->select('a.date_modify AS modified, 0 AS modified_by')
            ->select('a.product_publish AS state, a.access')
			->from('#__jshopping_products AS a')
			->where($db->quoteName('parent_id') . ' = 0');
		
		foreach($languages as $v) {
			$lang = $v->language;
			if ($curlang == $lang) {
				continue;
			}
			$query2 = $db->getQuery(true)
				->select('a.product_id as id, a.`name_'.$lang.'` as title, a.`alias_'.$lang.'` as alias, a.`description_'.$lang.'` as  summary')
				->select('a.product_date_added AS start_date, 0 AS created_by')
				->select('a.`meta_keyword_'.$lang.'` as metakey, `meta_description_'.$lang.'` as metadesc, a.`meta_title_'.$lang.'` as metadata, "'.$lang.'" as language')
				->select('a.date_modify AS modified, 0 AS modified_by')
				->select('a.product_publish AS state, a.access')
				->from('#__jshopping_products AS a')
				->where($db->quoteName('parent_id') . ' = 0');
				
			$query->union($query2);
		}

        return $query;
    }
	
	protected function getContentCount()
    {
        $query = $this->getListQuery();
        if (empty($query)) {
            return 0;
        }
        $this->db->setQuery($query);
		$this->db->execute();
        return (int)$this->db->getNumRows();
    }

    /**
     * Method to get a SQL query to load the published and access states for the given tag.
     *
     * @return  DatabaseQuery  A database object.
     *
     * @since   3.1
     */
    protected function getStateQuery()
    {
        $query = $this->db->getQuery(true);
        $query->select('a.product_id as id')
            ->select($this->db->quoteName('a.' . $this->state_field, 'state') . ', ' . $this->db->quoteName('a.access'))
            ->select('NULL AS cat_state, NULL AS cat_access')
            ->from($this->db->quoteName($this->table, 'a'));

        return $query;
    }

    /**
     * Method to get the query clause for getting items to update by time.
     *
     * @param   string  $time  The modified timestamp.
     *
     * @return  DatabaseQuery  A database object.
     *
     * @since   3.1
     */
    protected function getUpdateQueryByTime($time)
    {
        // Build an SQL query based on the modified time.
        $query = $this->db->getQuery(true)
            ->where('a.date_modify >= ' . $this->db->quote($time));

        return $query;
    }

    protected function getUrl($id, $extension, $view) {
        $category_id = $this->getFirstCategory($id);        
        return 'index.php?option=' . $extension . '&controller=product&task=view&category_id='.$category_id.'&product_id='.$id;
    }

    protected function getFirstCategory($prod_id) {
        $query = "SELECT pr_cat.category_id FROM `#__jshopping_products_to_categories` AS pr_cat
                    LEFT JOIN `#__jshopping_categories` AS cat ON pr_cat.category_id = cat.category_id
                    WHERE pr_cat.product_id=".(int)$prod_id." AND cat.category_publish=1";
        $this->db->setQuery($query);
        return (int)$this->db->loadResult();
    }
}
