<?php
/**
 * Elessi Hosting Marketing Notice
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Get parent theme version
 */
function elessi_get_parent_theme_version() {
    $theme = wp_get_theme();
    if ($theme->parent()) {
        $theme = $theme->parent();
    }
    
    return $theme->get('Version');
}

/**
 * Get dismiss option key by theme version
 */
function elessi_get_cloud_notice_option_key() {
    return 'elessi_cloud_notice_closed_' . elessi_get_parent_theme_version();
}

/**
 * Detect local / development environment
 */
function elessi_is_local_environment() {
    if (defined('WP_ENVIRONMENT_TYPE') && WP_ENVIRONMENT_TYPE === 'local') {
        return true;
    }

    $host = $_SERVER['HTTP_HOST'] ?? '';
    $host = preg_replace('/:\d+$/', '', $host);

    if (in_array($host, ['localhost', '127.0.0.1'], true)) {
        return true;
    }

    if (
        str_ends_with($host, '.local') ||
        str_ends_with($host, '.test') ||
        str_ends_with($host, '.dev')
    ) {
        return true;
    }

    return false;
}

/**
 * Calculate hosting score
 */
function elessi_calculate_hosting_score() {
    $score  = 0;
    $issues = [];

    if (version_compare(PHP_VERSION, '7.4', '>=')) {
        $score += 10;
    } else {
        $issues['php_version'] = PHP_VERSION;
    }

    if (wp_convert_hr_to_bytes(ini_get('upload_max_filesize')) >= 64 * MB_IN_BYTES) {
        $score += 5;
    } else {
        $issues['upload_max_filesize'] = ini_get('upload_max_filesize');
    }

    if ((int) ini_get('max_input_vars') >= 5000) {
        $score += 5;
    } else {
        $issues['max_input_vars'] = ini_get('max_input_vars');
    }

    $php_memory = wp_convert_hr_to_bytes(ini_get('memory_limit'));
    $wp_memory  = defined('WP_MEMORY_LIMIT') ? wp_convert_hr_to_bytes(WP_MEMORY_LIMIT) : 0;

    if ($wp_memory >= 512 * MB_IN_BYTES) {
        $score += 15;
    } else {
        $issues['wp_memory_limit'] = WP_MEMORY_LIMIT;
    }

    if ($php_memory >= 512 * MB_IN_BYTES) {
        $score += 15;
    } else {
        $issues['php_memory_limit'] = ini_get('memory_limit');
    }

    if ($php_memory && $wp_memory && $php_memory < $wp_memory) {
        $score -= 10;
        $issues['memory_mismatch'] = true;
    }

    global $wpdb;

    if ($wpdb->use_mysqli) {
        $db_version = mysqli_get_server_info($wpdb->dbh);
    } else {
        $db_version = mysql_get_server_info();
    }

    if (stripos($db_version, 'mariadb') !== false) {
        if (version_compare($db_version, '10.4', '>=')) {
            $score += 10;
        } else {
            $issues['mariadb_version'] = $db_version;
        }
    } else {
        if (version_compare($db_version, '5.7', '>=')) {
            $score += 10;
        } else {
            $issues['mysql_version'] = $db_version;
        }
    }

    if (function_exists('opcache_get_status')) {
        $status = @opcache_get_status(false);

        if (!empty($status['opcache_enabled'])) {
            $score += 15;

            if ((int) ini_get('opcache.memory_consumption') >= 128) {
                $score += 5;
            } else {
                $issues['opcache_memory'] = ini_get('opcache.memory_consumption');
            }

            if ((int) ini_get('opcache.max_accelerated_files') >= 10000) {
                $score += 5;
            } else {
                $issues['opcache_files'] = ini_get('opcache.max_accelerated_files');
            }
        } else {
            $issues['opcache_disabled'] = true;
        }
    } else {
        $issues['opcache_missing'] = true;
    }

    return [
        'score'  => max(0, $score),
        'issues' => $issues,
    ];
}

/**
 * Hosting level
 */
function elessi_get_hosting_level($score) {
    if ($score >= 70) {
        return 'excellent';
    }
    if ($score >= 55) {
        return 'good';
    }
    if ($score >= 40) {
        return 'weak';
    }
    
    return 'very_weak';
}

/**
 * Admin notice HTML Render
 */
add_action('admin_notices', function() {
    if (!current_user_can('manage_options')) {
        return;
    }

    if (get_option(elessi_get_cloud_notice_option_key())) {
        return;
    }
    
    $nonce = wp_create_nonce('elessi_cloud_notice');

    $result   = elessi_calculate_hosting_score();
    $level    = elessi_get_hosting_level($result['score']);
    $is_local = elessi_is_local_environment();

    if (!$is_local && !in_array($level, ['weak', 'very_weak'], true)) {
        return;
    }

    if ($is_local) {
        $title = '🚀 Prepare Elessi for a production-ready environment';
        $desc  = 'You are currently running Elessi on a local or temporary setup. When going live, we recommend a managed hosting platform optimized specifically for WooCommerce & Elessi — including free migration.';
    } else {
        $title = '🚀 Improve performance for your Elessi store';
        $desc  = 'Your current hosting configuration may limit speed, stability, and scalability when running Elessi & WooCommerce. Our managed hosting is fully optimized for this theme.';
    }
    ?>
    <style>
        .elessi-hosting-notice {
            border-left: 5px solid #f76b6a;
            padding: 15px 20px !important;
            background: #fffaf4;
        }
        .elessi-hosting-notice h3 {
            margin: 0 0 6px;
            font-size: 16px;
        }
        .elessi-hosting-notice .btn-elessi {
            display: inline-block;
            margin-top: 8px;
            padding: 6px 14px;
            background: #f76b6a;
            color: #fff;
            text-decoration: none;
            border-radius: 4px;
            font-weight: 600;
        }
        .elessi-hosting-notice .btn-elessi:hover {
            background: #f54543;
        }
    </style>

    <div class="notice elessi-hosting-notice is-dismissible" style="margin-top: 20px;">
        <h3><?php echo esc_html($title); ?></h3>
        <p><?php echo esc_html($desc); ?></p>
        <a class="btn-elessi" href="https://cloud.nasatheme.com/?utm_source=elessi_notice" target="_blank">
            Check hosting options →
        </a>
        <button type="button" class="notice-dismiss elessi-cloud-dismiss">
            <span class="screen-reader-text">Dismiss</span>
        </button>
    </div>
    <script>
    (function($){
        'use strict';

        $('.elessi-cloud-dismiss').on('click', function () {
            const $notice = $(this).closest('.elessi-hosting-notice');

            $.post(ajaxurl, {
                action: 'elessi_dismiss_cloud_notice',
                nonce: '<?php echo esc_js($nonce); ?>'
            });

            $notice.fadeOut(200, function () {
                $(this).remove();
            });
        });

    })(jQuery);
    </script>
    <?php
});

/**
 * Dismiss notice
 */
add_action('wp_ajax_elessi_dismiss_cloud_notice', function () {
    check_ajax_referer('elessi_cloud_notice', 'nonce');
    update_option(elessi_get_cloud_notice_option_key(), 1);
    wp_send_json_success();
});
