<?php

/**
 * @package         Smile Pack
 * @version         1.2.3 Pro
 * 
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2024 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

defined('_JEXEC') or die('Restricted access');

class SPMapContactMarkers extends SPMapMarkersItem
{
    protected $context = 'com_contact.contact';
    
    public function getMarkers()
    {
        $this->applyCategory();

        $this->applyStatus();

        return $this->getDBResults();
    }

    protected function setJoin()
    {
        $this->query->select('a.catid, a.language');
        $this->query->join('LEFT', $this->db->quoteName('#__contact_details', 'a') . ' ON a.id = fv.item_id');
    }
    
    protected function getFieldID()
    {
        return $this->params->get('acf_contact_map');
    }

    private function applyCategory()
    {
        $categoriesEnabled = $this->params->get('filters_contact_category_enabled', '0');
        if ($categoriesEnabled !== '1')
        {
            return;
        }

        if (!$categories = $this->params->get('filters_contact_category_value', []))
        {
            return;
        }

        $inc_children = $this->params->get('filters_contact_category_inc_children', '0');

        if (in_array($inc_children, ['1', '2']))
        {
            $categories = is_string($categories) ? array_map('trim', explode(',', $categories)) : $categories;
            
            $children_categories = $this->getCategoriesChildIds($categories, 'com_contact');

            // Also include children categories
            if ($inc_children === '1')
            {
                $categories = array_unique(array_filter(array_merge($categories, $children_categories)));
            }
            // Use only children categories
            else
            {
                $categories = $children_categories;
            }

            $categories = implode(',', $categories);
        }

        if (!$categories)
        {
            return;
        }

        $this->query->where($this->db->quoteName('a.catid') . ' IN (' . (is_string($categories) ? $categories : implode(',', $categories)) . ')');
    }

    private function applyStatus()
    {
        $status = $this->params->get('filters_contact_status_value', ['1']);

        $this->query->where($this->db->quoteName('a.published') . ' IN (' . (is_string($status) ? $status : implode(',', $status)) . ')');
    }
}