/**
 * Implementation of hook_civicrm_pageRun
 *
 * Handler for pageRun hook.
 */
function mailjet_civicrm_pageRun(&$page)
{
    if (get_class($page) == 'CRM_Mailing_Page_Report') {
        $mailingId = $page->_mailing_id;
        $mailingJobs = civicrm_api3('MailingJob', 'get', $params = array('mailing_id' => $mailingId));
        $stats = array('BlockedCount' => 0, 'BouncedCount' => 0, 'ClickedCount' => 0, 'DeliveredCount' => 0, 'OpenedCount' => 0, 'ProcessedCount' => 0, 'QueuedCount' => 0, 'SpamComplaintCount' => 0, 'UnsubscribedCount' => 0);
        foreach ($mailingJobs['values'] as $key => $job) {
            if ($job['job_type'] == 'child') {
                $jobId = $key;
                require_once 'packages/mailjet-0.3/php-mailjet-v3-simple.class.php';
                // Create a new Mailjet Object
                $mj = new Mailjet(MAILJET_API_KEY, MAILJET_SECRET_KEY);
                $mj->debug = 0;
                $mailJetParams = array('method' => 'VIEW', 'unique' => CRM_Mailjet_BAO_Event::getMailjetCustomCampaignId($jobId));
                $response = $mj->campaign($mailJetParams);
                $page->assign('mailjet_params', $mailJetParams);
                if (!empty($response)) {
                    if ($response->Count == 1) {
                        $campaign = $response->Data[0];
                        $mailJetParams = array('method' => 'VIEW', 'unique' => $campaign->ID);
                        $response = $mj->campaignstatistics($mailJetParams);
                        if ($response->Count == 1) {
                            $stats = sumUpStats($stats, get_object_vars($response->Data[0]));
                        }
                    }
                }
            }
        }
        $page->assign('mailjet_stats', $stats);
        CRM_Core_Region::instance('page-header')->add(array('template' => 'CRM/Mailjet/Page/Report.tpl'));
    }
}