<?php
/**
 * Plugin Name: Aegisify Core
 * Plugin URI:  https://aegisify.com/
 * Description: Aegisify Suite: Get Security, SEO, Backup, Spam Protection, WAF and Ticketing with one platform.  Everything you need!
 * Version:     1.1.14
 * Requires at least: 6.8
 * Requires PHP: 8.2
 * Author:      Aegisify Bundle: AegisWAF | AegisShield | AegisSEO | AegisBackup | AegisLink | AegisSiteMap | AegisSpam
 * Author URI:  https://aegisify.com/
 * Text Domain: aegisify
 * License: GPLv2 or later
 */
if (!defined('ABSPATH')) exit;

define('AEGISIFY_CORE_VERSION', '1.1.14');
define('AEGISIFY_CORE_PATH', plugin_dir_path(__FILE__));
define('AEGISIFY_CORE_URL', plugin_dir_url(__FILE__));
define('AEGISIFY_VERSION', AEGISIFY_CORE_VERSION);
define('AEGISIFY_FILE', __FILE__);
define('AEGISIFY_DIR', plugin_dir_path(__FILE__));
define('AEGISIFY_URL', plugin_dir_url(__FILE__));
define('AEGISIFY_BASENAME', plugin_basename(__FILE__));
define('AEGISIFY_SLUG', 'aegisify');

define('AEGISIFY_CLM_BASE', 'https://aegisify.com');
define('AEGISIFY_CLM_FREE_REGISTER_ENDPOINT',  AEGISIFY_CLM_BASE . '/wp-json/chue-license/v1/aegisify/free-register');
define('AEGISIFY_CLM_ACTIVATE_ENDPOINT',       AEGISIFY_CLM_BASE . '/wp-json/chue-license/v1/aegisify/activate');
define('AEGISIFY_CLM_DEACTIVATE_ENDPOINT',     AEGISIFY_CLM_BASE . '/wp-json/chue-license/v1/aegisify/deactivate');
define('AEGISIFY_CLM_STATUS_ENDPOINT',         AEGISIFY_CLM_BASE . '/wp-json/chue-license/v1/aegisify/status');
define('AEGISIFY_CLM_TRIAL_ENDPOINT',          AEGISIFY_CLM_BASE . '/wp-json/chue-license/v1/aegisify/trial');

require_once AEGISIFY_CORE_PATH . 'includes/interfaces/interface-aegisify-module.php';
require_once AEGISIFY_CORE_PATH . 'includes/class-aegisify-modules.php';
require_once AEGISIFY_CORE_PATH . 'includes/class-aegisify-admin.php';
require_once AEGISIFY_CORE_PATH . 'includes/class-aegisify-emails.php';
require_once AEGISIFY_CORE_PATH . 'includes/class-aegisify-admin-emails.php';
require_once AEGISIFY_CORE_PATH . 'includes/class-aegisify-core.php';
require_once AEGISIFY_CORE_PATH . 'includes/class-aegisify-dashboard-news-widget.php';
require_once AEGISIFY_CORE_PATH . 'includes/admin_pages/class-aegisify-bundled-plugins-page.php';

// Ensure bundled plugins admin-post handlers are registered even on admin-post.php requests.
// admin_menu does NOT run on admin-post.php, so relying on menu registration to call ::init() will cause the action to be unhandled (blank/0 page).
add_action('admin_init', function () {
    if (!is_admin()) { return; }
    if (class_exists('Aegisify_Bundled_Plugins_Page')) {
        Aegisify_Bundled_Plugins_Page::init(array(
            'parent_slug' => 'aegisify-dashboard',
            'menu_slug'   => 'aegisify-plugins',
            'page_title'  => 'Aegisify Plugins',
            'menu_title'  => 'Aegisify Plugins',
        ));
    }
}, 1);

require_once AEGISIFY_CORE_PATH . 'includes/utils/class-aegisify-license.php';

if (!function_exists('aegisify_update_log')) {
    function aegisify_update_log(string $message, array $context = array(), string $level = 'INFO'): void {
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log( '[Aegisify][' . $level . '] ' . $message . ' ' . wp_json_encode( $context ) );
        }
    }
}
if (!function_exists('aegisify_is_pro')) {
    function aegisify_is_pro(bool $force_refresh = false): bool {
        if (!class_exists('Aegisify_Core') || !method_exists('Aegisify_Core', 'instance')) {
            return false;
        }

        try {
            $lic = Aegisify_Core::instance()->license();
        } catch (\Throwable $e) {
            return false;
        }

        if (!$lic || !is_object($lic)) {
            return false;
        }

        $status      = $lic->get_status();
        $refresh_due = method_exists($lic, 'status_refresh_due')
            ? (bool) $lic->status_refresh_due()
            : empty($status);

        if ($force_refresh || empty($status) || $refresh_due) {
            $guard = get_transient('aegisify_status_autorefresh');
            if ($force_refresh || !$guard) {
                set_transient('aegisify_status_autorefresh', 1, 6 * HOUR_IN_SECONDS);
                $status = $lic->check_now(AEGISIFY_VERSION);
            }
        }

        return !empty($status['is_pro']);
    }
}

register_activation_hook(__FILE__, array('Aegisify_Core', 'activate'));
register_deactivation_hook(__FILE__, array('Aegisify_Core', 'deactivate'));

add_action('plugins_loaded', function () {
    Aegisify_Core::instance()->boot();

    if ( is_admin() && class_exists( 'Aegisify_Dashboard_News_Widget' ) ) {
        Aegisify_Dashboard_News_Widget::init();
    }
});


register_activation_hook(__FILE__, function () {
    if ( ! function_exists('wp_mkdir_p') ) return;

    $dir = trailingslashit(plugin_dir_path(__FILE__)) . 'includes/integrations/';
    wp_mkdir_p($dir);

    $defaults = array(
        'scan-plan.json' => array('pages'=>array(), 'subpages'=>array(), 'structured_text'=>'', 'updated_at'=>time()),
        'registry.json'  => array('entries'=>array(), 'updated_at'=>time()),
        'schema.json'    => array('schema'=>array(), 'updated_at'=>time()),
        'snapshot.json'  => array('snapshot'=>array(), 'updated_at'=>time()),
    );

    foreach ($defaults as $file => $data) {
        $path = $dir . $file;
        if ( file_exists($path) ) continue;
        @file_put_contents($path, wp_json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }
});

// Optional: safety check in case user deletes the folder later.
add_action('plugins_loaded', function () {
    $dir = trailingslashit(plugin_dir_path(__FILE__)) . 'includes/integrations/';
    if ( ! is_dir($dir) ) wp_mkdir_p($dir);
});


register_activation_hook(__FILE__, function () {
    if ( ! function_exists('wp_mkdir_p') ) return;

    $dir = trailingslashit(plugin_dir_path(__FILE__)) . 'includes/integrations/';
    wp_mkdir_p($dir);

    $defaults = array(
        'scan-plan.json' => array('pages'=>array(), 'subpages'=>array(), 'structured_text'=>'', 'updated_at'=>time()),
        'registry.json'  => array('entries'=>array(), 'updated_at'=>time()),
        'schema.json'    => array('schema'=>array(), 'updated_at'=>time()),
        'snapshot.json'  => array('snapshot'=>array(), 'updated_at'=>time()),
    );

    foreach ($defaults as $file => $data) {
        $path = $dir . $file;
        if ( file_exists($path) ) continue;
        @file_put_contents($path, wp_json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }
});

// Optional: safety check in case user deletes the folder later.
add_action('plugins_loaded', function () {
    $dir = trailingslashit(plugin_dir_path(__FILE__)) . 'includes/integrations/';
    if ( ! is_dir($dir) ) wp_mkdir_p($dir);
});