<?php

/*

Add This extension for localhost checking :
Chrome Extension : Advanced REST client Application
URL : https://chrome.google.com/webstore/detail/hgmloofddffdnphfgcellkdfbfbjeloo

Or use Firebug (for Firefox)

     */
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', mh_cfg('MAILBEEZ_API_DEBUG', 0));

require_once(MH_DIR_CONFIG . 'config_api/classes/Rest.inc.php');


class mailbeezApi extends REST
{

    public $data = "";

    var $api_url;
    var $api_key;
    var $api_version;
    var $extenders = array();

    var $request_module;
    var $request_module_method;
    var $request_entrypoint;
    var $request_method;
    var $request_data;

    var $api_secret_key = MAILBEEZ_API_KEY;

    public function __construct()
    {
        parent::__construct(); // Init parent contructor

        $this->request_method = $this->get_request_method();
        $this->load_extender();
    }


    /*
          * Public method for access api.
          * This method dynmically call the method based on the query string
          *
          */
    public function processApi($internal_call = null)
    {

        if ($internal_call) {
            $this->api_key = $this->api_secret_key;
            $request_elements = explode('/', $internal_call);
        } else {
            $request_elements = explode('/', $_SERVER['PATH_INFO']);

            $this->api_key = trim(str_replace("/", "", mh_request('apikey')));
        }


        array_shift($request_elements); // remove empty
        array_shift($request_elements); // remove /api/

        $this->request_entrypoint = array_shift($request_elements);
        $this->api_version = array_shift($request_elements); // get version

        $this->request_module = array_shift($request_elements);
        $this->request_module_method = array_shift($request_elements);
        $this->request_data = $request_elements;

        $entrypoint = 'api_' . $this->request_entrypoint;

        if ((int)method_exists($this, $entrypoint) > 0) {
            $this->$entrypoint();
        } else {
            $this->response('', 404); // If the method not exist with in this class, response would be "Page not found".
            echo 404 . ": $entrypoint";
            mh_exit();
        }
    }

    // http://localhost/osc_mailhive/catalog/mailhive.php/api/private/v1.0/product/reviews

    // entrypoint public
    function api_public()
    {
        return $this->api_handler();

    }
    // entrypoint internal
    function api_internal()
    {
        return $this->api_handler();
    }

    // entrypoint private

    function api_private()
    {

        if ($this->api_key != $this->api_secret_key) {
            $result = array('result' => false, 'error' => 'Unauthorized');
            $this->response($this->json($result), 401); // Unauthorized
            mh_exit();
        }
        return $this->api_handler();

    }


    function api_handler()
    {
        $api_module = 'api_' . $this->request_entrypoint . '_' . $this->request_module;
        $api_module_method = 'api_' . $this->request_entrypoint . '_' . $this->request_module . '_' . $this->request_module_method;

        if (isset($this->extenders[$api_module])) {
            $result = $this->api_handler_call($api_module);
            $this->response($this->json($result), 200);
        } elseif (isset($this->extenders[$api_module_method])) {
            $result = $this->api_handler_call($api_module_method);
            $this->response($this->json($result), 200);

        } else {
            $this->response(404 . ": $api_module / $api_module_method", 404); // If the method not exist with in this class, response would be "Page not found".
//            echo 404 . ": $api_module / $api_module_method";
        }


        return true;

        if ((int)method_exists($this, $api_module) > 0) {
            $this->$api_module();
        } else {
            $this->response( 404 . ": $api_module", 404); // If the method not exist with in this class, response would be "Page not found".

        }

    }


    function api_handler_call($api_module_code)
    {

        $method = '_' . strtolower($this->request_method);
        $api_module = $this->extenders[$api_module_code];

        if ((int)method_exists($api_module, $method) > 0) {
            $result = $api_module->$method($this->request_data, $this->_request);
            return $result;
        } else {
            $this->response('404' . ": $method", 404); // If the method not exist with in this class, response would be "Page not found".
//            echo 404 . ": $method";
        }
    }

    function api_check_method($method)
    {
        // $method = GET|POST
        if ($this->get_request_method() != $method) {
            $this->response('', 406);
        }
    }


    function load_extender($type = 'apibeez')
    {
        $seg_module_directory_array = glob(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '*/*/' . $type, GLOB_ONLYDIR);
        if (is_array($seg_module_directory_array) && sizeof($seg_module_directory_array) > 0) {
            foreach ($seg_module_directory_array as $idx => $seg_module_directory) {
                $seg_module_directory .= '/';
                $seg_module_directory = str_replace(MH_DIR_FS_CATALOG, '', $seg_module_directory);

                $seg_module_array = $this->read_module_directory(MH_DIR_FS_CATALOG . $seg_module_directory);

                if (sizeof($seg_module_array) > 0) {

                    foreach ($seg_module_array as $idx1 => $seg_module) {

                        $file = $seg_module;
                        $class = substr($file, 0, strrpos($file, '.'));

                        if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
//                            continue;
                        }

                        $seg_module_directory_path = MH_DIR_FS_CATALOG . $seg_module_directory;

                        if (file_exists($seg_module_directory_path . $file) && !class_exists($class)) {
                            include($seg_module_directory_path . $file);
                        }
                        if (class_exists($class)) {
                            mh_log("creating object: %s", $class);
                            $GLOBALS[$class] = new $class; // new object
                            $this->add_extender($GLOBALS[$class], $class);
                        }
                        mh_load_modules_language_files($seg_module_directory_path, $class, MH_FILE_EXTENSION);
                    }
                }
            }
        }
    }

    function read_module_directory($module_directory_current)
    {
        $directory_array = array();
        if ($dir = @dir($module_directory_current)) {
            while ($file = $dir->read()) {
                if (!is_dir($module_directory_current . $file)) {
                    if (substr($file, strrpos($file, '.')) == MH_FILE_EXTENSION) {
                        $directory_array[] = $file;
                    }
                }
            }
            $dir->close();
        }
        return $directory_array;
    }


    function add_extender($obj, $id)
    {
        $obj->set_extendee($this);
        $this->extenders[$id] = $obj;
        return true;
    }


    //----


    function api_load_modules()
    {
        $api_module_directory_array = glob(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '*/*/apibeez', GLOB_ONLYDIR);

        if (is_array($api_module_directory_array) && sizeof($api_module_directory_array) > 0) {

            foreach ($api_module_directory_array as $idx => $api_module_directory) {

                $api_module_directory_array[$idx] .= '/';
                $api_module_directory_array[$idx] = str_replace(MH_DIR_FS_CATALOG, '', $api_module_directory_array[$idx]);

            }
        }
        $directory_array = array();
        foreach ($api_module_directory_array as $api_module_directory_current) {
            $directory_array = $this->mh_read_module_directory($api_module_directory_current);
        }
        for ($i = 0, $n = sizeof($directory_array); $i < $n; $i++) {
            $offset = 0;
            $file = $directory_array[$i];
            $class = substr($file, 0, strrpos($file, '.'));

            if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
                continue;
            }

            $api_module_directory_path = MH_DIR_FS_CATALOG;

            if (file_exists($api_module_directory_path . $file) && !class_exists($class)) {
                include_once($api_module_directory_path . $file);
            }
        }
    }

    function mh_read_module_directory($module_directory_current)
    {
        $directory_array = array();
        if ($dir = @dir($module_directory_current)) {
            while ($file = $dir->read()) {
                if (!is_dir($module_directory_current . $file)) {
                    if (substr($file, strrpos($file, '.')) == MH_FILE_EXTENSION && $file != 'config.php') {
                        $directory_array[] = $file;
                    }
                }
            }
            $dir->close();
        }
        return $directory_array;
    }


    /*
    // demo


    // get orders for email
    function orderinfo()
    {


        $email = $this->request_data[0];

        if ($email == '') {
            // If invalid inputs "Bad Request" status message and reason
            $error = array('status' => "Failed", "msg" => "Invalid Email address");
            $this->response($this->json($error), 400);
        }


        $result['response'] = array('42' => 'my order for: ' . $email);

        // If success everythig is good send header as "OK" and user details
        $this->response($this->json($result), 200);

        // If no records "No Content" status
//        $this->response('', 204);

    }


    function demo()
    {
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'dashboardbeez/dashboard_beez_o_graph.php');
        $d = new dashboard_beez_o_graph();

        list($js_array_sent, $js_array_bounce, $js_array_open, $js_array_clicked, $js_array_ordered, $js_array_block) = $d->generateData();

        $result['response'] = array('sent' => $js_array_sent,
            'bounce' => $js_array_bounce,
            'open' => $js_array_open,
            'clicked' => $js_array_clicked,
            'ordered' => $js_array_ordered,
            'blocked' => $js_array_block,
        );

        $this->response($this->json($result), 200);
    }

    // demo

*/
    /*
          *	Encode array into JSON
         */
    private function json($data)
    {
        if (is_array($data)) {
            return json_encode($data);
        }
    }
}
