<?php
if (!defined('ABSPATH')) {
    exit;
}

use includescore\GamadsadmanagerandadexchangeHelper;

add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_save_ad', 'gam_ads_ad_manager_and_ad_exchange_ajax_save_ad');
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_get_ads_list', 'gam_ads_ad_manager_and_ad_exchange_ajax_get_ads_list');
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_delete_ad', 'gam_ads_ad_manager_and_ad_exchange_ajax_delete_ad');
add_action('wp_ajax_gam_get_ad_details', 'gam_ads_ad_manager_and_ad_exchange_ajax_get_ad_details');

// Save Ad handler
function gam_ads_ad_manager_and_ad_exchange_ajax_save_ad()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    global $wpdb;
    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $table = $wpdb->prefix . 'gamadsmbai_ads';

    $ad_id = isset($_POST['ad_id']) ? intval($_POST['ad_id']) : 0;
    $ad_type = isset($_POST['ad_type']) ? sanitize_text_field(wp_unslash($_POST['ad_type'])) : '';
    $blockid = isset($_POST['blockid']) ? intval($_POST['blockid']) : 0;
    $gam_ad_unit = isset($_POST['gam_ad_unit']) ? sanitize_text_field(wp_unslash($_POST['gam_ad_unit'])) : '';
    $is_refreshad = !empty($_POST['is_refreshad']) && sanitize_text_field(wp_unslash($_POST['is_refreshad'])) == 'on' ? 1 : 0;
    $refreshad_intervel = isset($_POST['refreshad_intervel']) ? intval($_POST['refreshad_intervel']) : '';
    $gam_ad_sizes = isset($_POST['gam_ad_sizes']) ? sanitize_text_field(wp_unslash($_POST['gam_ad_sizes'])) : '';
    $is_responsive = !empty($_POST['is_responsive']) && sanitize_text_field(wp_unslash($_POST['is_responsive'])) == 'on' ? 1 : 0;
    $gam_responsive_sizes = null;
    if (!empty($_POST['gam_responsive_sizes'])) {
        // Sanitize and decode JSON
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Sanitizing inside array_walk_recursive functions.
        $decoded = json_decode(stripslashes($_POST['gam_responsive_sizes']), true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            array_walk_recursive($decoded, function (&$item) {
                $item = sanitize_text_field($item);
            });
            // Store back as clean JSON
            $gam_responsive_sizes = wp_json_encode($decoded);
        }
    }

    if (current_user_can('unfiltered_html')) {
        $gam_custom_code = isset($_POST['gam_custom_code'])
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Custom code sanitized with wp_kses_post() or allowed for admins via unfiltered_html.
            ? wp_unslash($_POST['gam_custom_code'])
            : '';
    } else {
        $gam_custom_code = isset($_POST['gam_custom_code'])
            ? wp_kses_post(wp_unslash($_POST['gam_custom_code']))
            : '';
    }
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- sanitized.
    $visible_pages = isset($_POST['visible_pages']) ? array_map('sanitize_text_field', $_POST['visible_pages']) : [];
    $show_entire_site = isset($_POST['show_on_all_pages']) && $_POST['show_on_all_pages'] == '1' ? 1 : 0;
    $ad_position = isset($_POST['gam_ad_position']) ? sanitize_text_field(wp_unslash($_POST['gam_ad_position'])) : '';
    $paragraph_counts = isset($_POST['paragraph_counts']) ? sanitize_text_field(wp_unslash($_POST['paragraph_counts'])) : '';
    $ad_alignment = isset($_POST['gam_ad_alignment']) ? sanitize_text_field(wp_unslash($_POST['gam_ad_alignment'])) : '';
    $custom_ad_position = isset($_POST['custom_ad_position']) ? sanitize_text_field(wp_unslash($_POST['custom_ad_position'])) : 'No';
    $show_once = isset($_POST['show_once']) && ($_POST['show_once'] == 'on' || $_POST['show_once'] == '1') ? 1 : 1;
    $is_active = isset($_POST['is_active']) && $_POST['is_active'] == '1' ? 1 : 0;
    $gam_active_devices = isset($_POST['gam_active_devices']) ? sanitize_text_field(wp_unslash($_POST['gam_active_devices'])) : '';

    if (empty($ad_type)) {
        wp_send_json_error(__('Ad Type is required.', 'gam-ads-ad-manager-and-ad-exchange'));
    }

    if ($show_entire_site) {
        $visible_pages = [];
    }

    $data = [
        'ad_type' => $ad_type,
        'blockid' => $blockid,
        'gam_ad_unit' => $gam_ad_unit,
        'is_refreshad' => $is_refreshad,
        'refreshad_intervel' => $refreshad_intervel,
        'gam_ad_sizes' => $gam_ad_sizes,
        'is_responsive' => $is_responsive,
        'gam_responsive_sizes' => $gam_responsive_sizes,
        'custom_code' => $gam_custom_code,
        'visible_pages' => maybe_serialize($visible_pages),
        'show_entire_site' => $show_entire_site,
        'ad_position' => $ad_position,
        'paragraph_counts' => $paragraph_counts,
        'ad_alignment' => $ad_alignment,
        'custom_ad_position' => $custom_ad_position,
        'show_once' => $show_once,
        'is_active' => $is_active,
        'gam_active_devices' => $gam_active_devices,
    ];

    // Premium Ad Saving API Call
    if (in_array($ad_type, ['push_down', 'rewarded', 'flying_carpet', 'sticky'], true)) {
        // This function should handle API sync
        gamadsmbai_CallingGamAdsServerSavingFun($data);
    }


    // === Handle Interstitial and Rewarded ads (show_once=1, single active) ===
    if (in_array($ad_type, ['interstitial', 'rewarded']) && $show_once) {
        // Find existing active show_once ad of this ad_type
        /** @noinspection SqlResolve */
        /** @noinspection SqlNoDataSourceInspection */
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
        $existing_ad = $wpdb->get_row(
            $wpdb->prepare(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table is trusted internal variable (wpdb->prefix).
                "SELECT id FROM $table WHERE ad_type = %s AND blockid = %d LIMIT 1",
                $ad_type,
                $blockid
            )
        );

        if ($existing_ad) {
            // Update existing ad
            /** @noinspection SqlResolve */
            /** @noinspection SqlNoDataSourceInspection */
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
            $updated = $wpdb->update($table, $data, ['id' => $existing_ad->id], null, ['%d']);
            if ($updated === false) {
                wp_send_json_error(__('Failed to update the existing show_once ad.', 'gam-ads-ad-manager-and-ad-exchange'));
            }
            wp_send_json_success(__('Existing show_once ad updated.', 'gam-ads-ad-manager-and-ad-exchange'));
        } else {
            // Insert new ad record
            /** @noinspection SqlResolve */
            /** @noinspection SqlNoDataSourceInspection */
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $inserted = $wpdb->insert($table, $data);
            if (!$inserted) {
                wp_send_json_error(__('Failed to insert new ad.', 'gam-ads-ad-manager-and-ad-exchange'));
            }
            wp_send_json_success(__('New show_once ad created.', 'gam-ads-ad-manager-and-ad-exchange'));
        }
        return; // done processing
    }

    // === Handle Custom Ad ===
    if ($ad_type === 'custom_ad' || $ad_type === 'banner') {
        if ($ad_id > 0) {
            // Update existing custom ad
            /** @noinspection SqlResolve */
            /** @noinspection SqlNoDataSourceInspection */
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
            $updated = $wpdb->update($table, $data, ['id' => $ad_id], null, ['%d']);
            if ($updated === false) {
                wp_send_json_error(__('Failed to update custom ad.', 'gam-ads-ad-manager-and-ad-exchange'));
            }
            wp_send_json_success(__('Custom ad updated.', 'gam-ads-ad-manager-and-ad-exchange'));
        } else {
            // Always insert new custom ad
            /** @noinspection SqlResolve */
            /** @noinspection SqlNoDataSourceInspection */
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $inserted = $wpdb->insert($table, $data);
            if (!$inserted) {
                wp_send_json_error(__('Failed to insert custom ad.', 'gam-ads-ad-manager-and-ad-exchange'));
            }
            wp_send_json_success(__('New custom ad created.', 'gam-ads-ad-manager-and-ad-exchange'));
        }
        return; // done processing
    }

    // === Handle other ad types or fallback ===
    if ($ad_id > 0) {
        /** @noinspection SqlResolve */
        /** @noinspection SqlNoDataSourceInspection */
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
        $updated = $wpdb->update($table, $data, ['id' => $ad_id], null, ['%d']);
        if ($updated === false) {
            wp_send_json_error(__('Failed to update ad.', 'gam-ads-ad-manager-and-ad-exchange'));
        }
        wp_send_json_success(__('Ad updated.', 'gam-ads-ad-manager-and-ad-exchange'));
    } else {
        /** @noinspection SqlResolve */
        /** @noinspection SqlNoDataSourceInspection */
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $inserted = $wpdb->insert($table, $data);
        if (!$inserted) {
            wp_send_json_error(__('Failed to insert ad.', 'gam-ads-ad-manager-and-ad-exchange'));
        }
        wp_send_json_success(__('Ad saved.', 'gam-ads-ad-manager-and-ad-exchange'));
    }
}

// Calling Server For Saving Preimum Ads
function gamadsmbai_CallingGamAdsServerSavingFun($data)
{
    $payload              = $data;
    $payload['domain']  = get_site_url();
    $payload['lbl_credit']  = get_option('gamadsmbai_lbl_credit', '0');
    $payload['lbl_advertisement']  = get_option('gamadsmbai_lbl_advertisement', '0');
    $response = wp_remote_post(
        'https://gamadinserter.com/api/save-ads',
        [
            'body'    => wp_json_encode($payload),
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'timeout' => 30, // 300 is too high
        ]
    );
    if (is_wp_error($response)) {
        wp_send_json_error([
            'message' => $response->get_error_message(),
        ]);
    }
    $status_code = wp_remote_retrieve_response_code($response);
    $body        = wp_remote_retrieve_body($response);
    $api_data    = json_decode($body, true);
    if ($status_code !== 200 || empty($api_data['success'])) {
        if (class_exists('gam_ads_ad_manager_and_ad_exchange_Logs')) {
            gam_ads_ad_manager_and_ad_exchange_Logs::log(
                'API Error (' . $status_code . '): ' . wp_json_encode($api_data)
            );
        }
        wp_send_json_error([
            'message' => 'Invalid API response',
            'status'  => $status_code,
        ]);
    }
    if (!empty($api_data['save_path'])) {
        $path = sanitize_text_field($api_data['save_path']);
        $paths = get_option('save_path', []);
        if (!is_array($paths)) {
            $paths = [];
        }
        if ($data['is_active']) {
            // ADD path if not exists
            if (!in_array($path, $paths, true)) {
                $paths[] = $path;
                update_option('save_path', $paths);
            }
        } else {
            // REMOVE path if exists
            $key = array_search($path, $paths, true);
            if ($key !== false) {
                unset($paths[$key]);
                $paths = array_values($paths); // reindex
                update_option('save_path', $paths);
            }
        }
    }
}

// Get Data OF Once per Site data
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_get_show_once_ad', 'gam_ads_ad_manager_and_ad_exchange_get_show_once_ad');
function gam_ads_ad_manager_and_ad_exchange_get_show_once_ad()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    global $wpdb;
    $table = $wpdb->prefix . 'gamadsmbai_ads';

    $ad_type = isset($_POST['ad_type']) ? sanitize_text_field(wp_unslash($_POST['ad_type'])) : '';
    // $blockid = isset($_POST['blockid']) ? intval($_POST['blockid']) : 0;

    // Find the first active show_once ad for this type
    // AND blockid = %d 
    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is derived from $wpdb->prefix and escaped; $ad_type sanitized and used safely in prepare();No need of cache
    $ads = $wpdb->get_results(
        $wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table is trusted internal variable (wpdb->prefix).
            "SELECT * FROM $table WHERE ad_type = %s AND show_once = 1",
            $ad_type
            // $blockid
        )
    );

    if ($ads) {
        // Unserialize visible pages
        foreach ($ads as $ad) {
            if (!empty($ad->visible_pages)) {
                $ad->visible_pages = maybe_unserialize($ad->visible_pages);
            }
        }
        wp_send_json_success($ads);
    } else {
        wp_send_json_error(__('No show once ad found.', 'gam-ads-ad-manager-and-ad-exchange'));
    }
}


// Get Ads List handler
function gam_ads_ad_manager_and_ad_exchange_ajax_get_ads_list()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    global $wpdb;
    $table = $wpdb->prefix . 'gamadsmbai_ads';

    $paged = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
    $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';

    $limit = 12;
    $offset = ($paged - 1) * $limit;

    // $where = '1=1';
    $where = "ad_type NOT LIKE 'custom_ad'";
    $params = [];

    if ($search !== '') {
        /** @noinspection SqlResolve */
        /** @noinspection SqlNoDataSourceInspection */
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $where .= " AND (ad_type LIKE %s OR gam_ad_unit LIKE %s)";
        $like = '%' . $wpdb->esc_like($search) . '%';
        $params[] = $like;
        $params[] = $like;
    }

    $sql_total = "SELECT COUNT(*) FROM $table WHERE $where";
    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- No need of cache and dynamic WHERE clause already properly prepared; $table is derived from $wpdb->prefix and escaped; $ad_type sanitized and used safely in prepare()
    $total = $wpdb->get_var($wpdb->prepare($sql_total, ...$params));

    $sql = "SELECT * FROM $table WHERE $where ORDER BY is_active DESC LIMIT %d OFFSET %d";
    $params[] = $limit;
    $params[] = $offset;
    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- No need of cache and dynamic WHERE clause already properly prepared; $table is derived from $wpdb->prefix and escaped; $ad_type sanitized and used safely in prepare()
    $ads = $wpdb->get_results($wpdb->prepare($sql, ...$params));
    foreach ($ads as $ad) {
        $pages = maybe_unserialize($ad->visible_pages);
        $ad->visible_pages = $pages;
    }

    $total_pages = ceil($total / $limit);

    wp_send_json_success([
        'ads' => $ads,
        'total_pages' => $total_pages,
        'current_page' => $paged,
    ]);
}

// Delete Ad handler
function gam_ads_ad_manager_and_ad_exchange_ajax_delete_ad()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    global $wpdb;
    $table = $wpdb->prefix . 'gamadsmbai_ads';

    $ad_id = isset($_POST['ad_id']) ? intval($_POST['ad_id']) : 0;

    if ($ad_id <= 0) {
        wp_send_json_error(__('Invalid Ad ID.', 'gam-ads-ad-manager-and-ad-exchange'));
    }

    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
    $deleted = $wpdb->delete($table, ['id' => $ad_id]);

    if ($deleted) {
        wp_send_json_success(__('Ad deleted.', 'gam-ads-ad-manager-and-ad-exchange'));
    } else {
        wp_send_json_error(__('Failed to delete ad.', 'gam-ads-ad-manager-and-ad-exchange'));
    }
}

// Get ad details by ad_id or ad_type
function gam_ads_ad_manager_and_ad_exchange_ajax_get_ad_details()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    global $wpdb;
    $table = $wpdb->prefix . 'gamadsmbai_ads';

    $ad_id = isset($_POST['ad_id']) ? intval($_POST['ad_id']) : 0;
    $ad_type = isset($_POST['ad_type']) ? sanitize_text_field(wp_unslash($_POST['ad_type'])) : '';

    if ($ad_id > 0) {
        /** @noinspection SqlResolve */
        /** @noinspection SqlNoDataSourceInspection */
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
        $ad = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d LIMIT 1", $ad_id));
    } elseif ($ad_type !== '') {
        /** @noinspection SqlResolve */
        /** @noinspection SqlNoDataSourceInspection */
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
        $ad = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE ad_type = %s LIMIT 1", $ad_type));
    } else {
        $ad = null;
    }

    if ($ad) {
        wp_send_json_success($ad);
    } else {
        wp_send_json_error(__('Ad not found.', 'gam-ads-ad-manager-and-ad-exchange'));
    }
}

// SELECT AD BY ID
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_get_ad_by_id', 'gam_ads_ad_manager_and_ad_exchange_get_ad_by_id');

function gam_ads_ad_manager_and_ad_exchange_get_ad_by_id()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    if (!$id) {
        wp_send_json_error(['message' => 'Invalid ad ID']);
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'gamadsmbai_ads'; // Replace with your actual table name
    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is derived from $wpdb->prefix and escaped; $ad_type sanitized and used safely in prepare(); No need of cache
    $ad = $wpdb->get_row(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table is trusted internal variable (wpdb->prefix).
        $wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d", $id),
        ARRAY_A
    );

    if ($ad) {
        $ad['visible_pages'] = maybe_unserialize($ad['visible_pages']);
        wp_send_json_success($ad);
    } else {
        wp_send_json_error(['message' => 'Ad not found']);
    }
}

// Update is_Active Status
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_toggle_ad_status', 'gam_ads_ad_manager_and_ad_exchange_toggle_ad_status');
function gam_ads_ad_manager_and_ad_exchange_toggle_ad_status()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    global $wpdb;
    $table = $wpdb->prefix . 'gamadsmbai_ads';

    $ad_id = isset($_POST['ad_id']) ? intval($_POST['ad_id']) : '';
    $status = isset($_POST['status']) ? intval($_POST['status']) : 0;

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
    $adD = $wpdb->get_row(
        $wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table uses wpdb prefix.
            "SELECT * FROM {$table} WHERE id = %d LIMIT 1",
            $ad_id
        )
    );

    /* Validate record exists */
    if (!$adD) {
        wp_send_json_error(['message' => 'Ad not found']);
    }

    /* Premium ad types */
    $premium_types = ['push_down', 'rewarded', 'flying_carpet', 'sticky'];
    if (in_array($adD->ad_type, $premium_types, true)) {
        $data = [
            'ad_type' => $adD->ad_type,
            'blockid' => $adD->blockid,
            'gam_ad_unit' => $adD->gam_ad_unit,
            'is_refreshad' => $adD->is_refreshad,
            'refreshad_intervel' => $adD->refreshad_intervel,
            'gam_ad_sizes' => $adD->gam_ad_sizes,
            'is_responsive' => $adD->is_responsive,
            'gam_responsive_sizes' => $adD->gam_responsive_sizes,
            'custom_code' => $adD->custom_code,
            'visible_pages' => $adD->visible_pages,
            'show_entire_site' => $adD->show_entire_site,
            'ad_position' => $adD->ad_position,
            'paragraph_counts' => $adD->paragraph_counts,
            'ad_alignment' => $adD->ad_alignment,
            'custom_ad_position' => $adD->custom_ad_position,
            'show_once' => $adD->show_once,
            'is_active' => $status,
            'gam_active_devices' => $adD->gam_active_devices,
        ];
        // This function should handle API sync
        gamadsmbai_CallingGamAdsServerSavingFun($data);
    }

    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
    $updated = $wpdb->update(
        $table,
        ['is_active' => $status],
        ['id' => $ad_id],
        ['%d'],
        ['%d']
    );

    if ($updated !== false) {
        wp_send_json_success(['status' => $status]);
    } else {
        wp_send_json_error('Could not update ad status.');
    }
}

// AJAX handler endpoint — saves credentials from remote
function gamadsmbai_encrypt_secret($data)
{
    $key = wp_salt('auth');
    $iv  = openssl_random_pseudo_bytes(16);
    $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
    update_option('gam_secret_iv', base64_encode($iv));
    return base64_encode($encrypted);
}
function gamadsmbai_decrypt_secret($data)
{
    $key = wp_salt('auth');
    $iv  = base64_decode(get_option('gam_secret_iv'));
    return openssl_decrypt(base64_decode($data), 'AES-256-CBC', $key, 0, $iv);
}
add_action('wp_ajax_gamadsmbai_save_config', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');

    $use_default = isset($_POST['use_default']) && in_array($_POST['use_default'], ['true', '1'], true);

    if ($use_default) {
        // update_option('gam_using_default_config', true);
        // update_option('gam_web_client_id', '');
        // update_option('gam_web_client_secret', '');
        // update_option('gam_redirect_uri', '');
        // wp_send_json_success(['message' => 'Using default configuration']);
        gamadsmbai_sync_config_func();
        return;
    }

    $custom_client_id      = isset($_POST['client_id'])     ? sanitize_text_field(wp_unslash($_POST['client_id']))     : '';
    $custom_client_secret  = isset($_POST['client_secret']) ? gamadsmbai_encrypt_secret(sanitize_text_field(wp_unslash($_POST['client_secret']))) : '';
    $usecustom_redirect_uri = isset($_POST['redirect_uri']) ? esc_url_raw(wp_unslash($_POST['redirect_uri'])) : '';

    update_option('gam_using_default_config', false);
    update_option('gam_web_client_id', $custom_client_id);
    update_option('gam_web_client_secret', $custom_client_secret);
    update_option('gam_redirect_uri', $usecustom_redirect_uri);

    wp_send_json_success(['message' => 'Custom configuration saved', 'configs' => ['cid' => $custom_client_id, 'rui' => $usecustom_redirect_uri]]);
});

// AJAX handler endpoint — syncs from remote
// If user allow to use "Default Configs" then this API will be call to get configs
add_action('wp_ajax_gamadsmbai_sync_config', 'gamadsmbai_sync_config_func');
function gamadsmbai_sync_config_func()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    $custom_site_url = isset($_POST['site_url']) ? esc_url_raw(wp_unslash($_POST['site_url'])) : '';

    $response = wp_remote_post('https://gamadinserter.com/api/check-site', [
        'body'    => wp_json_encode(['site_url' => get_site_url()]),
        'headers' => [
            'Content-Type' => 'application/json',
            'Referer' => $custom_site_url,
        ],
        'timeout' => 10,
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error(['message' => $response->get_error_message()]);
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if (empty($data['client_id'])) {
        if (class_exists('gam_ads_ad_manager_and_ad_exchange_Logs')) {
            gam_ads_ad_manager_and_ad_exchange_Logs::log('Api Error: ' . $data);
        }
        wp_send_json_error(['message' => 'Invalid API response: ' . $data]);
    }

    update_option('gam_using_default_config', true);
    update_option('gam_web_client_id', sanitize_text_field($data['client_id']));
    update_option('gam_web_client_secret', gamadsmbai_encrypt_secret(sanitize_text_field($data['client_secret'])));
    update_option('gam_redirect_uri', esc_url_raw($data['redirect_uri']));

    wp_send_json_success(['message' => 'Default configuration synced', 'configs' => ['cid' => sanitize_text_field($data['client_id']), 'rui' => esc_url_raw($data['redirect_uri'])]]);
}

// Revoke Default Configs
add_action('wp_ajax_gamadsmbai_revoke_default', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    delete_option('gam_web_client_id');
    delete_option('gam_web_client_secret');
    delete_option('gam_redirect_uri');
    delete_option('gam_using_default_config');
    delete_option('gam_secret_iv');
    wp_send_json_success(['message' => 'Default configuration revoked']);
});


// Redirect flow handler
add_action('admin_post_gam_redirect_auth', 'gam_ads_ad_manager_and_ad_exchange_redirect_auth_handler'); // logged-in users
add_action('admin_post_nopriv_gam_redirect_auth', 'gam_ads_ad_manager_and_ad_exchange_redirect_auth_handler'); // non-logged-in
function gam_ads_ad_manager_and_ad_exchange_redirect_auth_handler()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_die('Access denied');
    }

    $client_id = get_option('gam_web_client_id');
    $scope = 'https://www.googleapis.com/auth/dfp';
    $redirect_uri = 'https://magicbid.ai/gam-press-plugin-code/';
    $response_type = 'code';
    $access_type = 'offline';
    $prompt = 'consent';

    $auth_url = add_query_arg(
        [
            'client_id'     => $client_id,
            'redirect_uri'  => $redirect_uri,
            'response_type' => $response_type,
            'scope'         => $scope,
            'access_type'   => $access_type,
            'prompt'        => $prompt,
        ],
        'https://accounts.google.com/o/oauth2/v2/auth'
    );

    // Allow Google OAuth redirect
    add_filter('allowed_redirect_hosts', function ($hosts) {
        $hosts[] = 'accounts.google.com';
        return $hosts;
    });

    wp_safe_redirect($auth_url);
    exit;
}

/**
 * Disconnect (clear saved data)
 */
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_disconnect', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    delete_option('gam_ads_ad_manager_and_ad_exchange_tokens');
    delete_option('gam_ads_ad_manager_and_ad_exchange_networks');
    global $wpdb;
    /** @noinspection SqlResolve */
    /** @noinspection SqlNoDataSourceInspection */
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No need of cache
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'gam_ads_ad_manager_and_ad_exchange_network_%'");
    delete_option('gam_ads_ad_manager_and_ad_exchange_network_code');
    wp_send_json_success(['message' => 'Disconnected successfully']);
});

// // Google Client
// function gam_get_google_client()
// {
//     $client = new Google_Client();
//     $client->setClientId(GAM_WEB_CLIENT_ID);
//     $client->setClientSecret(GAM_WEB_CLIENT_SECRET);
//     $client->setRedirectUri(GAM_REDIRECT_URI);
//     $client->setAccessType('offline');
//     $client->setPrompt('consent');
//     // $client->addScope('https://www.googleapis.com/auth/admanager');
//     $client->addScope('https://www.googleapis.com/auth/dfp');
//     return $client;
// }

// // Fetch all user networks
// function gam_fetch_user_networks($refreshToken)
// {
//     try {
//         $oAuth2Credential = (new OAuth2TokenBuilder())
//             ->withClientId(GAM_WEB_CLIENT_ID)
//             ->withClientSecret(GAM_WEB_CLIENT_SECRET)
//             ->withRefreshToken($refreshToken)
//             ->build();

//         $session = (new AdManagerSessionBuilder())
//             ->withOAuth2Credential($oAuth2Credential)
//             // ->withNetworkCode('22824929284')
//             ->withApplicationName('GAM Connect Plugin')
//             ->build();

//         $serviceFactory = new ServiceFactory();
//         $networkService = $serviceFactory->createNetworkService($session);

//         return $networkService->getAllNetworks();
//     } catch (\Throwable $e) {
//         error_log('[GAM Fetch Networks Error] ' . $e->getMessage());
//         return [];
//     }
// }

// Manul mode active
add_action('wp_ajax_gamadsmbai_manual_mode_active', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);
    update_option('gamadsmbai_manual_mode', "1");
    wp_send_json_success(['message'  => 'Manual Mode Active']);
});

// Save auth code & fetch networks
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_save_auth_code', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Sanitized OAuth callback, read-only, external POST source, no nonce
    $authCode = sanitize_text_field($_POST['auth_code'] ?? $_POST['code'] ?? '');
    if (!$authCode) wp_send_json_error(['message' => 'Missing authorization code']);

    try {
        // Remove Manual Mode
        update_option('gamadsmbai_manual_mode', "0");

        $client = GamadsadmanagerandadexchangeHelper::gam_get_google_client();
        if (empty($client)) {
            wp_send_json_error(['message' => 'Cant make client authantication with GAM']);
        }
        $token  = $client->fetchAccessTokenWithAuthCode($authCode);

        if (!empty($token['error'])) {
            wp_send_json_error(['message' => $token['error_description'] ?? $token['error']]);
        }

        // Save tokens
        $normalized = [
            'access_token'  => $token['access_token'] ?? '',
            'refresh_token' => $token['refresh_token'] ?? '',
            'expires_in'    => (int)($token['expires_in'] ?? 0),
            'scope'         => $token['scope'] ?? '',
            'token_type'    => $token['token_type'] ?? '',
            'created'       => time(),
            'expires_at'    => time() + (int)($token['expires_in'] ?? 0),
        ];
        update_option('gam_ads_ad_manager_and_ad_exchange_tokens', $normalized);
        // Fetch networks
        // require_once gamadsmbai_PLUGIN_DIR . 'vendor/autoload.php';
        // require_once gamadsmbai_PLUGIN_DIR . 'includescore/GamadsadmanagerandadexchangeHelper.php';
        $networks = GamadsadmanagerandadexchangeHelper::CheckMainGam();
        if (
            // require_once gamadsmbai_PLUGIN_DIR . 'includescore/GamadsadmanagerandadexchangeHelper.php'
            count($networks) > 0
        ) {
            wp_send_json_success([
                'message'  => '✅ Authorization successful',
                'networks' => $networks
            ]);
        } else {
            wp_send_json_error(['message' => "⚠️ Can't find networks, Make sure: \n• This Google email is added to GAM, \n• Required permissions are granted, \n• You accepted the GAM invitation"]);
        }

        wp_send_json_success(['message' => 'Authorization successful', 'networks' => $networks]);
    } catch (Throwable $e) {
        gam_ads_ad_manager_and_ad_exchange_Logs::log('Error: ' . $e->getMessage() . '. File: ' . __FILE__ . '. Line: ' . __LINE__);
        wp_send_json_error(['message' => 'Error: ' . $e->getMessage()]);
    }
});

// Refetch Networks Codes
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_refetch_networks', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    try {
        $storedtoken = get_option('gam_ads_ad_manager_and_ad_exchange_tokens', []);
        if (empty($storedtoken['refresh_token'])) {
            wp_send_json_error(['message' => 'No refresh token found. Please reconnect Google Ad Manager.']);
        }
        // require_once gamadsmbai_PLUGIN_DIR . 'vendor/autoload.php';
        // require_once gamadsmbai_PLUGIN_DIR . 'includescore/GamadsadmanagerandadexchangeHelper.php';
        $networks = GamadsadmanagerandadexchangeHelper::CheckMainGam();
        if (
            // require_once gamadsmbai_PLUGIN_DIR . 'includescore/GamadsadmanagerandadexchangeHelper.php'
            count($networks) > 0
        ) {
            wp_send_json_success(['message' => '✅ Networks Refreshed', 'networks' => $networks]);
        } else {
            wp_send_json_error(['message' => "⚠️ Failed to fetch networks, Make sure: \n• This Google email is added to GAM, \n• Required permissions are granted, \n• You accepted the GAM invitation", 'networks' => $networks]);
        }
    } catch (\Throwable $e) {
        gam_ads_ad_manager_and_ad_exchange_Logs::log('[GAM Refetch Error] ' . $e->getMessage() . '. File: ' . __FILE__ . '. Line: ' . __LINE__);
        wp_send_json_error(['message' => 'Error: ' . $e->getMessage()]);
    }
});

// Save selected network
add_action('wp_ajax_gam_ads_ad_manager_and_ad_exchange_select_network', function () {
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');

    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Unauthorized']);
    // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- sanitized Read-only.
    $networkCode = sanitize_text_field(wp_unslash($_POST['network_code']) ?? '');
    if (!$networkCode) wp_send_json_error(['message' => 'Missing network code']);

    update_option('gam_ads_ad_manager_and_ad_exchange_network_code', $networkCode);
    $networks = GamadsadmanagerandadexchangeHelper::CheckMainGam();
    if (
        // require_once gamadsmbai_PLUGIN_DIR . 'includescore/GamadsadmanagerandadexchangeHelper.php'
        count($networks) > 0
    ) {
        wp_send_json_success(['message' => '✅ Network selected successfully']);
    } else {
        wp_send_json_error(['message' => 'Something went wrong', 'error' => $networks]);
    }
});

// Token auto-renew
function gam_ads_ad_manager_and_ad_exchange_get_access_token()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    $tokens = get_option('gam_ads_ad_manager_and_ad_exchange_tokens', []);
    if (empty($tokens['access_token'])) return false;

    if (time() > $tokens['expires_at'] - 60 && !empty($tokens['refresh_token'])) {
        $response = wp_remote_post('https://oauth2.googleapis.com/token', [
            'body' => [
                'client_id' => get_option('gam_web_client_id'),
                'client_secret' => gamadsmbai_decrypt_secret(get_option('gam_web_client_secret')),
                'refresh_token' => $tokens['refresh_token'],
                'grant_type' => 'refresh_token',
            ],
            'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
        ]);

        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($data['access_token'])) {
                $tokens['access_token'] = sanitize_text_field($data['access_token']);
                $tokens['expires_at']   = time() + intval($data['expires_in']);
                if (!empty($data['refresh_token'])) {
                    $tokens['refresh_token'] = sanitize_text_field($data['refresh_token']);
                }
                update_option('gam_ads_ad_manager_and_ad_exchange_tokens', $tokens);
            }
        }
    }

    return $tokens['access_token'];
}

// CRON FUN CALL
function gam_ads_ad_manager_and_ad_exchange_refresh_access_token_if_needed()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Permission denied']);

    gam_ads_ad_manager_and_ad_exchange_get_access_token();
}

// Licence Key Update Handler
add_action('wp_ajax_gamadsmbai_check_licence_and_save', 'gamadsmbai_check_licence_and_save');
function gamadsmbai_check_licence_and_save()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }
    // Get license key
    $license_key = isset($_POST['license_key'])
        ? sanitize_text_field(wp_unslash($_POST['license_key']))
        : '';
    if (empty($license_key)) {
        wp_send_json_error(['message' => 'License key is required.']);
    }
    // External API URL For License Verification
    $api_url = 'https://gamadinserter.com/api/validate-plugin-license';
    // Payload
    $payload = [
        'license_key' => $license_key
    ];
    // Send request to API
    $response = wp_remote_post($api_url, [
        'headers' => [
            'Content-Type' => 'application/json',
            'Origin'       => get_site_url(),
            'Referer'      => admin_url(),
            'User-Agent'   => 'GAM-ADS/1.0.2; ' . get_site_url(),
            'Accept'       => 'application/json'
        ],
        'body'      => wp_json_encode($payload),
        'timeout'   => 15,
        'sslverify' => true,
    ]);
    // Check network error
    if (is_wp_error($response)) {
        wp_send_json_error([
            'message' => 'API Error: ' . $response->get_error_message()
        ]);
    }
    // Decode response
    $body = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($body)) {
        wp_send_json_error(['message' => 'Invalid API response.']);
    }
    // If API returned success = false
    if (empty($body['success']) || $body['success'] !== true) {
        // Process server error messages into nicer texts
        $error_msg = $body['message'] ?? 'License invalid';
        switch (strtolower($error_msg)) {
            case 'license expired':
                $error_msg = 'Your license key has expired. Please renew it to continue using premium features.';
                break;
            case 'black listed domain':
                $error_msg = 'This domain is blacklisted and cannot activate the license.';
                break;
            case 'domain limit exceeted':
                $error_msg = 'Your license has reached the maximum number of allowed domains.';
                break;
            case 'invalid license':
                $error_msg = 'The license key you entered is invalid.';
                break;
            default:
                // If unknown error, return the original message
                $error_msg = $body['message'];
                break;
        }
        wp_send_json_error(['message' => $error_msg]);
    }

    // If success = true → extract data
    $data = isset($body['data']) ? $body['data'] : [];
    $token        = sanitize_text_field($data['token']        ?? '');
    $activated_at = sanitize_text_field($data['activated_at'] ?? '');
    $expires_at   = sanitize_text_field($data['expires_at']   ?? '');
    $plan         = sanitize_text_field($data['plan']         ?? '');
    if (empty($token)) {
        wp_send_json_error(['message' => 'Invalid response: missing token.']);
    }
    // Save license details
    update_option('gamadsmbai_license_key',    $license_key, false);
    update_option('gamadsmbai_license_token',  $token, false);
    update_option('gamadsmbai_activated_at',   $activated_at, false);
    update_option('gamadsmbai_expires_at',     $expires_at, false);
    update_option('gamadsmbai_license_plan',   $plan, false);
    update_option('gamadsmbai_license_status', 'active', false);
    update_option('gamadsmbai_lbl_credit', 1);

    wp_send_json_success([
        'message'      => $body['message'] ?? 'License validated successfully.'
    ]);
}

// Refresh License Status
add_action('wp_ajax_gamadsmbai_refresh_licence_and_save', 'gamadsmbai_refresh_licence_and_save');
function gamadsmbai_refresh_licence_and_save()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }
    // Get license key
    $license_key = get_option('gamadsmbai_license_key', '');
    $license_token = get_option('gamadsmbai_license_token', '');
    if (empty($license_key) && empty($license_token)) {
        wp_send_json_error(['message' => 'License key not found.']);
    }
    // External API URL For License Verification
    // $api_url = 'https://gamadinserter.com/api/refresh-license';
    $api_url = 'https://gamadinserter.com/api/validate-plugin-license';
    // Payload
    $payload = [
        'license_key' => $license_key,
        'token' => $license_token
    ];
    // Send request to API
    $response = wp_remote_post($api_url, [
        'headers' => [
            'Content-Type' => 'application/json',
            'Origin'       => get_site_url(),
            'Referer'      => admin_url(),
            'User-Agent'   => 'GAM-ADS/1.0.2; ' . get_site_url(),
            'Accept'       => 'application/json'
        ],
        'body'      => wp_json_encode($payload),
        'timeout'   => 15,
        'sslverify' => true,
    ]);
    // Check network error
    if (is_wp_error($response)) {
        wp_send_json_error([
            'message' => 'API Error: ' . $response->get_error_message()
        ]);
    }
    // Decode response
    $body = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($body)) {
        wp_send_json_error(['message' => 'Invalid API response.']);
    }
    // If API returned success = false
    if (empty($body['success']) || $body['success'] !== true) {
        // Process server error messages into nicer texts
        $error_msg = $body['message'] ?? 'License invalid';
        switch (strtolower($error_msg)) {
            case 'license expired':
                $error_msg = 'Your license key has expired. Please renew it to continue using premium features.';
                break;
            case 'black listed domain':
                $error_msg = 'This domain is blacklisted and cannot activate the license.';
                break;
            case 'domain limit exceeted':
                $error_msg = 'Your license has reached the maximum number of allowed domains.';
                break;
            case 'invalid license':
                $error_msg = 'The license key you entered is invalid.';
                break;
            default:
                // If unknown error, return the original message
                $error_msg = $body['message'];
                break;
        }
        wp_send_json_error(['message' => $error_msg]);
    }

    // If success = true → extract data
    $data = isset($body['data']) ? $body['data'] : [];
    $token        = sanitize_text_field($data['token']        ?? '');
    $activated_at = sanitize_text_field($data['activated_at'] ?? '');
    $expires_at   = sanitize_text_field($data['expires_at']   ?? '');
    $plan         = sanitize_text_field($data['plan']         ?? '');
    if (empty($token)) {
        wp_send_json_error(['message' => 'Invalid response: missing token.']);
    }
    // Save license details
    update_option('gamadsmbai_license_token',  $token, false);
    update_option('gamadsmbai_activated_at',   $activated_at, false);
    update_option('gamadsmbai_expires_at',     $expires_at, false);
    update_option('gamadsmbai_license_plan',   $plan, false);
    update_option('gamadsmbai_license_status', 'active', false);

    wp_send_json_success([
        'message' => $body['message'] ?? 'License refreshed.'
    ]);
}

// Remove License Local & Remote API
add_action('wp_ajax_gamadsmbai_remove_license', 'gamadsmbai_remove_license');
function gamadsmbai_remove_license()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }
    //Inform remote API about deactivation
    $license_key = get_option('gamadsmbai_license_key', '');
    if (!empty($remote_token)) {
        $response = wp_remote_post('https://gamadinserter.com/api/deactivate-license', [
            'headers' => [
                'Content-Type' => 'application/json',
                'Origin'       => get_site_url(),
                'Referer'      => admin_url(),
                'Accept'       => 'application/json',
            ],
            'body' => wp_json_encode([
                'license_key'  => $license_key,
            ]),
            'timeout'   => 15,
            'sslverify' => true,
        ]);
        //If API fails No blocking of local removal
    }
    // Remove local license data
    delete_option('gamadsmbai_license_key');
    delete_option('gamadsmbai_license_token');
    delete_option('gamadsmbai_activated_at');
    delete_option('gamadsmbai_expires_at');
    delete_option('gamadsmbai_license_plan');
    delete_option('gamadsmbai_license_status');
    delete_option('gamadsmbai_lbl_credit');
    delete_option('gamadsmbai_lbl_advertisement');
    wp_send_json_success([
        'message' => 'License removed successfully from this site.'
    ]);
}

// Ads Label Show Or Hide option savinf Func
add_action('wp_ajax_gamadsmbai_save_adsbanners_label_showhide', 'gamadsmbai_save_adsbanners_label_showhide');
function gamadsmbai_save_adsbanners_label_showhide()
{
    check_ajax_referer('gam_ads_ad_manager_and_ad_exchange_nonce', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }
    // Get license key
    $show_banner_ad_label = isset($_POST['show_banner_ad_label']) && sanitize_text_field(wp_unslash($_POST['show_banner_ad_label'])) === 'on' ? 1 : 0;
    $show_credit_label = isset($_POST['show_credit_label']) && sanitize_text_field(wp_unslash($_POST['show_credit_label'])) === 'on' ? 1 : 0;
    // Only validate if both are missing (not if off)
    if (!isset($_POST['show_banner_ad_label']) && !isset($_POST['show_credit_label'])) {
        wp_send_json_error(['message' => 'No settings were sent.']);
    }
    update_option('gamadsmbai_lbl_advertisement', $show_banner_ad_label);
    update_option('gamadsmbai_lbl_credit', $show_credit_label);
    wp_send_json_success([
        'message' => 'Settings Changed'
    ]);
}
