<?php
/**
 * @desc this program will add or edit a logaholic user account
 * for more information please read:
 * http://www.logaholic.com/manual/LogaholicManual/APIDocumentationForServiceProviderEditions
 */

class LogaholicDBSubscription
{
    var $subscriptionid;
    var $subscriptionname;
    var $subscriptionvalues;

    #Delete vars
    var $movetosubid;
    var $movetosubname;

    function __construct()
    {
        global $config;

        $this->subscriptionname = '';
        $this->subscriptionid = '';
        $this->subscriptionvalues = '';

        $this->movetosubid = '';
        $this->movetosubname = '';

        # first check the variables we need to execute this program
        $this->CheckVars();

        # now connect to the database
        $this->dbConnect();

        include_once($config['path'] . "/components/Subscriptions/subscriptions.php");
        $this->subscriptions = new Subscriptions();
        $this->subscriptions->createReportsTable();
        $this->subscriptions->createSubscriptionsTable();
        $this->subscriptions->createUserLogTable();
    }

    function CheckVars()
    {
        global $action;
        $help = "Required at least one of these variables:<br>\n";
        $help .= " - subscriptionname (addsubscription, editsubscription, deletesubscription)<br>\n";
        $help .= " - subscriptionid (editsubscription, deletesubscription)<br>\n";
        $help .= "Optional variables:<br>\n";
        $help .= " - movetosubid (deletesubscription)<br>\n";
        $help .= " - movetosubname (deletesubscription)<br>\n";
        $help .= "- custom ( array - example: custom[price]=100&custom[description]=testing)<br>\n";

        if ((isset($_GET['from']) && is_numeric($_GET['from'])) && (isset($_GET['to']) && is_numeric($_GET['to']))) {
            $this->from = $_GET['from'];
            $this->to = $_GET['to'];
        }

        # ignore List
        if ($action == "getreportslist") {
            return true;
        } else {
            if ($action == "getsubscriptions") {
                return true;
            } else {
                if ($action == "syncsubscriptions") {
                    return true;
                } else {
                    if ($action == "getsubscriptionslog") {
                        return true;
                    }
                }
            }
        }


        if (empty($_GET["subscriptionname"]) && empty($_GET["subscriptionid"])) {
            Output($help, true);
        }
        if (empty($_GET["subscriptionname"]) && $action = "addsubscription") {
            Output($help, true);
        }

        if (!empty($_GET["movetosubid"])) {
            $this->movetosubid = $_GET["movetosubid"];
        }

        if (!empty($_GET["movetosubname"])) {
            $this->movetosubname = $_GET["movetosubname"];
        }


        if (!empty($_GET["subscriptionname"])) {
            $this->subscriptionname = $_GET["subscriptionname"];
        }
        if (!empty($_GET["subscriptionid"])) {
            $this->subscriptionid = $_GET["subscriptionid"];
        }

        $this->SetValues();
    }

    function SetValues()
    {
        global $action;
        $values = array();
        $ignore = array(
            "subscriptionname"
        ,
            "subscriptionid"
        ,
            "action"
        ,
            "api_password"
        ,
            "movetosubid"
        ,
            "movetosubname"
        );

        if (!empty($_GET['custom'])) {
            foreach ($_GET['custom'] as $rkey => $rval) {
                if (!in_array($rkey, $ignore)) {
                    $values[$rkey]['value'] = $rval;
                    $values[$rkey]['type'] = '';
                }
            }
        }
        $values["reports"] = array();
        if (!empty($_GET['reports'])) {
            $values["reports"] = $_GET['reports'];
        }

        $values["reports"] = $this->CheckReports($values["reports"]);

        $this->subscriptionvalues = json_encode($values);
    }

    function CheckReports($reports)
    {
        global $db;
        $checked = array();
        foreach ($reports as $key => $value) {
            if (is_numeric($value)) {
                $checked[$k] = $value;
            }
        }
        return $checked;
    }

    function dbConnect()
    {
        global $db, $config;
        require_once($config['path'] . "/common.inc.php");
    }

    function SyncSubscriptions()
    {
        global $db;

        # First synchronize the reports table for the id's
        $reports = json_decode($_GET['reportsdata'], true);

        $db->Execute("DELETE FROM " . TBL_REPORTS);

        if (!empty($reports) && is_array($reports)) {
            foreach ($reports as $report) {
                $query = "REPLACE INTO " . TBL_REPORTS . " (`id`,`filename`, `value`) VALUES (?,?,?)";
                $db->Execute($query, array($report['id'], $report['filename'], $report['value'])) or Output(
                    "An error occurred: " . $db->ErrorMsg(),
                    true
                );
            }
        } else {
            Output("Invalid Report Data.", true);
        }

        # Now sync the subscriptions
        $full_data = json_decode($_GET['subscriptions'], true);
        if (!empty($full_data) && is_array($full_data)) {
            foreach ($full_data as $data) {
                if (!isset($data['id']) && !isset($data['name']) && !isset($data['value']) && count($data) != 3) {
                    Output("Invalid Data.", true);
                }
                $query = "REPLACE INTO `" . TBL_SUBSCRIPTIONS . "` (`id`,`name`,`value`) VALUES (?,?,?)";
                $db->Execute($query, array($data['id'], $data['name'], $data['value'])) or Output(
                    "An error occurred: " . $db->ErrorMsg(),
                    true
                );
            }
        } else {
            Output("Invalid Subscriptions Data.", true);
        }
        Output("Synchronize subscriptions completed.");
    }

    function GetSubscriptions()
    {
        global $db;
        $data = array();
        $r = $db->Execute("SELECT * FROM " . TBL_SUBSCRIPTIONS);
        while ($row = $r->fetchRow()) {
            $data[$row['id']] = $row;
        }

        if (empty($data)) {
            Output("Subscriptions do not exists.", true);
        }

        return $data;
    }

    function ReportsList()
    {
        global $db;
        $data = array();
        $r = $db->Execute("SELECT * FROM " . TBL_REPORTS);
        while ($row = $r->fetchRow()) {
            $data[$row['id']] = $row;
        }

        if (empty($data)) {
            return false;
        }
        return $data;
    }

    function AddSubscription()
    {
        global $db;

        $query = "INSERT INTO `" . TBL_SUBSCRIPTIONS . "` (`name`,`value`) VALUES (" . $db->quote(
                $this->subscriptionname
            ) . "," . $db->quote($this->subscriptionvalues) . ")";

        $db->Execute($query) or Output("An error occurred " . $db->ErrorMsg(), true);

        Output("Success: Added subscription $this->subscriptionname<br>\n");
    }

    function EditSubscription()
    {
        global $db;
        if (empty($this->subscriptionid)) {
            $q = $db->Execute(
                "SELECT `id`,`value` FROM `" . TBL_SUBSCRIPTIONS . "` WHERE `name` =" . $db->quote(
                    $this->subscriptionname
                ) . " limit 1"
            );
            $data = $q->fetchRow();
            $id = $data['id'];
            $values = json_decode($data['value'], true);
        } else {
            $id = $this->subscriptionid;
            $q = $db->Execute("SELECT `value` FROM `" . TBL_SUBSCRIPTIONS . "` WHERE `id` = " . $db->quote($id));
            $data = $q->fetchRow();
            $values = json_decode($data['value'], true);
        }

        if (empty($data)) {
            Output("Subscription does not exists.", true);
        }

        # do i want to edit the name?
        $editname = "";
        if (!empty($this->subscriptionid) && !empty($this->subscriptionname)) {
            $editname = ", `name`= " . $db->quote($this->subscriptionname) . " ";
        }


        # values
        $this->subscriptionvalues = json_decode($this->subscriptionvalues, true);
        foreach ($this->subscriptionvalues as $k => $v) {
            $values[$k] = $v;
        }

        # do the edit query
        $values = json_encode($values);
        $query = "UPDATE `" . TBL_SUBSCRIPTIONS . "` SET `value` =" . $db->quote(
                $values
            ) . " {$editname} WHERE `id` = " . $db->quote($id);

        @$db->Execute($query) or Output("An error occurred " . $db->ErrorMsg(), true);


        Output("Success: Edited subscription $this->subscriptionname<br>\n");
    }

    function DeleteSubscription()
    {
        global $db;
        if (empty($this->subscriptionid)) {
            $q = $db->Execute(
                "SELECT `id` FROM `" . TBL_SUBSCRIPTIONS . "` WHERE `name` =" . $db->quote(
                    $this->subscriptionname
                ) . " limit 1"
            );
            $data = $q->fetchRow();
            $id = $data['id'];
        } else {
            $id = $this->subscriptionid;
        }

        $setid = 'null';
        if (!empty($this->movetosubid)) {
            $setid = $this->movetosubid;
        } else {
            if (!empty($this->movetosubname)) {
                $q = $db->Execute(
                    "SELECT `id` FROM `" . TBL_SUBSCRIPTIONS . "` WHERE `name` =" . $db->quote(
                        $this->movetosubname
                    ) . " LIMIT 1"
                );
                $data = $q->fetchRow();
                $id = $data['id'];
            }
        }

        if (empty($data)) {
            Output("Subscription does not exists.", true);
        }

        @$db->Execute(
            "UPDATE `" . TBL_USERS . "` SET subscriptionid = " . $db->quote(
                $setid
            ) . " WHERE `subscriptionid` = " . $db->quote($id)
        );

        # finally, delete the user record
        @$db->Execute("delete from `" . TBL_SUBSCRIPTIONS . "` where `name`=\"$this->subscriptionname\"") or Output(
            "An error occurred:" . $db->ErrorMsg(),
            true
        );

        Output("Success: Deleted subscription $this->subscriptionname<br>\n");
    }

    function GetSubscriptionsLog()
    {
        global $db;
        $db->SetFetchMode(ADODB_FETCH_ASSOC);

        $q = $db->Execute("SELECT * FROM " . TBL__SUBSCRIPTIONS_USERLOG);

        $data = array();
        while ($row = $q->fetchRow()) {
            $data[] = $row;
        }
        $db->SetFetchMode(ADODB_FETCH_BOTH);
        Output($data);
    }
}

?>