<?php
//error_reporting(error_reporting() & ~E_NOTICE);
//error_reporting(E_ALL);
error_reporting(0);

require_once($_SERVER["DOCUMENT_ROOT"] . '/library/functions.php');
openDBLIPlayground3309('pareto');

$debug = isset($_GET['debug']);
$reload = isset($_GET['reload']);

/**
 * Class SamplePardotApiClient
 *
 * Example PHP client to call the Pardot API
 */
class QueryActivityPardotApiClient
{
    const BASE_URL = "https://pi.pardot.com/api/";
    const SALESFORCE_OAUTH_TOKEN_URL = "https://login.salesforce.com/services/oauth2/token";

    /** @var int $apiVersion */
    private $apiVersion;

    /** @var string $format  */
    private $format;

    public function __construct($apiVersion, $format = 'xml')
    {
        $this->apiVersion = $apiVersion;
        $this->format = $format;
    }

    /**
     * @param string $endpoint
     * @param string $operation
     * @param array $data
     * @param array $headers
     * @param array $queryParams
     * @param bool $useSalesforceOAuth
     * @return array
     * @throws Exception
     */
    public function post($endpoint, $operation, $data = [], $headers = [], $queryParams = [], $useSalesforceOAuth = true)
    {
        $curl_handle = $this->initRequest($endpoint, $operation, $headers, $queryParams, $useSalesforceOAuth);
        curl_setopt($curl_handle, CURLOPT_POST, true);
        // Add POST data if given
        if (!empty($data)) {
            curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $data);
        }

        return $this->executeCall($curl_handle);
    }

    /**
     * @param string $endpoint
     * @param string $operation
     * @param array $headers
     * @param array $queryParams
     * @param bool $useSalesforceOAuth
     * @return array
     * @throws Exception
     */
    public function get($endpoint, $operation, $headers = [], $queryParams = [], $useSalesforceOAuth = true)
    {
        $curl_handle = $this->initRequest($endpoint, $operation, $headers, $queryParams, $useSalesforceOAuth);

        return $this->executeCall($curl_handle);
    }

    /**
     * @param string $endpoint
     * @param string $operation
     * @param array $headers
     * @param array $queryParams
     * @param bool $useSalesforceOAuth
     * @return false|resource
     */
    private function initRequest($endpoint, $operation, $headers = [], $queryParams = [], $useSalesforceOAuth = true)
    {
        // Construct our full URL to the Pardot API
        $url = $this->buildUrl($endpoint, $operation, $useSalesforceOAuth);
        // Add desired format to any query string params provided
        $queryParams['format'] = $this->format;
        // Build query string params into an encoded string
        $queryString = http_build_query($queryParams, null, '&');
        $queryString = str_replace('%5B0%5D%5B0%5D','',$queryString);
        // Append query string params to URL
        $url .= "?{$queryString}";

        // Init curl handle and set standard curl options: timeouts / require SSL / verify SSL
        $curl_handle = curl_init($url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_handle, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl_handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);

        // Add any headers passed in such as Authorization header
        if (!empty($headers)) {
            curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
        }

        return $curl_handle;
    }

    /**
     * @param string $endpoint
     * @param string $operation
     * @param bool $useSalesforceOAuth
     * @return string
     */
    private function buildUrl($endpoint, $operation = "", $useSalesforceOAuth = true)
    {
        if ($endpoint === 'login') {
            if ($useSalesforceOAuth) {
                return self::SALESFORCE_OAUTH_TOKEN_URL;
            } else {
                return self::BASE_URL . "login";
            }
        }

        return self::BASE_URL . "{$endpoint}/version/{$this->apiVersion}/do/{$operation}";
    }

    /**
     * @param $curl_handle
     * @return array
     * @throws Exception
     */
    private function executeCall($curl_handle)
    {
        // Execute our call to the Pardot API
        $rsp = curl_exec($curl_handle);
        // Gather the HTTP response code and last effective URL called
        $httpCode = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
        $url = curl_getinfo($curl_handle, CURLINFO_EFFECTIVE_URL);

        // Handle errors in calls, this could be a log or an exception thrown as written here
        if (!$rsp) {
            $errorMessage = curl_error($curl_handle);
            curl_close($curl_handle);
            throw new Exception("Error calling API. HTTP Code: {$httpCode}. Message: {$errorMessage}");
        }
        curl_close($curl_handle);

        // Output call response for informational purposes
        /*
        echo ("URL: {$url}" . PHP_EOL);
        echo ("HTTP Response Code: {$httpCode}" . PHP_EOL);
        echo ("Response: {$rsp}" . PHP_EOL . PHP_EOL);
        */

        return [$httpCode, $rsp];
    }

    /**
     * Use Pardot API using Api Key and User Key - No longer available
     */
    /*
    public function executeRequestsWithApiKeys()
    {
        // Setup user credentials
        $credentials = [
            'user_key' => '60ef081ba86770e2a43d0a14a1d45029',
            'email' => 'revenuewell@2x.marketing',
            'password' => '2XMarketing2020!'
        ];

        // Authenticate to Pardot - Must be a POST with credentials in the message body
        list($httpCode, $rsp) = $this->post('login', '', $credentials, null, [], false);
        // Capture the api_key from a successful login response
        // api_key is good for 1 hour and can be reused on subsequent calls
        $apiKey = json_decode($rsp, true)['api_key'];

        // Create Authorization Header from api_key
        $authHeader = ["Authorization: Pardot user_key={$credentials['user_key']},api_key={$apiKey}"];

        $strSQL = "select MAX(_pardotID) from pardot_prospect";
        $prevMax = getArrayResult($strSQL);
        if (empty($prevMax)) {
            $prevMax = 0;
        }

        // Call Prospect Query
        $params = array(
            'limit'=>200, 
            'id_greater_than'=>$prevMax, 
            'sort_by'=>'id', 
            'sort_order' => 'ascending'
        );
        
        list($httpCode, $rsp) = $this->get('prospect', 'query', $authHeader, $params);

        return $rsp;
    }
    */

    /**
     * Use Pardot API with a SSO user.
     * Getting the access token and using that to use the Pardot API.
     */
    public function executeRequestsWithSalesforceOAuth()
    {
        // Setup user credentials
        /*
        $credentials = [
            "grant_type" => "password",
            "client_id" => "<your_client_id>",
            "client_secret" => "<your_client_secert>",
            "username" => "<your_salesforce_email>",
            "password" => "<your_password>"
        ];
        */
        $credentials = [
            "grant_type" => "password",
            "client_id" => "3MVG9A2kN3Bn17hviVFf.TwbV0egtvohywPyVe4llySiHm57NrpLQycbSQuG85UU_y6Pl3fnpJAFd6Z5X3PoY",
            "client_secret" => "587BDBE3AC3A047E2B6B33C82033C65D0C5CBC90DE76BFF5D94E64A064749F8A",
            "username" => "jasmine.sim@2x.marketing",
            "password" => 'Pareto_2X22_!!!'
        ];

        //$pardot_business_unit_id = "<Pardot_business_unit_id>";
        $pardot_business_unit_id = "0Uv5A000000006dSAA";

        // Authenticate to Salesforce - Must be a POST with credentials in the message body
        list($httpCode, $rsp) = $this->post('login', '', $credentials, null, [], true);
        //var_dump($rsp);

        // Capture the access_token from a successful login response
        $access_token = json_decode($rsp, true)['access_token'];

        // Create Authorization Header from access_token and business unit
        $authHeader = ["Authorization: Bearer {$access_token}", "Pardot-Business-Unit-Id: {$pardot_business_unit_id}"];

        $strSQL = "select MAX(_pardotActivityID) from pardot_visitor_activity";
        $prevMax = getArrayResult($strSQL);
        if (empty($prevMax)) {
            $prevMax = 0;
        }

        // Call Prospect Query
        $params = array(
            'limit'=>200, 
            'id_greater_than'=>$prevMax, 
            'sort_by'=>'id', 
            'sort_order' => 'ascending',
            'prospect_only' => 'true'
        );
        
        /*
        Test
        $params = array(
            'limit'=>10, 
            'created_after'=>'yesterday',
            'sort_by'=>'id', 
            'sort_order' => 'descending',
            'offset' => 10,
            'prospect_only' => 'true'
        );
        */
        // Call Prospect Query
        //list($httpCode, $rsp) = $this->get('prospect', 'query', $authHeader, $params);

        
        // Call VisitorActivity Query
        list($httpCode, $rsp) = $this->get('visitorActivity', 'query', $authHeader, $params);
        //var_dump($rsp);
        /*
        
        // Create a Campaign
        list($httpCode, $rsp) = $this->post(
            'campaign',
            'create',
            ['name' => 'A Campaign', 'cost' => 100],
            $authHeader
        );
        */
        return $rsp;
    }
}

$start = time();

// Prepare to call version 3 or 4 of the API with JSON or XML responses
$client = new QueryActivityPardotApiClient(4, 'json');



// Authenticate to Pardot - Using API Keys
//$rsp = $client->executeRequestsWithApiKeys();
$rsp = $client->executeRequestsWithSalesforceOAuth();
$rspArray = json_decode($rsp, true);

if ($debug) {
    var_dump($rsp);
}

$totalAffected = 0;

$result = $rspArray['result'];
$activities = $result['visitor_activity'];

foreach ($activities as $p) {
    $pardotActivityID = $p['id'];
    $pardotProspectID = $p['prospect_id'];
    $type = $objConn->real_escape_string($p['type']);
    $typeName = $objConn->real_escape_string($p['type_name']);
    $details = $objConn->real_escape_string($p['details']);
    $emailID = isset($p['email_id']) ? $objConn->real_escape_string($p['email_id']) : '';

    $emailName = isset($p['email']['name']) ? $objConn->real_escape_string($p['email']['name']) : '';
    $emailAppURL = isset($p['email']['app_url']) ? $objConn->real_escape_string($p['email']['app_url']) : '';

    $listEmailID = isset($p['list_email_id']) ? $objConn->real_escape_string($p['list_email_id']) : '';
    $emailTemplateID = isset($p['email_template_id']) ? $objConn->real_escape_string($p['email_template_id']) : '';

    $formID = isset($p['form_id']) ? $objConn->real_escape_string($p['form_id']) : '';
    $formName = isset($p['form']['name']) ? $objConn->real_escape_string($p['form']['name']) : '';
    $formAppURL = isset($p['form']['app_url']) ? $objConn->real_escape_string($p['form']['app_url']) : '';

    $formHandlerID = isset($p['form_handler_id']) ? $objConn->real_escape_string($p['form_handler_id']) : '';
    $formHandlerName = isset($p['form_handler']['name']) ? $objConn->real_escape_string($p['form_handler']['name']) : '';
    $formHandlerAppURL = isset($p['form_handler']['app_url']) ? $objConn->real_escape_string($p['form_handler']['app_url']) : '';

    $siteSearchQueryID = isset($p['site_search_query_id']) ? $objConn->real_escape_string($p['site_search_query_id']) : '';
    $landingPageID = isset($p['landing_page_id']) ? $objConn->real_escape_string($p['landing_page_id']) : '';
    $paidSearchAdID = isset($p['paid_search_ad_id']) ? $objConn->real_escape_string($p['paid_search_ad_id']) : '';
    $multivariateTestVariationID = isset($p['multivariate_test_variation_id']) ? $objConn->real_escape_string($p['multivariate_test_variation_id']) : '';
    $visitorPageViewID = isset($p['visitor_page_view_id']) ? $objConn->real_escape_string($p['visitor_page_view_id']) : '';
    $fileID = isset($p['file_id']) ? $objConn->real_escape_string($p['file_id']) : '';
    $customRedirectID = isset($p['custom_redirect_id']) ? $objConn->real_escape_string($p['custom_redirect_id']) : '';
    $visitID = isset($p['visit_id']) ? $objConn->real_escape_string($p['visit_id']) : '';

    $campaignID = isset($p['campaign']['id']) ? $objConn->real_escape_string($p['campaign']['id']) : '';
    $campaignName = isset($p['campaign']['name']) ? $objConn->real_escape_string($p['campaign']['name']) : '';
    $campaignCRMID = isset($p['campaign']['crm_fid']) ? $objConn->real_escape_string($p['campaign']['crm_fid']) : '';

    $createdAt = $objConn->real_escape_string($p['created_at']);
    $updatedAt = $objConn->real_escape_string($p['updated_at']);

    

    $strSQL = "INSERT INTO pardot_visitor_activity (_pardotActivityID,
_pardotProspectID,
_type,
_typeName,
_details,
_emailID,
_emailName,
_emailAppURL,
_listEmailID,
_emailTemplateID,
_formID,
_formName,
_formAppURL,
_formHandlerID,
_formHandlerName,
_formHandlerAppURL,
_siteSearchQueryID,
_landingPageID,
_paidSearchAdID,
_multivariateTestVariationID,
_visitorPageViewID,
_fileID,
_customRedirectID,
_visitID,
_campaignID,
_campaignName,
_campaignCRMID,
_createdAt,
_updatedAt)
VALUES ('$pardotActivityID',
'$pardotProspectID',
'$type',
'$typeName',
'$details',
'$emailID',
'$emailName',
'$emailAppURL',
'$listEmailID',
'$emailTemplateID',
'$formID',
'$formName',
'$formAppURL',
'$formHandlerID',
'$formHandlerName',
'$formHandlerAppURL',
'$siteSearchQueryID',
'$landingPageID',
'$paidSearchAdID',
'$multivariateTestVariationID',
'$visitorPageViewID',
'$fileID',
'$customRedirectID',
'$visitID',
'$campaignID',
'$campaignName',
'$campaignCRMID',
'$createdAt',
'$updatedAt')
ON DUPLICATE KEY UPDATE _pardotProspectID='$pardotProspectID',
_type='$type',
_typeName='$typeName',
_details='$details',
_emailID='$emailID',
_emailName='$emailName',
_emailAppURL='$emailAppURL',
_listEmailID='$listEmailID',
_emailTemplateID='$emailTemplateID',
_formID='$formID',
_formName='$formName',
_formAppURL='$formAppURL',
_formHandlerID='$formHandlerID',
_formHandlerName='$formHandlerName',
_formHandlerAppURL='$formHandlerAppURL',
_siteSearchQueryID='$siteSearchQueryID',
_landingPageID='$landingPageID',
_paidSearchAdID='$paidSearchAdID',
_multivariateTestVariationID='$multivariateTestVariationID',
_visitorPageViewID='$visitorPageViewID',
_fileID='$fileID',
_customRedirectID='$customRedirectID',
_visitID='$visitID',
_campaignID='$campaignID',
_campaignName='$campaignName',
_campaignCRMID='$campaignCRMID',
_createdAt='$createdAt',
_updatedAt='$updatedAt' 
    ";

    $objConn->query($strSQL);

    $affected = $objConn->affected_rows;
    if ($affected > 0) {
        $totalAffected++;
    }

    if ($debug) {
        echo $strSQL . '<br/>';
        echo 'inserted = ' . $affected . '<br/><br/>';
    }
    
}



echo 'Total insert / updated: ' . $totalAffected . '<br/>';
echo 'Time spent: ' . (time() - $start);
// Authenticate to Pardot - Using Salesforce OAuth
//$client->executeRequestsWithSalesforceOAuth();

if ((sizeof($activities) > 0) && $reload) {
?>    

<script type = "text/javascript">
window.onload=location.reload();
</script>

<?php
}

?>
