<?php
/*
 *=================================
 * Creote Functions and Definitions
 * @package Creote WordPress Theme
 *==================================
*/
// ============================== theme file get ============================
require_once get_template_directory() . '/includes/Mobile_Detect.php';
// Merlin

// Mobile Detect callback
function isMobile() {
    if ( ! class_exists( 'Mobile_Detect' ) ) {
        return false;
    }
    // Validate Mobile_Detect version
    if (!defined('MOBILE_DETECT_VERSION') || version_compare(MOBILE_DETECT_VERSION, '2.8.0', '<')) {
        return false;
    }
    $detect = new Mobile_Detect();
    return ($detect->isMobile() || $detect->isTablet());
}
if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
  }

require_once get_template_directory() . '/includes/theme-file.php'; 
if(class_exists('Creote_Addons')):
add_action( 'vc_before_init', 'creote_vc_remove_css' );
function creote_vc_remove_css() {
    vc_remove_param('vc_row', 'css');
}
endif;
// ============================== theme update ============================ 
use YahnisElsts\PluginUpdateChecker\v5\PucFactory; 
if(class_exists('Creote_update')): 
    $update_key = '33328caf00548c12cdce0c8f53fea73b'; // Put your generated key here 
    $myUpdateChecker = PucFactory::buildUpdateChecker(
        add_query_arg('license_key', $update_key, 'https://themepanthers.com/updatedplugin/creote/theme.json'),
        __FILE__,
        'creote-theme-update'
    );
endif; 
// ============================== theme update ============================
add_action('init', 'creote_disable_elementor_onboarding_redirect');
function creote_disable_elementor_onboarding_redirect() {
    delete_transient( 'elementor_activation_redirect' );
}
// ============================== Elementor Register Location ============================
function creote_register_elementor_locations( $elementor_theme_manager ) {
    if (!current_user_can('edit_theme_options')) {
        return;
    }
    
    // Validate manager
    if (!method_exists($elementor_theme_manager, 'register_all_core_location')) {
        return;
    }
    $elementor_theme_manager->register_all_core_location();
	$elementor_theme_manager->register_location(
		'footer',
		[
			'hook' => 'creote_elementor_footer',
			'remove_hooks' => [ 'creote_print_elementor_footer' ],
		]
	);
    $elementor_theme_manager->register_location(
		'header',
		[
			'hook' => 'creote_elementor_header',
			'remove_hooks' => [ 'creote_print_elementor_header' ],
		]
	);
	 
}
add_action( 'elementor/theme/register_locations', 'creote_register_elementor_locations' );

// Theme footer
function creote_print_elementor_footer() {
	get_template_part( 'templates-parts/footer' );  
}
add_action( 'creote_elementor_footer', 'creote_print_elementor_footer' );
// Theme header
function creote_print_elementor_header() {
    ?>
	    <?php get_template_part( 'templates-parts/header' ); ?>
    <?php
}
add_action( 'creote_elementor_header', 'creote_print_elementor_header' );
// ============================== Elementor Register Location ============================

add_action('admin_notices', 'custom_plugin_update_notice');

function custom_plugin_update_notice() {
    // Only run for admin users
    if (!current_user_can('manage_options')) {
        return;
    }

    // Add nonce for AJAX requests
    $nonce = wp_create_nonce('plugin_update_check');
    
    // URL to the hosted version.json file
    $json_url = 'https://themepanthers.com/updatedplugin/plugins.json';
    
    // Set strict arguments for the request
    $args = array(
        'timeout'     => 5,
        'redirection' => 5,
        'sslverify'   => true,
        'headers'     => array(
            'Accept' => 'application/json'
        )
    );

    // Fetch the JSON file
    $response = wp_remote_get(esc_url_raw($json_url), $args);

    // Check for errors
    if (is_wp_error($response)) {
        error_log('Plugin update check failed: ' . $response->get_error_message());
        return;
    }

    // Verify response code
    $response_code = wp_remote_retrieve_response_code($response);
    if ($response_code !== 200) {
        error_log('Plugin update check failed with response code: ' . $response_code);
        return;
    }

    // Parse the JSON response
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    // Validate JSON structure
    if (!is_array($data) || 
        !isset($data['plugins']) || 
        !is_array($data['plugins'])) {
        error_log('Invalid plugin update JSON structure');
        return;
    }

    foreach ($data['plugins'] as $plugin) {
        // Validate required plugin data
        if (!isset($plugin['slug'], $plugin['name'], $plugin['latest_version'], $plugin['source']) ||
            !is_string($plugin['slug']) ||
            !is_string($plugin['name']) ||
            !is_string($plugin['latest_version']) ||
            !is_string($plugin['source'])) {
            continue;
        }

        // Sanitize plugin data
        $slug = sanitize_file_name($plugin['slug']);
        $plugin_path = WP_PLUGIN_DIR . '/' . $slug . '/' . $slug . '.php';

        // Custom path validation
        $plugin_path = str_replace('\\', '/', $plugin_path);
        $plugin_path = preg_replace('|/+|', '/', $plugin_path);
        $plugin_dir = str_replace('\\', '/', WP_PLUGIN_DIR);
        
        // Verify the path is within the plugins directory
        if (strpos($plugin_path, $plugin_dir) !== 0 || !file_exists($plugin_path)) {
            continue;
        }

        // Get installed plugin data
        $plugin_data = get_plugin_data($plugin_path);
        $installed_version = isset($plugin_data['Version']) ? $plugin_data['Version'] : '';

        if (!empty($installed_version) && version_compare($installed_version, $plugin['latest_version'], '<')) {
            // Use wp_kses to allow only specific HTML tags
            $message = sprintf(
                __('A new version of %s is available. Installed version: %s, Latest version: %s. You can download the update from %s.', 'risehand'),
                '<strong>' . esc_html($plugin['name']) . '</strong>',
                esc_html($installed_version),
                esc_html($plugin['latest_version']),
                '<a href="' . esc_url($plugin['source']) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('here', 'risehand') . '</a>'
            );

            printf(
                '<div class="notice notice-warning is-dismissible"><p>%s</p></div>',
                wp_kses(
                    $message,
                    array(
                        'strong' => array(),
                        'a' => array(
                            'href' => array(),
                            'target' => array(),
                            'rel' => array()
                        )
                    )
                )
            );
        }
    }
}