<?php

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

namespace ConvertForms;

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

/**
 *  This is the main Convert Forms API helper class meant to be used ONLY by 3rd party developers and advanced users. 
 *  Do not ever use this class to implement and rely any core feture.
 */
class Api
{
    /**
     * Delete a submission from the database
     *
     * @param  integer $id  The submission's primary key
     *
     * @return bool True on success
     */
    public static function removeSubmission($submission_id)
    {
        if (!$submission_id)
        {
            return;
        }

		\JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_convertforms/tables');
        $table = \JTable::getInstance('Conversion', 'ConvertFormsTable');
        return $table->delete($submission_id);
    }

    /**
     * Delete all form submissions from the database
     *
     * @param  integer $form_id     The form's primary key
     *
     * @return bool
     */
    public static function removeFormSubmissions($form_id)
    {
        if (!$form_id)
        {
            return;
        }

        $db = \JFactory::getDbo();

        $query = $db->getQuery(true)
            ->delete($db->quoteName('#__convertforms_conversions'))
            ->where($db->quoteName('form_id') . ' = ' . $form_id);
        
        $db->setQuery($query);
        
        return $db->execute();
    }

    /**
     * Return the total number of form total submissions
     *
     * @param   integer $form_id    The form's ID
     *
     * @return  integer
     */
    public static function getFormSubmissionsTotal($form_id)
    {
        if (!$form_id)
        {
            return;
        }

        $db = \JFactory::getDbo();

        $query = $db->getQuery(true)
            ->select('count(id)')
            ->from($db->quoteName('#__convertforms_conversions'))
            ->where($db->quoteName('form_id') . ' = ' . $form_id);
    
        $db->setQuery($query);
        
        return (int) $db->loadResult();
    }
}