<?php 

error_reporting(E_ALL);
ini_set("display_errors", 1);

class Spins_API extends API {

    private static $instance = NULL;
    private $db = NULL;
    private $lurl = false;

    public static function Singleton() {        
        if( !self::$instance ) {
            self::$instance = new Spins_API();
        }

        $GLOBALS["addon_spins_class"] = self::$instance;
        return self::$instance;
    }

    public function __construct() {        
        $this->db = IEM::getDatabase();
    }

    public function url_details($id=false) {
        
        if( !$id ) {            
            $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "spins_urls";
            $q = $this->db->Query($query);
            $data = array();
            while( $row = $this->db->Fetch($q) ) {                
                $data[] = $row;
            }

            return $data;
        }

        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "spins_urls WHERE uid='" . $this->db->Quote($id) . "'";
        $result = $this->db->Query($query);
        $r = $this->db->Fetch($result);
        $data = $r ? $r : array( "count" => 0 );
        return array( "exist" => $r ? true : false , "data" => $data );
    }

    public function url_add($data) {        
        $result = $this->db->InsertQuery("spins_urls", array( "url" => $data["url"] ));
        return $result;
    }

    public function url_update($data) {        
        $uid = is_numeric($data["uid"]) ? $data["uid"] : 0;
        $result = $this->db->UpdateQuery("spins_urls", array( "url" => $data["url"] ), "`uid`=" . $uid);
        return $result;
    }

    public function url_delete($id) {        
        return $this->db->DeleteQuery("spins_urls", "WHERE `uid`=" . $id, 1);
    }

    public function p_rep($matches) {        
        $e = explode("|", $matches[1]);
        $rnd = rand(0, count($e) - 1);
        return $e[$rnd];
    }

    public function spin($text) {        
        $result = preg_replace_callback("/\\{([^\\}]+)\\}/i", array( $this , "p_rep" ), $text);
        return $result;
    }

    public function p_rep_url($matches) {        
        if( $this->lurl ) {            
            return $this->lurl;
        }

        $rurl = $this->get_random_url();
        if( $rurl ) {            
            $this->lurl = $rurl;
            return $rurl;
        }

        return $matches[0];
    }

    public function get_random_url() {        
        $query = "SELECT * FROM " . SENDSTUDIO_TABLEPREFIX . "spins_urls ORDER BY RAND() LIMIT 1";
        $result = $this->db->Query($query);
        $r = $this->db->Fetch($result);
        $data = $r ? $r["url"] : false;
        return $data;
    }

    public function rotate_url($text) {        
        $uri = parse_url(SENDSTUDIO_APPLICATION_URL);
        $result = preg_replace_callback("/" . $uri["host"] . "/i", array( $this , "p_rep_url" ), $text);
        return $result;
    }

    public function iem_spin($_this, $disconnect) {        
        $_this->Email_API->spin = array();
        $_this->Email_API->_AssembledEmail["Headers"]["m"] = NULL;
        $_this->Email_API->_AssembledEmail["Headers"]["t"] = NULL;
        $_this->Email_API->_AssembledEmail["Headers"]["h"] = NULL;
        $_this->Email_API->_AssembledEmail["Body"]["m"] = NULL;
        $_this->Email_API->_AssembledEmail["Body"]["t"] = NULL;
        $_this->Email_API->_AssembledEmail["Body"]["h"] = NULL;
    }

    public function iem_spin_into_ss_email($_this, $disconnect_from_smtp) {        
        if( isset( $_this->spin) && is_array($_this->spin) ) {            
            if( !$tmp && !is_array($tmp) ) {                
                //echo "no existe" . PHP_EOL;
                $tmp = array();
                $tmp["subject"] = $_this->Subject;
                $tmp["from_name"] = $_this->FromName;
                $tmp["mail_bounce"] = $_this->BounceAddress;
                $tmp["mail_from"] = $_this->FromAddress;
                $tmp["mail_reply"] = $_this->ReplyTo;
                $tmp = $tmp;
            }
            else {                
                //echo "existe" . PHP_EOL;
                if( isset( $GLOBALS["addon_mta_umf"] ) && $GLOBALS["addon_mta_umf"] == true ) {
                    
                    echo "from " . $tmp["mail_from"] . " to " . $_this->FromAddress . PHP_EOL;
                    $tmp["mail_from"] = $_this->FromAddress;
                    echo "modify mail from in cache for spin" . PHP_EOL;
                }

                if( isset( $GLOBALS["addon_mta_umr"] ) && $GLOBALS["addon_mta_umr"] == true ) {
                    
                    echo "from " . $tmp["mail_reply"] . " to " . $_this->ReplyTo . PHP_EOL;
                    $tmp["mail_reply"] = $_this->ReplyTo;
                    echo "modify mail reply in cache for spin" . PHP_EOL;
                }

                if( isset( $GLOBALS["addon_mta_umb"] ) && $GLOBALS["addon_mta_umb"] == true ) {
                    
                    echo "from " . $tmp["mail_bounce"] . " to " . $_this->BounceAddress . PHP_EOL;
                    $tmp["mail_bounce"] = $_this->BounceAddress;
                    echo "modify mail bounce in cache for spin" . PHP_EOL;
                }

            }

            $_this->Set("FromName", $this->spin($tmp["from_name"]));
            $_this->Set("Subject", $this->spin($tmp["subject"]));
            $_this->Set("FromAddress", $this->spin($tmp["mail_from"]));
            $_this->Set("ReplyTo", $this->spin($tmp["mail_reply"]));
            $_this->Set("BounceAddress", $this->spin($tmp["mail_bounce"]));
        }

    }

    public function iem_spin_into_ss_email_body($_this, $body) {        
        if( isset( $_this->spin) && is_array($_this->spin) ) {            
            $body = $this->spin($body);
            $body = $this->rotate_url($body);

            return $body;
        }
    }

}

?>
