<?php
/**
 * @package     Sven.Bluege
 * @subpackage  com_eventgallery
 *
 * @copyright   Copyright (C) 2005 - 2019 Sven Bluege All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.modellist' );

class eventgalleryModelEventgallery  extends \Joomla\CMS\MVC\Model\ListModel
{

    public function getFolderCount() {

        return $this->countEntries('#__eventgallery_folder');

    }

    public function getOrderCount() {

        return $this->countEntries('#__eventgallery_order');

    }

    public function getCartCount() {

        return $this->countEntries('#__eventgallery_cart');

    }

    public function getDownloadlogCount() {

        return $this->countEntries('#__eventgallery_downloadlog');

    }


    public function getFileCount() {

        return $this->countEntries('#__eventgallery_file file, #__eventgallery_folder folder', 'file.folder=folder.folder');

    }

    public function getFileTotalCount() {
        return $this->countEntries('#__eventgallery_file');
    }

    protected function countEntries($table, $where = null) {
        $db = $this->getDbo();
        $query = $db->getQuery(true);

        $query->select('count(1)');
        $query->from($table);
        if (isset($where)) {
            $query->where($where);
        }
        $db->setQuery($query);

        return $db->loadResult();
    }

    public function getUpdateSiteId() {
        $site = $this->getUpdateSite();
        if (empty($site)) return null;

        return $site->update_site_id;
    }

    private function getUpdateSite() {
        $db = $this->getDbo();
        $query = $db->getQuery(true);

        $extensionId = (int)\Joomla\CMS\Component\ComponentHelper::getComponent('com_eventgallery')->id;

        $query->select('s.*')
            ->from('#__update_sites s, #__update_sites_extensions se, #__extensions e')
            ->where('s.update_site_id = se.update_site_id and e.package_id=se.extension_id and e.extension_id = ' . $db->quote($extensionId));
        $db->setQuery($query);
        $result = $db->loadObject();
        return $result;
    }

    private function getDownloadId() {
        $site = $this->getUpdateSite();
        if (empty($site)) return '';

        return $site->extra_query;
    }

    public function needsDownloadId() {
        if (!EVENTGALLERY_EXTENDED) return false;

        if (strlen($this->getDownloadId())>12) {
            return false;
        }

        return true;
    }
}
