<?php

 
$reports["_INTERCOM_TOTAL_USERS"] = Array(
 	
  "ClassName" => "IntercomTotalUsers", 
  "Category" => "_INTERCOM", 
  "Options" => "daterangeField,displaymode",
  "Distribution" => "Premium",
  "EmailAlerts" => false,
  "Update" => false,
  "Filename" => "intercom_total_users"
 
); 

 
class IntercomTotalUsers extends Report {

    function Settings() {
        $this->DisplayModes = "table,barchart,linechart";
        $this->DefaultDisplay = "barchart";
        $this->columnDefinitions[] = array("Label" => "_DATE");
        $this->columnDefinitions[] = array("Label" => "Users", "totalRow" => "none");
        $this->help = "This will show the total users for intercom.";
        $old_api_id = $this->profile->GetOtherSettings("IntercomApiId", "");
        $old_api_key = $this->profile->GetOtherSettings("IntercomApiKey", "");
        if(isset($this->ApiKey) && $this->ApiKey != $old_api_key) {
           $this->profile->SetOtherSettings("IntercomApiKey", $this->ApiKey);
        } else {
            $this->ApiKey = $old_api_key;
            
        }
        if(isset($this->ApiID) && $this->ApiID != $old_api_id){
            $this->profile->SetOtherSettings("IntercomApiId", $this->ApiID);
        } else {
            $this->ApiID = $old_api_id;
        }


    }
    function curl_download($Url) {
 
    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();
 
    // Now set some options (most are optional)
 
    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);
 

    curl_setopt($ch, CURLOPT_USERPWD, $this->ApiID . ":" . $this->ApiKey);
    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: application/json',
        ));
 
    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 
    // Download the given URL, and return output_add_rewrite_var(name, value)
    $output = curl_exec($ch);
 
    // Close the cURL resource, and free system resources
    curl_close($ch);


    return($output);

    }   
    function DisplayCustomForm(){
        echo "<div class='form-group'>";
            echo "<label for='period'>New users per:</label>";
            echo "<select id='period' name='period' class='form-control'>";
                echo "<option value='_DAYS'";
                    if($this->period == '_DAYS') { echo " selected "; }
                echo ">"._DAYS."</option>";
                echo "<option value='_WEEKS'";
                    if($this->period == '_WEEKS') { echo " selected "; }
                echo ">"._WEEKS."</option>";
                echo "<option value='_MONTHS'";
                    if($this->period == '_MONTHS') { echo " selected "; }
                echo ">"._MONTHS."</option>";
            echo "</select>";       
        echo "</div>";        
        $form = "<div class='form-group'>" .
                "<label for='author'>API Key:</label>
                <input type='text' name='ApiKey'
                value='".@$this->ApiKey."' class='report_option_field form-control' /> " .
                "</div>" .
                "<div class='form-group'>" .
                "<label for='author'>API ID:</label>
                <input type='text' name='ApiID'
                value='".@$this->ApiID."' class='report_option_field form-control' />" .
                "</div>"; 
                 
        return $form;
    } 
    function AggregateUsers($import, $key, $default = 1){
        $ts = date('Y-m-d', $key);
        if($this->period == '_MONTHS'){
            $ts = date('Y-m', $key);
        }
        elseif($this->period == '_WEEKS'){
            $ts = date('Y-W', $key);
        }
        if(empty($import[$ts])){
            $import[$ts] = $default;
        }
        else{
            $import[$ts] += $default;
        }
        return $import;
    }
    function GetReportData(){


        $r = $this->curl_download("https://api.intercom.io/users");
        $data = json_decode($r, true);
        if(isset($data['total_count'])) {
            $ctotal = $data['total_count'];
        }

        if($data['type'] == 'error.list'){
            foreach($data['errors'] as $k => $v) {
                echoWarning("Intercom Error ({$v['code']}) : {$v['message']}");
            }
            return [];
        }

        if(empty($data)){
            return [];
        }

        $this->profile->SetOtherSettings("IntercomApiId", $this->ApiID);

        $this->profile->SetOtherSettings("IntercomApiKey", $this->ApiKey);

        $import = [];
        $lasttime = 0;
        $firsttime = 0;

        foreach($data['users'] as $key => $user) {
            if(empty($firsttime) || $firsttime > $user['created_at']){
                $firsttime = $user['created_at'];
            }       
            if(empty($lasttime) || $lasttime < $user['created_at']){
                $lasttime = $user['created_at'];
            }           

            $import = $this->AggregateUsers($import, $user['created_at']);
        }

        $totalpages = $data['pages']['total_pages'];
        if($totalpages > 1){
            for ($i=2; $i <= $totalpages; $i++) { 
                $r = $this->curl_download("https://api.intercom.io/users?page=$i");
                $data = json_decode($r, true);

                foreach($data['users'] as $key => $user) {
                    if(empty($firsttime) || $firsttime > $user['created_at']){
                        $firsttime = $user['created_at'];
                    }
                    if(empty($lasttime) || $lasttime < $user['created_at']){
                        $lasttime = $user['created_at'];
                    }            
                    $import = $this->AggregateUsers($import, $user['created_at']);
                }
            }
        }
        ksort($import);
        
        $time = $firsttime;

        while($time < $lasttime){
            $import = $this->AggregateUsers($import, $time, 0);

            if($this->period == '_MONTHS'){
                $time = mktime(0, 0, 0, date("m", $time)+1, date("d", $time), date("Y", $time));
            }
            elseif($this->period == '_WEEKS'){
                $time = mktime(0, 0, 0, date("m", $time), date("d", $time)+7, date("Y", $time));
            }
            else{
                $time = mktime(0, 0, 0, date("m", $time), date("d", $time)+1, date("Y", $time));
            }
        }

        ksort($import);
        $data = [];
        $i = 0;
        foreach($import as $date => $users){
            $dateparts = explode('-', $date);
            if($this->period == '_MONTHS'){
                $time = mktime(0, 0, 0, $dateparts[1], 1 , $dateparts[0]);
                $date = date("F Y", $time);
            }
            elseif($this->period == '_WEEKS'){
                $date = $dateparts[0] . " " . _WEEK . " " . $dateparts[1];
            }
            else{
                $time = mktime(0, 0, 0, $dateparts[1], $dateparts[2], $dateparts[0]);
                $date = date(implode($this->profile->dateFormat), $time);
            }           



            $data[$i][0] = $date;
            $data[$i][1] = $users;
            $i++;
        }
        $data = array_reverse($data);
        $newdata = [];
        foreach($data as $key => $row){
        	if($key == 0){
        		$newdata[$key][0] = $row[0];
        		$newdata[$key][1] = $ctotal;
        	}
        	else{
        		$ctotal = $ctotal - $row[1];
        		$newdata[$key][0] = $row[0];
        		$newdata[$key][1] = $ctotal;

        	}
        }

        $newdata = array_reverse($newdata);
        return $newdata;


    } 
    function DisplayReport(){
        // is cURL installed yet?
        if (!function_exists('curl_init')){
            echoWarning('Sorry cURL is not installed!');
            return false;
        }

        if (empty($this->ApiID) || empty($this->ApiKey)) {
            echoNotice($this->SettingsButton(). "The ID field or the Key field is empty. <br><br> for more information: check <a href='https://developers.intercom.io/page/getting-started' target='_blank'>the documentation</a>. ");
            return false;
        }else{
                parent::DisplayReport();
        }    
    }

}
?>