<?php
/**
 * Front-end Actions
 *
 * @package     EDD
 * @subpackage  Functions
 * @copyright   Copyright (c) 2015, Pippin Williamson
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       1.0.8.1
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Hooks EDD actions, when present in the $_GET superglobal. Every edd_action
 * present in $_GET is called using WordPress's do_action function. These
 * functions are called on init.
 *
 * @since 1.0
 * @return void
*/
add_action('init', 'irpp_do_action');
add_action('wp_ajax_do_action', 'irpp_do_action');
function irpp_do_action() {
    global $irpp;

	if ($irpp->Utils->qs('irpp_action')) {
        $args=array_merge($_GET, $_POST, $_COOKIE, $_SERVER);
        $name='irpp_'.$irpp->Utils->qs('irpp_action');
        if(has_action($name)) {
            $irpp->Log->debug('EXECUTING ACTION=%s', $name);
            do_action($name, $args);
        } elseif(function_exists($name)) {
            $irpp->Log->debug('EXECUTING FUNCTION=%s DATA=%s', $name, $args);
            call_user_func($name, $args);
        } elseif(strpos($irpp->Utils->qs('irpp_action'), '_')!==FALSE) {
            $pos=strpos($irpp->Utils->qs('irpp_action'), '_');
            $what=substr($irpp->Utils->qs('irpp_action'), 0, $pos);
            $function=substr($irpp->Utils->qs('irpp_action'), $pos+1);

            $class=NULL;
            switch (strtolower($what)) {
                case 'cron':
                    $class=$irpp->Cron;
                    break;
                case 'tracking':
                    $class=$irpp->Tracking;
                    break;
                case 'properties':
                    $class=$irpp->Options;
                    break;
            }

            if(!$class) {
                $irpp->Log->fatal('NO CLASS FOR=%s IN ACTION=%s', $what, $irpp->Utils->qs('irpp_action'));
            } elseif(!method_exists ($class, $function)) {
                $irpp->Log->fatal('NO METHOD FOR=%s IN CLASS=%s IN ACTION=%s', $function, $what, $irpp->Utils->qs('irpp_action'));
            } else {
                $irpp->Log->debug('METHOD=%s OF CLASS=%s', $function, $what);
                call_user_func(array($class, $function), $args);
            }
        } else {
            $irpp->Log->fatal('NO FUNCTION FOR==%s', $irpp->Utils->qs('irpp_action'));
        }
	}
}
