<?php

/**
 * @desc This file is a handler for the logaholic SPE API
 * for more information please read:
 * http://www.logaholic.com/manual/LogaholicManual/APIDocumentationForServiceProviderEditions
 */
$script_start = time();

require "config.php";
require "includes/common.php";
if (file_exists("includes/LogaholicDBInstall.php")) {
    require "includes/LogaholicDBInstall.php";
}
require "includes/LogaholicDBUser.php";
require "includes/LogaholicDBProfile.php";
require "includes/LogaholicDBBatch.php";
require "includes/LogaholicDBSubscription.php";
require "includes/LogaholicDBDatamanger.php";

# Quick fix for $_POST complatible
if (!empty($_POST)) {
    foreach ($_POST as $k => $v) {
        $_GET[$k] = $v;
    }
}
##### !!!
ReadVars();

date_default_timezone_set("Europe/Amsterdam");

# This array is stored in the call_log
$apilog = array(
    "Date" => date("Y-m-d H:i:s", time()),
    "Duration" => 0,
    "Action" => "",
    "Status" => "",
    "Parameters" => "",
    "Result" => ""
);
SetupApiLog($action, $_GET);

AccessControl($config['api_password']);

$mysqlprefix = $config['mysqlprefix'];
include_once($config['path'] . "/includes/table_definitions.php");
include_once($config['path'] . "/includes/version.php");

if (!isset($action)) {
    Output(
        "No action given. Please read the Logaholic Service Provider Edition API Documentation here <br>\nhttp://www.logaholic.com/manual/LogaholicManual/APIDocumentationForServiceProviderEditions"
    );
    exit();
}
$running_from_command_line = true;
switch ($action) {
    case 'getupdatestatus':
        $obj = new LogaholicDBProfile();
        $data = $obj->GetUpdateStatus();
        Output($data);
        break;

    case 'datalocation':

        include_once($config['path'] . "/common.inc.php");
        if (empty($_GET['conf'])) {
            Output(getGlobalSetting("datamanagerDirectory", logaholic_dir() . "data/"));
        } else {
            Output($profile->datamanagerDir);
        }
        break;

    case 'globalstats':
        include_once($config['path'] . "/common.inc.php");
        include_once($config['path'] . "/includes/datavisualization.php");
        include_once($config['path'] . "/includes/globalstats.php");
        $g = new Globalstats();
        $data = $g->Json();

        # To get clean data output lets first json decode the data.
        $data = json_decode($data, true);
        Output($data);
        break;

    case 'profilescount':
        $obj = new LogaholicDBProfile();
        $data = $obj->CountProfiles();
        Output($data);
        break;

    case 'exportlogdata':
        $obj = new LogaholicDBBatch();
        $result = $obj->Export();
        if ($result != false) {
            Output($result);
        }
        break;

    case 'logaholicversion':
        Output(LOGAHOLIC_BASE_EDITION . " " . LOGAHOLIC_VERSION_NUMBER);
        break;

    case 'installdb':
        if (!file_exists("includes/LogaholicDBInstall.php")) {
            Output("This feature is not available for your version");
            exit();
        }
        $obj = new LogaholicDBInstall();
        $obj->FreshInstall();
        break;

    case 'writeappconfig':
        $obj = new LogaholicDBInstall();
        $obj->WriteAppConfig();
        break;

    case 'adduser':
        $user = new LogaholicDBUser();
        $user->AddUser();
        break;

    case 'edituser':
        $user = new LogaholicDBUser();
        $user->EditUser();
        break;

    case 'deleteuser':
        $user = new LogaholicDBUser();
        $user->DeleteUser();
        break;

    case 'listusers':
        $user = new LogaholicDBUser();
        $data = $user->ListUsers();
        Output($data);
        break;

    case 'getuser':
        $user = new LogaholicDBUser();
        $data = $user->FetchUser();
        Output($data);
        break;

    case 'fetchuser':
        $user = new LogaholicDBUser();
        $data = $user->FetchUser();
        $return_str = '{';
        if (is_array($data) && !empty($data)) {
            foreach ($data as $key => $value) {
                $return_arr[] = "$key=$value";
            }
            $return_str .= implode(';', $return_arr);
        }
        $return_str .= '}';
        Output($return_str);
        break;

    case 'listuserprofiles':
        $user = new LogaholicDBUser();
        $user->ListUserProfiles();
        break;

    case 'getuserprofileinfo':
        $user = new LogaholicDBUser();
        $user->getUserProfileInfo();
        break;

    case 'listprofiles':
        $site = new LogaholicDBProfile();
        $data = $site->ListProfiles();
        Output($data);
        break;

    case 'editprofile':
        $site = new LogaholicDBProfile();
        $site->EditProfile();
        break;

    case 'renameprofile':
        $site = new LogaholicDBProfile();
        $site->RenameProfile();
        break;

    case 'addprofile':
        $site = new LogaholicDBProfile();
        $site->AddProfile();
        break;

    case 'deleteprofile':
        $site = new LogaholicDBProfile();
        $return = $site->DeleteProfile();
        if ($return != false) {
            Output($return);
        }
        break;

    case 'getprofileinfo':
        $site = new LogaholicDBProfile();
        $site->GetProfileInfo();
        break;

    case 'getdbsize':
        $user = new LogaholicDBUser();
        output($user->getUserDBSize());
        break;

    case 'exportprofilesettings':
        $obj = new LogaholicDBBatch();
        $obj->exportProfileSettings();
        break;

    case 'importprofilesettings':
        $obj = new LogaholicDBBatch();
        Output($obj->importProfileSettings());
        break;

    case 'includebackup':
        $site = new LogaholicDBProfile();
        $site->includeBackup();
        break;

    case 'getreportslist':
        $site = new LogaholicDBSubscription();
        $data = $site->ReportsList();
        if ($data === false) {
            Output("Error while collecting report data", true);
        } else {
            Output($data);
        }
        break;
    case 'addsubscription':
        $site = new LogaholicDBSubscription();
        $site->AddSubscription();
        break;

    case 'syncsubscriptions':
        $site = new LogaholicDBSubscription();
        $site->SyncSubscriptions();
        break;

    case 'getsubscriptions':
        $site = new LogaholicDBSubscription();
        $data = $site->GetSubscriptions();
        Output($data);
        break;

    case 'editsubscription':
        $site = new LogaholicDBSubscription();
        $site->EditSubscription();
        break;

    case 'deletesubscription':
        $site = new LogaholicDBSubscription();
        $site->DeleteSubscription();
        break;

    case 'editdatamanager':
        $site = new LogaholicDBDatamanger();
        $site->EditDatamanager();
        break;

    case 'set_affiliateid':
        $running_from_command_line = true;
        include_once($config['path'] . "/common.inc.php");
        @include_once($config['path'] . "/languages/english.php");
        affiliateID();
        break;

    case 'emailalerts':
        SetEmailAlerts();
        break;

    case 'reportstore':
        SetReportStore();
        break;

    case 'upgradelogaholicinstall':
        $obj = new LogaholicDBInstall();
        $obj->UpgradeLogaholicInstall();
        break;

    case 'upgrade':
        $obj = new LogaholicDBInstall();
        $obj->Upgrade();
        break;

    case 'getsubscriptionslog':
        $obj = new LogaholicDBSubscription();
        $obj->GetSubscriptionsLog();
        break;

    case 'packprofile':
        $pro = new LogaholicDBBatch();
        $pro->PackProfile();
        break;

    case 'unpackprofile':
        $pro = new LogaholicDBBatch();
        $pro->UnPackProfile();
        break;

    /*
    ** This action gives a list with the full data the CloudCron needs to update a Cloud Database
    */
    case 'cloudusersinfo':
        $obj = new LogaholicDBUser();
        Output($obj->GetCloudUsersInfo());
        break;

    default:
        Output(
            "No valid action found, please read:<br>\nhttp://www.logaholic.com/manual/LogaholicManual/APIDocumentationForServiceProviderEditions",
            true
        );
        break;
}