Overview

Packages

  • ACF
  • Automation
    • Actions
    • Activation
    • LeadProfile
    • Menus
    • Queries
    • Rules
    • Triggers
  • CTA
    • Activation
    • AJAXListeners
    • Cloning
    • Core
    • Display
    • EditPage
    • Enqueues
    • GPLSettings
    • LeadsProfile
    • Loading
    • Menus
    • Notices
    • PlacementMetabox
    • PostType
    • Templates
    • Tracking
    • Variations
    • YOAST
  • InboundPro
    • Activation
    • AdminAJAX
    • AutoLoading
    • Cron
    • DataInterface
    • FieldMapping
    • Funnels
    • InboundNowAPI
    • Installer
    • LeadStatuses
    • Menus
    • Notifications
    • Ouath
    • Reports
    • Settings
    • Tracking
    • Translations
    • Updates
  • LandingPages
    • Activation
    • DataInterfaces
    • Management
    • Menus
    • NeedsAttention
    • Notices
    • Sidebars
    • Templates
    • Tracking
    • Variations
    • WelcomeScreen
    • Widgets
  • Leads
    • Activation
    • Akismet
    • BranchControl
    • BulkActions
    • Dashboard
    • Management
    • Notifications
    • Settings
    • Tracking
    • UserProfile
    • WPLogin
  • Mailer
    • Activation
    • Admin
    • ClickTracking
    • DataInterface
    • InboundForms
    • Leads
    • Management
    • Notifications
    • Scheduling
    • Sending
    • Settings
    • ShortcodesAndTokens
    • SparkPost
    • Templates
    • Unsubscribes
    • Variations
    • YoastSEO
  • None
  • Shared
    • APIs
    • CPT
    • DatabaseRoutines
    • DebugTricks
    • DoubleOptin
    • EventManagement
    • FieldMapping
    • InboundForms
    • LeadSorage
    • MarketingButton
    • Menus
    • Notifications
    • Shortcodes
    • ShortcodesAndTokens
    • StandAloneLicensing
    • Tracking
    • VisualEditor
  • xDepreciated

Classes

  • CTA_Activation
  • CTA_Activation_Update_Routines
  • CTA_Admin_Notices
  • CTA_Ajax_Listeners
  • CTA_Clone_Post
  • CTA_Conversion_Tracking
  • CTA_Dynamic_Widget
  • CTA_Enqueues
  • CTA_Load_Extensions
  • CTA_Menus
  • CTA_Metaboxes
  • CTA_Metaboxes_Global
  • CTA_Post_Type
  • CTA_Render
  • CTA_Settings
  • CTA_Static_Widget
  • CTA_Template_Manager
  • CTA_Template_Manager_List
  • CTA_Variations
  • CTA_WordPress_Leads
  • CTA_WordPress_SEO
  • Inbound_Ajax
  • Inbound_Akismet
  • Inbound_Analytics
  • Inbound_API
  • Inbound_API_Keys_Generation
  • Inbound_API_Keys_Table
  • Inbound_API_Wrapper
  • Inbound_Asset_Loader
  • Inbound_Automation_Action_Add_Remove_List
  • Inbound_Automation_Action_Add_Remove_Tag
  • Inbound_Automation_Action_Create_Lead
  • Inbound_Automation_Action_Create_User
  • Inbound_Automation_Action_Kill_Tasks
  • Inbound_Automation_Action_Relay_Data
  • Inbound_Automation_Action_Send_Email
  • Inbound_Automation_Action_Wait
  • Inbound_Automation_Activation
  • Inbound_Automation_Activation_Update_Routines
  • Inbound_Automation_Adminbar
  • Inbound_Automation_Lead_Profile
  • Inbound_Automation_Loader
  • Inbound_Automation_Plugin
  • Inbound_Automation_Post_Type
  • Inbound_Automation_Processing
  • Inbound_Automation_Query_Lead
  • Inbound_Automation_Query_User
  • Inbound_Automation_Trigger_inbound_double_optin_confirm
  • Inbound_Automation_Trigger_inbound_store_lead_post
  • Inbound_Automation_Trigger_inbound_track_link
  • Inbound_Automation_Trigger_Publish_Post
  • Inbound_Automation_Trigger_Save_Post_Deactivated
  • Inbound_Automation_Trigger_Set_Object_Terms
  • Inbound_Automation_Trigger_Update_Lead
  • Inbound_Automation_Trigger_User_Register
  • Inbound_Calls_To_Action_Plugin
  • Inbound_Confirm_Double_Optin
  • Inbound_Cron
  • Inbound_CTA_Quick_View
  • Inbound_Customizer
  • Inbound_Debug_Scripts
  • Inbound_Email_Meta
  • Inbound_Email_Preview
  • Inbound_Email_Template_Shortcodes
  • Inbound_Event_Report
  • Inbound_Events
  • Inbound_Events_Report
  • Inbound_Extension_Loads
  • Inbound_Forms
  • Inbound_Funnel_Reporting
  • Inbound_Impressions_Report
  • Inbound_Landing_Pages_Plugin
  • Inbound_Lead_Statuses
  • Inbound_Leads
  • Inbound_Leads_Custom_fields
  • Inbound_Leads_Plugin
  • Inbound_License
  • Inbound_List_Double_Optin
  • Inbound_Load_Shared
  • Inbound_Logging_Automation
  • Inbound_Login
  • Inbound_Mail_Daemon
  • Inbound_Mailer_ACF
  • Inbound_Mailer_Activation
  • Inbound_Mailer_Activation_Update_Routines
  • Inbound_Mailer_Ajax_Listeners
  • Inbound_Mailer_Clone_Post
  • Inbound_Mailer_Common_Settings
  • Inbound_Mailer_Customizer
  • Inbound_Mailer_Direct_Email_Leads
  • Inbound_Mailer_Enqueues
  • Inbound_Mailer_Forms_Integration
  • Inbound_Mailer_Load_Templates
  • Inbound_Mailer_Menus
  • Inbound_Mailer_Metaboxes
  • Inbound_Mailer_Notifications
  • Inbound_Mailer_Plugin
  • Inbound_Mailer_Post_Type
  • Inbound_Mailer_Scheduling
  • Inbound_Mailer_Settings
  • Inbound_Mailer_SparkPost
  • Inbound_Mailer_Stats_Report
  • Inbound_Mailer_Template_Manager
  • Inbound_Mailer_Template_Manager_List
  • Inbound_Mailer_Tokens
  • Inbound_Mailer_Tracking
  • Inbound_Mailer_Unsubscribe
  • Inbound_Mailer_Variations
  • Inbound_Mailer_WordPress_SEO
  • Inbound_Maintenance_Lists
  • Inbound_Marketing_Button
  • Inbound_Menus_Admin
  • Inbound_Menus_Adminbar
  • Inbound_Metaboxes_Automation
  • Inbound_Metaboxes_Leads
  • Inbound_Notifications
  • Inbound_Now_Store
  • Inbound_Options_API
  • Inbound_Pro_Activation
  • Inbound_Pro_Admin_Ajax_Listeners
  • Inbound_Pro_Automatic_Updates
  • Inbound_Pro_Downloads
  • Inbound_Pro_Notifications
  • Inbound_Pro_Oauth_Engine
  • Inbound_Pro_Plugin
  • Inbound_Pro_Settings
  • Inbound_Quick_View
  • Inbound_Reporting_Templates
  • Inbound_Search_And_Comment_Report
  • Inbound_Shared_ACF_BootStrap
  • Inbound_Shortcodes
  • Inbound_Shortcodes_Cookies
  • Inbound_Shortcodes_Fields
  • Inbound_SparkPost
  • Inbound_SparkPost_Stats
  • Inbound_Template_Utils
  • Inbound_Templating_Engine
  • Inbound_Tracking
  • Inbound_Translation_Updater
  • Inbound_Updater
  • Inbound_Upgrade_For_More_Reports
  • Inbound_Upgrade_Routines
  • Inbound_Visitor_Event_Report
  • Inbound_Visitor_Impressions_Report
  • Inbound_Visitors_Report
  • INBOUNDNOW_EXTEND
  • Landing_Pages_ACF
  • Landing_Pages_Activation
  • Landing_Pages_Activation_Update_Routines
  • Landing_Pages_Admin_Menus
  • Landing_Pages_Admin_Notices
  • Landing_Pages_Install
  • Landing_Pages_Load_Extensions
  • Landing_Pages_Meta
  • Landing_Pages_Metaboxes
  • Landing_Pages_Post_Type
  • Landing_Pages_Row_Actions
  • Landing_Pages_Settings
  • Landing_Pages_Sidebars
  • Landing_Pages_Split_Testing_Stats
  • Landing_Pages_Template_Management
  • Landing_Pages_Template_Switcher
  • Landing_Pages_Templates_List_Table
  • Landing_Pages_Variations
  • LandingPages_Welcome
  • Leads_Activation
  • Leads_Activation_Update_Routines
  • Leads_Admin_Notices
  • Leads_Batch_Processor
  • Leads_Branching
  • Leads_Dashboard
  • Leads_Field_Map
  • Leads_Manager
  • Leads_Post_Type
  • Leads_Settings
  • Leads_Tracking
  • Leads_User_Profile
  • LeadStorage
  • LP_EXTENSION_LICENSENING
  • LP_EXTENSION_UPDATER
  • LP_Variation_Rotation
  • LP_Widget_Conversion_Area

Functions

  • cta_check_active
  • cta_example_template_function
  • cta_load_dynamic_widget
  • CTA_Load_Extensions
  • cta_load_static_widget
  • CTA_Render
  • inbound_add_conversion_to_lead
  • inbound_automation_check_active
  • inbound_automation_load_definitions
  • inbound_automation_metaboxes
  • inbound_automation_processing
  • inbound_color
  • inbound_color_scheme
  • inbound_confirm_email_service_provider
  • inbound_email_kill_ie8
  • inbound_email_load_templates
  • inbound_form_add_lead_list
  • inbound_form_auto_publish
  • inbound_form_delete_transient
  • inbound_form_get_data
  • inbound_form_save
  • inbound_forms_change_columns
  • inbound_forms_cpt
  • inbound_forms_custom_columns
  • inbound_forms_default_content
  • inbound_get_form_names
  • inbound_get_parent_directory
  • inbound_Hex_2_RGB
  • inbound_inbound_email_example_template_function
  • inbound_load_lead_manager
  • inbound_load_token_engine
  • inbound_mailer_acf_integration
  • Inbound_Mailer_Common_Settings
  • Inbound_Mailer_Load_Templates
  • inbound_qtrans_disable
  • inbound_record_log
  • inbound_register_form_role_capabilities
  • inbound_shortcode_alert
  • inbound_shortcode_callout
  • inbound_shortcode_columns
  • inbound_shortcode_content_box
  • inbound_shortcode_divider
  • inbound_shortcode_empty_paragraph_fix
  • inbound_shortcode_four_fifth_columns
  • inbound_shortcode_full_columns
  • inbound_shortcode_gmap
  • inbound_shortcode_icon
  • inbound_shortcode_intro
  • inbound_shortcode_landing_pages
  • inbound_shortcode_leadp
  • inbound_shortcode_list_icons
  • inbound_shortcode_one_fifth_columns
  • inbound_shortcode_one_fourth_columns
  • inbound_shortcode_one_half_columns
  • inbound_shortcode_one_third_columns
  • inbound_shortcode_portfolio
  • inbound_shortcode_pricing
  • inbound_shortcode_profile
  • inbound_shortcode_social_links
  • inbound_shortcode_tabs
  • inbound_shortcode_teaser
  • inbound_shortcode_testimonial
  • inbound_shortcode_three_fifth_columns
  • inbound_shortcode_three_fourth_columns
  • inbound_shortcode_two_fifth_columns
  • inbound_shortcode_two_third_columns
  • inbound_shortcode_video
  • inbound_store_lead
  • inbound_template_brightness
  • inbound_template_color
  • Inbound_Templating_Engine
  • inbound_travis_check
  • inboundnow_add_master_license
  • json_encode_fallback
  • landingpage_fix_known_wp_title_isses
  • landingpages_is_active
  • load_CTA_Settings
  • load_CTA_Template_Manager
  • load_Inbound_API_Keys_Generation
  • load_Inbound_Lead_Statuses
  • load_Inbound_Leads_Custom_fields
  • load_inbound_mail_daemon
  • load_Inbound_Mailer_Settings
  • load_Inbound_Mailer_Template_Manager
  • load_Inbound_Pro_Downloads
  • lp_ab_testing_get_current_variation_id
  • lp_add_option
  • lp_body_class
  • lp_check_active
  • lp_content_area
  • lp_conversion_area
  • lp_discover_important_wrappers
  • lp_footer
  • lp_generate_drowndown
  • lp_get_parent_directory
  • lp_get_value
  • lp_global_config
  • lp_head
  • lp_in_admin_header
  • lp_init
  • lp_list_feature
  • lp_load_widgets
  • lp_main_headline
  • lp_manage_templates
  • lp_move_template_files
  • lp_rebuild_attributes
  • lp_templates_upload
  • mailer_check_active
  • wp_cta_check_active
  • wp_cta_kill_ie8
  • wp_cta_load_calls_to_action
  • wp_leads_get_page_final_id
  • wpl_url_to_postid
  • wpleads_add_lead_to_list
  • wpleads_check_active
  • wpleads_get_lead_lists_as_array
  • Overview
  • Package
  • Class
  1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673: 674: 675: 676: 677: 678: 679: 680: 681: 682: 683: 684: 685: 686: 687: 688: 689: 690: 691: 692: 693: 694: 695: 696: 697: 698: 699: 700: 701: 702: 703: 704: 705: 706: 707: 708: 709: 710: 711: 712: 713: 714: 715: 716: 717: 718: 719: 720: 721: 722: 723: 724: 725: 726: 727: 728: 729: 730: 731: 732: 733: 734: 735: 736: 737: 738: 739: 740: 741: 742: 743: 744: 745: 746: 747: 748: 749: 750: 751: 752: 753: 754: 755: 756: 757: 758: 759: 760: 761: 762: 763: 764: 765: 766: 767: 768: 769: 770: 771: 772: 773: 774: 775: 776: 777: 778: 779: 780: 781: 782: 783: 784: 785: 786: 787: 788: 789: 790: 791: 792: 793: 794: 795: 796: 797: 798: 799: 800: 801: 802: 803: 804: 805: 806: 807: 808: 809: 810: 811: 812: 813: 814: 815: 816: 817: 818: 819: 820: 821: 822: 823: 824: 825: 826: 827: 828: 829: 830: 831: 832: 833: 834: 835: 836: 837: 838: 839: 840: 841: 842: 843: 844: 845: 846: 847: 848: 849: 850: 851: 852: 853: 854: 855: 856: 857: 858: 859: 860: 861: 862: 863: 864: 865: 866: 867: 868: 869: 870: 871: 872: 873: 874: 875: 876: 877: 878: 879: 880: 881: 882: 883: 884: 885: 886: 887: 888: 889: 890: 891: 892: 893: 894: 895: 896: 897: 898: 899: 900: 901: 902: 903: 904: 905: 906: 907: 908: 909: 910: 911: 912: 913: 914: 915: 916: 917: 918: 919: 920: 921: 922: 923: 924: 925: 926: 927: 928: 929: 930: 931: 932: 933: 934: 935: 936: 937: 938: 939: 940: 941: 942: 943: 944: 945: 946: 947: 948: 949: 950: 951: 952: 953: 954: 955: 956: 957: 958: 959: 960: 961: 962: 963: 964: 965: 966: 967: 968: 969: 970: 971: 972: 973: 974: 975: 976: 977: 978: 979: 980: 981: 982: 983: 984: 985: 986: 987: 988: 989: 990: 991: 
<?php

/**
 * Class Inbound_SparkPost_Stats provides webhook listeners and data storage and retrieval methods related to email stats
 *
 * @package Mailer
 * @subpackage  SparkPost
 */


class Inbound_SparkPost_Stats {

    static $settings; /* email settings */
    static $results; /* results returned from sparkpost */
    static $email_id; /* email id being processed */
    static $vid; /* variation id being processed */
    static $stats; /* stats array */
    static $timemarker; /* marks time of last api call */

    public function __construct() {
        self::add_hooks();
    }

    public static function add_hooks() {
        if (is_admin()) {
            /* For mail service activation */
            add_action('inbound-settings/after-field-value-update', array(__CLASS__, 'sparkpost_activation_routines'));

            add_action( 'mailer/unschedule-email' , array( __CLASS__, 'unschedule_email' ) , 10 , 1 );
        }

        /* For processing webhooks */
        add_action('wp_ajax_nopriv_sparkpost_webhook', array(__CLASS__, 'process_webhook'));

        /* process send event */
        add_action( 'sparkpost/send/response' , array( __CLASS__ , 'process_send_event') , 10 , 2 );

        /* process rejection errors */
        add_action( 'sparkpost/send/response' , array( __CLASS__ , 'process_rejections') , 10 , 2 );
    }


    /**
     *  Get SparkPost Stats including varition totals
     */
    public static function get_sparkpost_webhook_stats() {
        global $post, $Inbound_Mailer_Variations;

        /* prepare date range */
        self::prepare_date_range();

        /* get user saved job id for automated email */
        if ($post->post_status=='automated') {
            $job_id = get_user_option(
                'inbound_mailer_reporting_job_id_' .$post->ID,
                get_current_user_id()
            );
        } else {
            $job_id = null;
        }

        /* first get totals */
        self::get_sparkpost_inbound_events( $post->ID , $vid = null , $job_id  );

        /* now total variations */
        $variations = $Inbound_Mailer_Variations->get_variations($post->ID, $vid = null );

        foreach ( $variations as $vid => $variation ) {
            self::get_sparkpost_inbound_events( $post->ID , $vid , $job_id );
        }

        return self::$stats;
    }

    /**
     * Get all all custom event data by a certain indicator
     */
    public static function get_sparkpost_inbound_events( $email_id , $variation_id = null , $job_id = null ) {
        global $wpdb, $post, $inbound_settings;

        /* check if email id is set else use global post object */
        if ($email_id) {
            $post = get_post($email_id);
        }

        /* whitelist of email statuses we prepare statistics for */
        if (!in_array($post->post_status, array('sent', 'sending', 'automated', 'direct_email'))) {
            return array();
        }

        /* get email setup data */
        $settings = Inbound_Email_Meta::get_settings($post->ID);
        $settings['send_datetime'] = (isset($settings['send_datetime'])) ? $settings['send_datetime'] : '';
        $table_name = $wpdb->prefix . "inbound_events";
        $variation_query = '';
        $job_id_query = '';

        /* check if automated email has a job id saved */
        if ($post->post_status=='automated') {

            /* account for last_send */
            $job_id = ($job_id == 'last_send') ?Inbound_Mailer_Post_Type::get_last_job_id($email_id) : $job_id ;

            /* add job id to the query if not zero or false */
            if ($job_id) {
                $job_id_query = ' AND job_id="' . $job_id . '" ';
            }
        }

        /* Add variation id to the query if it's present */
        if (is_numeric($variation_id)) {
            $variation_query = ' AND variation_id="' . $variation_id . '" ';
        }

        /* get deliveries */
        $wordpress_date_time =  date_i18n('Y-m-d G:i:s');
        $today = new DateTime($wordpress_date_time);
        $schedule_date = new DateTime($settings['send_datetime']);
        $interval = $today->diff($schedule_date);

        /* complicated  - needs doc */
        if ( !$settings['send_datetime'] || $interval->format('%R') == '-' || $settings['email_type'] == 'automated' ) {
            $query = 'SELECT `variation_id`, `lead_id` FROM ' . $table_name . ' WHERE `email_id` = "' . $email_id . '"  ' . $variation_query . $job_id_query . ' AND `event_name` =  "sparkpost_delivery"';

            /* add date constraints if applicable */
            if (isset(self::$stats['start_date'])) {
                $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
            }
            $results = $wpdb->get_results($query, ARRAY_A);

            /*get the unique lead_id sends for each variation*/
            $sent_array = array();
            foreach( $results as $index => $rows ){
                if(!isset($sent_array[$rows['variation_id']][$rows['lead_id']])){
                    $sent_array[$rows['variation_id']][$rows['lead_id']] = 1;
                }
            }
            $sent = (count($sent_array, 1) - count($sent_array));
        } else {
            $sent = 0;
        }

        /* get opens */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' AND `event_name` =  "sparkpost_open"';
        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $opens = self::process_selected_rows($results);

        /* get clicks */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' AND `event_name` =  "sparkpost_click"';
        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $clicks = self::process_selected_rows($results);

        /* get bounce */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' AND `event_name` =  "sparkpost_bounce"';
        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $bounces = self::process_selected_rows($results);

        /* get rejects */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' ';
        $query .= ' AND ( `event_name` =  "sparkpost_rejected" OR `event_name` = "sparkpost_relay_rejection" )';

        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $rejects = self::process_selected_rows($results);

        /* get spam complaints */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' AND `event_name` =  "sparkpost_spam_complaint"';
        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $complaints = self::process_selected_rows($results);

        /* get unsubscribes */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' AND `event_name` =  "inbound_unsubscribe"';
        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $unsubs = self::process_selected_rows($results);

        /* get mutes */
        $query = 'SELECT `variation_id`, `lead_id` FROM '.$table_name.' WHERE `email_id` = "'.$email_id.'"  '. $variation_query . $job_id_query.' AND `event_name` =  "inbound_mute"';
        /* add date constraints if applicable */
        if (isset(self::$stats['start_date'])) {
            $query .= ' AND datetime >= "'.self::$stats['start_date'].'" AND  datetime <= "'.self::$stats['end_date'].'" ';
        }
        $results = $wpdb->get_results( $query, ARRAY_A );
        $mutes = self::process_selected_rows($results);


        $totals = array(
            'sent' => $sent,
            'opens' =>$opens,
            'clicks' => $clicks,
            'bounces' => $bounces,
            'rejects' => $rejects,
            'complaints' => $complaints,
            'unsubs' => $unsubs,
            'mutes' => $mutes,
            'unique_opens' => $opens,
            'unique_clicks' => $clicks,
            'unopened' => $sent - $opens
        );

        if ( is_numeric($variation_id) ) {
            self::$stats[ 'totals' ][ 'variations' ][ $variation_id ] = $totals;
            self::$stats[ 'totals' ][ 'variations' ][ $variation_id ][ 'label' ] =  Inbound_Mailer_Variations::vid_to_letter( $email_id , $variation_id );
        } else {
            self::$stats[ 'totals' ] = $totals;
        }

        return self::$stats;
    }

    /**
     * Processes queried rows into action counts
     */
    public static function process_selected_rows($query){

        /*get the unique lead_id sends for each variation*/
        $action_count = array();
        foreach( $query as $index => $rows ){
            if(!isset($action_count[$rows['variation_id']][$rows['lead_id']])){
                $action_count[$rows['variation_id']][$rows['lead_id']] = 1;
            }
        }

        /* count recursivly first, then remove the counted variation ids*/
        $counted_actions = (count($action_count, 1) - count($action_count));

        return $counted_actions;
    }

    /**
     *  Get stats object from db
     */
    public static function get_statistics_object() {
        global $post;

        //delete_post_meta( $post->ID , 'inbound_statistics'  );
        $stats = get_post_meta( $post->ID , 'inbound_statistics' , true );

        self::$stats = ($stats) ? $stats : array( 'sparkpost' => array() );
    }

    /**
     *  Converts gmt timestamps to correct timezones
     *  @param DATETIME $timestamp timestamp in gmt before calculating timezone
     */
    public static function get_sparkpost_timestamp( $timestamp ) {

        /* make sure we have a timezone set */
        $tz = Inbound_Mailer_Scheduling::get_current_timezone();
        self::$settings['timezone'] = (!empty(self::$settings['timezone'])) ? self::$settings['timezone'] :  $tz['abbr'] . '-UTC' . $tz['offset'];

        $sparkpost_timestamp = date( 'c' , strtotime( $timestamp ) );
        $date_parts = explode('+' , $sparkpost_timestamp );

        // $timezone_parts = explode('UTC' , self::$settings['timezone'] );

        $sparkpost_timestamp = $date_parts[0];
        $date_parts = explode(':' , $sparkpost_timestamp );
        array_pop($date_parts);

        $sparkpost_timestamp = implode(':', $date_parts);

        return $sparkpost_timestamp;
    }

    /**
     * Pull data from Mandrill based on email id and variation id
     *
     */
    public static function get_send_stream() {
        global $Inbound_Mailer_Variations;
        global $inbound_settings;
        global $post;

        self::$vid = $Inbound_Mailer_Variations->get_current_variation_id();

        $campaign_id =  $post->ID   . '_'. self::$vid;
        $sparkpost = new Inbound_SparkPost(  $inbound_settings['mailer']['sparkpost-key'] );
        self::$results = $sparkpost->get_transmissions( $campaign_id );

        return self::$results;
    }


    /**
     *  Timezone check
     */
    public static function timezone_check( $timezone ) {
        if ($timezone) {
            return $timezone;
        }

        switch( self::$settings['timezone'] ) {
            case 'BIT-UTC-12' :
                return '';
                break;
        }
    }

    /**
     *  Update db stats object
     */
    public static function update_statistics_object() {
        global $post;

        //delete_post_meta( $post->ID , 'inbound_statistics'  );
        //error_log(print_r(self::$stats,true));
        update_post_meta( $post->ID , 'inbound_statistics' , self::$stats );

    }


    /**
     *  build variation totals
     */
    public static function process_variation_totals() {
        $batch_key_parts = explode('T' , self::$stats['date_to'] );
        $batch_key = $batch_key_parts[0];

        /* skip processing if no data */
        if (!isset(self::$results['results'])) {
            self::$stats['sparkpost'][$batch_key][ 'variations' ] = array();
            return;
        }

        /* loop through sparkpost object & compile hour totals to build variation totals */
        foreach ( self::$results['results'] as $i => $totals ) {
            $campaign_parts = explode('_' , $totals['campaign_id'] );
            $vid = $campaign_parts[1];

            self::$stats['sparkpost'][$batch_key][ 'variations' ][ $vid ] = array(
                'sent' => $totals['count_sent'],
                'opens' => $totals['count_rendered'],
                'clicks' => $totals['count_unique_clicked'],
                'bounces' => $totals['count_bounce'],
                'hard_bounces' => $totals['count_hard_bounce'],
                'soft_bounces' => $totals['count_soft_bounce'],
                'rejects' => $totals['count_rejected'],
                'complaints' => $totals['count_spam_complaint'],
                'unique_opens' => $totals['count_unique_rendered'],
                'unique_clicks' => $totals['count_unique_clicked'],
                'unopened' => $totals['count_sent']
            );

        }


    }

    /**
     *  Prepares dates to process
     */
    public static function prepare_date_range() {
        $range = get_user_option(
            'inbound_mailer_screen_option_range',
            get_current_user_id()
        );


        $range = ($range) ? $range : 90;

        /* create date objects */
        $start_date = new DateTime();
        $start_date->modify('-'.$range.' days');
        self::$stats['start_date'] = $start_date->format('Y-m-d G:i:s T');

        $end_date = new DateTime();
        self::$stats['end_date'] = $end_date->format('Y-m-d G:i:s T');

    }

    /**
     *  Totals variation stats to create an aggregated statistic total_stat
     *  @param ARRAY $stats array of variations with email statics
     *  @returns ARRAY $stats array of variations with email statics and aggregated statistics
     */
    public static function prepare_totals(  ) {

        self::$stats[ 'totals' ] = array(
            'sent' => 0,
            'opens' => 0,
            'clicks' => 0,
            'bounces' => 0,
            'hard_bounces' => 0,
            'soft_bounces' => 0,
            'rejects' => 0,
            'complaints' => 0,
            'unsubs' => 0,
            'mutes' => 0,
            'unique_opens' => 0,
            'unique_clicks' => 0,
            'opens' => 0,
            'unopened' => 0
        );

        /* skip processing if no data */
        if (!isset(self::$stats['sparkpost'])) {
            return;
        }

        foreach (self::$stats['sparkpost'] as $block_key => $data ) {

            /* prepare default counters for variations */
            foreach ($data['variations'] as $vid => $totals ) {
                self::$stats['totals']['variations'][$vid] = array(
                    'sent' => 0,
                    'opens' => 0,
                    'clicks' => 0,
                    'bounces' => 0,
                    'hard_bounces' => 0,
                    'soft_bounces' => 0,
                    'rejects' => 0,
                    'complaints' => 0,
                    'unsubs' => 0,
                    'mutes' => 0,
                    'unique_opens' => 0,
                    'unique_clicks' => 0,
                    'opens' => 0,
                    'unopened' => 0
                );
            }

            foreach ($data['variations'] as $vid => $totals ) {

                self::$stats['totals']['sent'] = self::$stats['totals']['sent'] + $totals['sent'];
                self::$stats['totals']['opens'] = self::$stats['totals']['opens'] + $totals['opens'];
                self::$stats['totals']['clicks'] = self::$stats['totals']['clicks'] + $totals['clicks'];
                self::$stats['totals']['bounces'] = self::$stats['totals']['bounces'] + $totals['bounces'];
                self::$stats['totals']['hard_bounces'] = self::$stats['totals']['hard_bounces'] + $totals['hard_bounces'];
                self::$stats['totals']['soft_bounces'] = self::$stats['totals']['soft_bounces'] + $totals['soft_bounces'];
                self::$stats['totals']['rejects'] = self::$stats['totals']['rejects'] + $totals['rejects'];
                self::$stats['totals']['complaints'] = self::$stats['totals']['complaints'] + $totals['complaints'];
                self::$stats['totals']['unique_opens'] = self::$stats['totals']['unique_opens'] + $totals['unique_opens'];
                self::$stats['totals']['unique_clicks'] = self::$stats['totals']['unique_clicks'] + $totals['unique_clicks'];
                //print_r(self::$stats);exit;

                self::$stats['totals']['variations'][$vid]['sent'] = self::$stats['totals']['variations'][$vid]['sent'] + $totals['sent'];
                self::$stats['totals']['variations'][$vid]['clicks'] = self::$stats['totals']['variations'][$vid]['clicks'] + $totals['clicks'];
                self::$stats['totals']['variations'][$vid]['bounces'] = self::$stats['totals']['variations'][$vid]['bounces'] + $totals['bounces'];
                self::$stats['totals']['variations'][$vid]['hard_bounces'] = self::$stats['totals']['variations'][$vid]['hard_bounces'] + $totals['hard_bounces'];
                self::$stats['totals']['variations'][$vid]['soft_bounces'] = self::$stats['totals']['variations'][$vid]['soft_bounces'] + $totals['soft_bounces'];
                self::$stats['totals']['variations'][$vid]['rejects'] = self::$stats['totals']['variations'][$vid]['rejects'] + $totals['rejects'];
                self::$stats['totals']['variations'][$vid]['complaints'] = self::$stats['totals']['variations'][$vid]['complaints'] + $totals['complaints'];
                self::$stats['totals']['variations'][$vid]['opens'] = self::$stats['totals']['variations'][$vid]['opens'] + $totals['opens'];
                self::$stats['totals']['variations'][$vid]['unique_opens'] = self::$stats['totals']['variations'][$vid]['unique_opens'] + $totals['unique_opens'];
                self::$stats['totals']['variations'][$vid]['unique_clicks'] = self::$stats['totals']['variations'][$vid]['unique_clicks'] + $totals['unique_clicks'];

                /* add label */
                self::$stats['totals']['variations'][ $vid ][ 'label' ] =   Inbound_Mailer_Variations::vid_to_letter( self::$email_id , $vid );

                /* add subject line */
                self::$stats['totals']['variations'][ $vid ][ 'subject' ] = self::$settings['variations'][ $vid ][ 'subject' ];

                /* add unopened */
                self::$stats['totals']['variations'][ $vid ]['unopened'] = self::$stats['totals']['variations'][$vid]['sent']   - self::$stats['totals']['variations'][$vid]['opens'];
            }

        }


        /* calculate unopened */
        self::$stats['totals']['unopened'] = self::$stats['totals']['sent'] - self::$stats['totals']['opens'];
        self::$stats['totals']['unsubs'] = self::prepare_unsubscribes();
        self::$stats['totals']['mutes'] = self::prepare_mutes();


    }

    /**
     *  Returns an array of zeros for email statistics
     */
    public static function prepare_empty_stats() {

        return array(
            'sends' => 0,
            'opens' => 0,
            'unopened' => 0,
            'clicks' => 0
        );

    }

    /**
     *  Returns an array of zeros for email statistics
     */
    public static function prepare_unsubscribes(  ) {

        global $post;


        return Inbound_Events::get_unsubscribes_count_by_email_id( $post->ID  );


    }

    /**
     *  Returns an array of zeros for email statistics
     */
    public static function prepare_mutes(  ) {

        global $post;


        return Inbound_Events::get_mutes_count_by_email_id( $post->ID  );


    }

    /**
     *
     */
    public static function create_sparkpost_webhooks($field) {
        global $inbound_settings;

        /* load SparkPost connector */
        $sparkpost = new Inbound_SparkPost(  $field['value'] );

        $inbound_settings['mailer']['sparkpost-key'] = $field['value'];

        /* check if webhook is already created */
        if (isset($inbound_settings['mailer']['sparkpost']['webhook']['id']) ) {

            $webhook = $sparkpost->get_webhook($inbound_settings['mailer']['sparkpost']['webhook']['id']);

            if ( isset($webhook['results']['name']) && $webhook['results']['name'] == 'Inbound Now Webhook' ) {

                return;
            }
        }

        /* create webhook location and save it */
        $url = add_query_arg(
            array(
                'action' => 'sparkpost_webhook' ,
                'fast_ajax' => true ,
                'load_plugins' => '["inbound-pro/inbound-pro.php"]'
            ),
            admin_url('admin-ajax.php')
        );

        self::$results = $sparkpost->create_webhook( array(
            'name' => 'Inbound Now Webhook',
            'events' => array(
                'bounce',
                'open',
                'click',
                'relay_rejection',
                'generation_rejection',
                'spam_complaint'
            ),
            'target' => $url,
            'auth_type' => 'basic',
            'auth_credentials' => array(
                'username' => preg_replace("/[^A-Za-z0-9 ]/", '', AUTH_KEY),
                'password' => preg_replace("/[^A-Za-z0-9 ]/", '', AUTH_SALT)
            )
        ) );


        if (isset(self::$results['results'])) {
            $inbound_settings['mailer']['sparkpost']['webhook'] = self::$results['results'];
        } else {
            $inbound_settings['mailer']['sparkpost']['webhook'] = self::$results;
        }

        Inbound_Options_API::update_option('inbound-pro', 'settings', $inbound_settings);

    }

    /**
     * @param $field
     */
    public static function sparkpost_activation_routines( $field ) {

        if (!isset($field['sparkpost-key'])) {
            return;
        }

        Inbound_SparkPost_Stats::create_sparkpost_webhooks($field);

    }

    public static function process_webhook() {

        $data = stripslashes(file_get_contents("php://input"));

        $events = json_decode($data,true);

        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            error_log('PHP_AUTH_USER not detected');
            return;
        }

        $auth_user = preg_replace( "/[^A-Za-z0-9 ]/", '', AUTH_KEY );
        $auth_pass = preg_replace( "/[^A-Za-z0-9 ]/", '', AUTH_SALT );


        if ( $auth_user != $_SERVER['PHP_AUTH_USER'] ) {
            return;
        }

        if ( $auth_pass != $_SERVER['PHP_AUTH_PW'] ) {
            return;
        }

        if (!is_array($events)) {
            error_log('Events empty?');
            error_log($events);
            error_log($data);
            return;
        }

        foreach ($events as $i => $event) {


            if (isset($event['msys']['message_event'])) {
                $event = $event['msys']['message_event'];
            }

            if (isset($event['msys']['track_event'])) {
                $event = $event['msys']['track_event'];
            }


            if ( $event['campaign_id'] == 'test') {
                return;
            }

            if (!isset($event['rcpt_meta']['email_id'])) {
                return;
            }

            if ($event['type'] == 'delivery') {
                continue;
            }

            $args = array(
                'event_name' => 'sparkpost_' . $event['type'],
                'email_id' => $event['rcpt_meta']['email_id'],
                'variation_id' =>  $event['rcpt_meta']['variation_id'],
                'form_id' => '',
                'lead_id' => $event['rcpt_meta']['lead_id'],
                'job_id' => (isset($event['rcpt_meta']['job_id'])) ? $event['rcpt_meta']['job_id'] : 0,
                'rule_id' => (isset($event['rcpt_meta']['rule_id'])) ? $event['rcpt_meta']['rule_id'] : 0,
                'session_id' => '',
                'event_details' => json_encode($event)
            );

            /* lets not spam our events table with repeat opens and clicks */
            if (!Inbound_Events::event_exists($args)) {
                Inbound_Events::store_event($args);
            }


            /* handle rejections */
            if ($event['type'] == 'spam_compaint') {

                $maintenance_lists = Inbound_Maintenance_Lists::get_lists();

                /* add to spam complaint list */
                Inbound_Leads::add_lead_to_list( $event['rcpt_meta']['lead_id'], $maintenance_lists['spam']['id'] );
            }

            /* handle bounces */
            if ($event['type'] == 'bounce') {

                /* create/get maintenance lists */
                $maintenance_lists = Inbound_Maintenance_Lists::get_lists();

                /* add to spam complaint list */
                Inbound_Leads::add_lead_to_list( $event['rcpt_meta']['lead_id'], $maintenance_lists['bounce']['id'] );


            }

        }

    }

    /**
     * Check SparkPost Response for Errors and Handle them
     */
    public static function process_send_event( $transmission_args , $response ) {

        /* skip if contains errors */
        if (isset($response['errors'])) {
            error_log(print_r($errors,true));
            return;
        }

        if (isset($transmission_args['recipients'][0]['tags']) && in_array( 'test' , $transmission_args['recipients'][0]['tags']) ) {

            return;
        }

        /* clear funnel from session if it exists */
        $_SESSION['inbound_page_views'] = "";

        /* recipients */
        $args = array(
            'event_name' => 'sparkpost_delivery',
            'email_id' => $transmission_args['metadata']['email_id'],
            'variation_id' =>  $transmission_args['metadata']['variation_id'],
            'form_id' => '',
            'lead_id' => $transmission_args['metadata']['lead_id'],
            'rule_id' => $transmission_args['metadata']['rule_id'],
            'job_id' => $transmission_args['metadata']['job_id'],
            'session_id' => '',
            'event_details' => json_encode($transmission_args)
        );

        /* lets not spam our events table with repeat opens and clicks */
        if (!Inbound_Events::event_exists($args)) {
            Inbound_Events::store_event($args);
        }

    }

    /**
     * Check SparkPost Response for Errors and Handle them
     */
    public static function process_rejections( $transmission_args , $response ) {
        if (isset($response['errors']) || !isset($transmission_args['metadata']['lead_id'])) {
            error_log(print_r($response['errors'],true));
            return;
        } else {
            $response['errors'] = array();
        }

        foreach ($response['errors'] as $error) {

            switch( $error['code'] ) {
                case '1902':

                    /* create/get maintenance lists */
                    $maintenance_lists = Inbound_Maintenance_Lists::get_lists();

                    /* add to rejected list */
                    Inbound_Leads::add_lead_to_list( $transmission_args['metadata']['lead_id'], $maintenance_lists['rejected']['id'] );

                    $args = array(
                        'event_name' => 'sparkpost_rejected',
                        'email_id' => $transmission_args['metadata']['email_id'],
                        'variation_id' =>  $transmission_args['metadata']['variation_id'],
                        'form_id' => '',
                        'lead_id' => $transmission_args['metadata']['lead_id'],
                        'session_id' => '',
                        'event_details' => json_encode($error)
                    );

                    /* lets not spam our events table with repeat opens and clicks */
                    if (!Inbound_Events::event_exists($args)) {
                        Inbound_Events::store_event($args);
                    }
                    break;
            }
        }

    }

    public static function unschedule_email( $email_id ) {
        global $inbound_settings;

        $variations = Inbound_Mailer_Variations::get_variations($email_id);
        $sparkpost = new Inbound_SparkPost(  $inbound_settings['mailer']['sparkpost-key'] );

        foreach ($variations as $vid => $variation) {

            $campaign_id =  $email_id   . '_'. $vid;
            $results = $sparkpost->get_transmissions( $campaign_id );

            $delete_count = 0;
            foreach ($results['results'] as $key=>$transmission) {

                if ($transmission['state'] != 'submitted' ) {
                    continue;
                }

                $result = $sparkpost->delete_transmission( $transmission['id'] );

                $delete_count++;
            }
        }

    }

    /**
     * Display API status inside settings area
     * @param $field
     */
    public static function display_api_status( $field ) {
        global $inbound_settings;

        /* do nothing if no key present */
        if (!isset($inbound_settings['mailer']['sparkpost-key'])) {
            return;
        }

        /* set the sparkpost apikey and load sparkpost connector */
        $sparkpost = new Inbound_SparkPost(  $inbound_settings['mailer']['sparkpost-key'] );

        /* discover sending domains */
        $domains = $sparkpost->get_domains();
        $webhooks = $sparkpost->get_webhooks();


        /* check if webhooks are created */
        $webhook_status = __('not created' , 'inbound-pro');
        if (isset($inbound_settings['mailer']['sparkpost']['webhook']['id']) ) {
            $webhook = $sparkpost->get_webhook($inbound_settings['mailer']['sparkpost']['webhook']['id']);

            if ( isset($webhook['results']['name']) && $webhook['results']['name'] == 'Inbound Now Webhook' ) {
                $webhook_status = '<span style="color:green;!important;">'.__('created' , 'inbound-pro') . '</span>';
            }
        } else if (isset($webhooks['results']) && count($webhooks['results']) > 0 ) {
            /* If for any reason we lost data and the webhooks still exist lets find them and update the data */
            foreach ($webhooks['results'] as $key => $webhook) {

                if ( $webhook['name'] != 'Inbound Now Webhook') {
                    continue;
                }

                if (!strstr($webhook['target'] , site_url() )) {
                    continue;
                }

                $inbound_settings['mailer']['sparkpost']['webhook']['id'] = $webhook['id'];

                Inbound_Options_API::update_option('inbound-pro', 'settings', $inbound_settings);
                $webhook_status = '<span style="color:green;!important;">'.__('created' , 'inbound-pro') . '</span>';
            }
        }

        ?>
        <table class="sparkpost-status-table">
            <tr>
                <td class="inbound-label-field">
                    <?php _e('API Key:','inbound-pro'); ?>
                </td>
                <td class="">

                    <?php

                    if (isset($domains['results']) && is_array($domains['results']) ){
                        echo '<span style="color:green !important;">'.__('active' , 'inbound-pro') . '</span>';
                    } else {
                        if (isset($domains['errors'])) {
                            switch($domains['errors'][0]['message']) {
                                case 'Unauthorized.':
                                    echo '<pre>'.__('invalid' , 'inbound-pro') . '</pre>';

                                    break;
                                case 'Forbidden.':
                                    echo '<pre>'.__('API Key does not have correct permissions checked. Try creating a new key and checking all the available permissions.' , 'inbound-pro') . '</pre>';

                                    break;
                            }
                        }
                    }

                    ?>

                </td>

            </tr>
        </table>
        <table>
            <tr>
                <td class="inbound-label-field">
                    <?php _e('Sending Domains:','inbound-pro'); ?>
                </td>

                <td class="sparkpost-status-domains status-value">
                    <table>
                        <?php

                        if (isset($domains['results']) && is_array($domains['results']) ){
                            foreach($domains['results'] as $i => $domains ) {

                                ?>

                                <tr>
                                    <td class="inbound-label-field" style='' colspan="2">
                                        <span style="color:green !important;"><?php echo $domains['domain']; ?></span>
                                    </td>

                                </tr>
                                <tr>
                                    <td class="inbound-label-field" style=''>
                                        <?php _e('ownership','inbound-pro'); ?>:
                                    </td>

                                    <td class="status-value">
                                        <?php
                                        if ($domains['status']['ownership_verified']) {
                                            echo '<span style="color:green !important;">'.__('confirmed','inbound-pro').'</span>';
                                        } else {
                                            echo '<span style="color:red !important;">'.__('not confirmed','inbound-pro').'</span>';
                                        }
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="inbound-label-field" style=''>
                                        <?php _e('dkim','inbound-pro'); ?>:
                                    </td>

                                    <td class="status-value">
                                        <?php
                                        if ($domains['status']['dkim_status'] == 'valid' ) {
                                            echo '<span style="color:green !important;">'.__('valid','inbound-pro').'</span>';
                                        } else {
                                            echo '<span style="color:red !important;">'.__('invalid','inbound-pro').'</span>';
                                        }
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="inbound-label-field" style=''>
                                        <?php _e('compliance status','inbound-pro'); ?>
                                    </td>

                                    <td class="status-value">
                                        <?php
                                        if ($domains['status']['compliance_status'] == 'valid' ) {
                                            echo '<span style="color:green !important;">'.__('valid','inbound-pro').'</span>';
                                        } else {
                                            echo '<span style="color:red !important;">'.__('invalid','inbound-pro').'</span>';
                                        }
                                        ?>
                                    </td>
                                </tr>

                                <?php
                            }

                        } else {
                            echo __( 'No sending domains set. Please see https://app.sparkpost.com/account/sending-domains' , 'inbound-pro' );
                        }

                        ?>
                    </table>
                </td>

            </tr>
        </table>

        <table>
            <tr>
                <td class="inbound-label-field">
                    <?php _e('Webhooks:','inbound-pro'); ?>
                </td>

                <td class="sparkpost-status-webhooks status-value">
                    <?php echo  $webhook_status; ?>
                    <?php if(isset($inbound_settings['mailer']['sparkpost']['webhook']['errors'])) {
                        print_r($inbound_settings['mailer']['sparkpost']['webhook']);
                    }
                    ?>
                </td>

            </tr>
        </table>
        <?php
    }
}

new Inbound_SparkPost_Stats();
Inbound Pro Plugin - PHP Codex API documentation generated by ApiGen