<?php
/*
Plugin Name: GAM Ad Inserter - Adx & Ad Manager Ads
Plugin URI: https://gamadinserter.com/
Description: Easily place and manage Google Ad Manager (GAM) and AdX ads in WordPress—without editing theme files. Add Sticky, interstitial, pop ups, rewarded, Anchor, Banner ads and control placements, and update ad units from a clean, user-friendly dashboard built for publishers.
Version: 1.2.6
Author: Magicbid.ai
Author URI: https://Magicbid.ai/
Text Domain: gam-ads-ad-manager-and-ad-exchange
License: GPL-2.0-or-later
License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/*
* The plugin uses gam_ads_ad_manager_and_ad_exchange and gamadsmbai as a prefix of the plugin.
* The PCP plugin saying that's incorrect but we think both are valid prefix.
* Please guide us if we are wrong about prefix.
*/

define('gamadsmbai_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('gamadsmbai_PLUGIN_URL', plugin_dir_url(__FILE__));
define('gamadsmbai_PLUGIN_VERSION', '1.3.9');

register_activation_hook(__FILE__, 'gam_ads_ad_manager_and_ad_exchange_activate');
register_deactivation_hook(__FILE__, 'gam_ads_ad_manager_and_ad_exchange_deactivate');

// Activation hook: create DB table
function gam_ads_ad_manager_and_ad_exchange_activate()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'gamadsmbai_ads';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
      id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      ad_type varchar(100) NOT NULL,
      blockid INT NOT NULL,
      gam_ad_unit varchar(255) DEFAULT NULL,
      is_refreshad tinyint(1) DEFAULT 0,
      refreshad_intervel int(100) DEFAULT NULL,
      gam_ad_sizes varchar(255) DEFAULT NULL,
      is_responsive tinyint(1) DEFAULT 0,
      gam_responsive_sizes JSON DEFAULT NULL,
      custom_code text DEFAULT NULL,
      visible_pages text DEFAULT NULL,
      show_entire_site tinyint(1) DEFAULT 0,
      ad_position varchar(100) DEFAULT NULL,
      paragraph_counts VARCHAR(255) DEFAULT NULL,
      ad_alignment VARCHAR(20) DEFAULT NULL,
      custom_ad_position varchar(255) DEFAULT NULL,
      show_once tinyint(1) DEFAULT 0,
      is_active tinyint(1) DEFAULT 1,
      gam_active_devices varchar(255) DEFAULT NULL,
      created_at datetime DEFAULT CURRENT_TIMESTAMP,
      updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is derived from $wpdb->prefix and escaped; No need of chache
    if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
        wp_die('GAM Ads table creation failed.');
    }

    $table_name = $wpdb->prefix . 'gamadsmbai_adunits';
    $charset_collate = $wpdb->get_charset_collate();

    $adunits_table = $wpdb->prefix . 'gamadsmbai_adunits';
    $sql = "CREATE TABLE $adunits_table (
      id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      network_code VARCHAR(50) NOT NULL,
      adunit_id VARCHAR(100) NOT NULL,
      adunit_name VARCHAR(255) NOT NULL,
      code TEXT NULL,
      status VARCHAR(100) NOT NULL,
      parent_id VARCHAR(100) NOT NULL,
      description TEXT NULL,
      sizes VARCHAR(255) NULL,
      last_modified TIMESTAMP NULL,
      PRIMARY KEY (id),
      UNIQUE KEY idx_network_adunit (network_code, adunit_id),
      KEY adunit_name (adunit_name)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of chache
    if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
        wp_die('GAM AdUnit table creation failed.');
    }

    // Add UNIQUE key (only if it doesn't exist)
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is derived from $wpdb->prefix and escaped; No need of chache
    $unique_key_exists = $wpdb->get_row("SHOW INDEX FROM $adunits_table WHERE Key_name = 'unique_adunit'");
    if (!$unique_key_exists) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is derived from $wpdb->prefix and escaped; No need of chache
        $wpdb->query("ALTER TABLE $adunits_table ADD UNIQUE KEY unique_adunit (network_code, adunit_id)");
    }
}

// Deactivation hook - optional cleanup or leave empty
function gam_ads_ad_manager_and_ad_exchange_deactivate()
{
    // You may remove table here if you want (optional)
}

// Include main plugin class & ajax handlers
require_once gamadsmbai_PLUGIN_DIR . 'includescore/log.php';
require_once gamadsmbai_PLUGIN_DIR . 'vendor/autoload.php';
require_once gamadsmbai_PLUGIN_DIR . 'includescore/GamadsadmanagerandadexchangeHelper.php';
require_once gamadsmbai_PLUGIN_DIR . 'includescore/class-gam-ads-ad-manager-and-ad-exchange.php';
require_once gamadsmbai_PLUGIN_DIR . 'includescore/ajax-handlers.php';
require_once gamadsmbai_PLUGIN_DIR . 'includescore/class-gam-ad.php';
require_once plugin_dir_path(__FILE__) . 'includescore/hooks.php';

// Initialize plugin
add_action('plugins_loaded', function () {
    Gam_ads_ad_manager_and_ad_exchange::get_instance();
});

// Add Settings Option to installed plugins action links
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'gamadsmbai_plugin_action_links');
function gamadsmbai_plugin_action_links($links)
{
    $settings_link = '<a href="admin.php?page=gam-ads-ad-manager-and-ad-exchange&tab=settings">Settings</a>';
    array_unshift($links, $settings_link);
    return $links;
}

// GAM TOKEN REFRESH CRONs
register_activation_hook(__FILE__, function () {
    if (!wp_next_scheduled('gam_ads_ad_manager_and_ad_exchange_refresh_tokens_event')) {
        wp_schedule_event(time() + 3600, 'hourly', 'gam_ads_ad_manager_and_ad_exchange_refresh_tokens_event');
    }
});

register_deactivation_hook(__FILE__, function () {
    $ts = wp_next_scheduled('gam_ads_ad_manager_and_ad_exchange_refresh_tokens_event');
    if ($ts) {
        wp_unschedule_event($ts, 'gam_ads_ad_manager_and_ad_exchange_refresh_tokens_event');
    }
});

add_action('gam_ads_ad_manager_and_ad_exchange_refresh_tokens_event', 'gam_ads_ad_manager_and_ad_exchange_refresh_access_token_if_needed');
