<?php
// If user not in admin area, abort.
defined('DRAGONIZER_ADMIN_INIT') || die();

echo '<style>
        .dragonizer-status{background:#fff;border-radius:6px;box-shadow:rgba(0,0,0,.05) 0 1px 2px 0!important;border:1px solid #eee;margin:30px 0;padding:25px}
        .dragonizer-title{font-size:20px;margin:0 0 25px;padding-bottom:15px;border-bottom:1px solid #e0e0e0;color:#333}
        .dragonizer-grid{display:flex;flex-wrap:wrap;gap:25px;align-items:stretch}
        .dragonizer-column{flex:1 1 calc(50% - 12.5px);display:flex;flex-direction:column}
        .dragonizer-main{border-radius:6px;padding:20px;display:flex;flex-direction:column;flex:1;transition:box-shadow .3s ease}
        .dragonizer-status-content{flex:1;display:flex;flex-direction:column}
        .dragonizer-status-content h3{font-size:18px;margin:0 0 12px;color:#333}
        .dragonizer-status-content p{margin:0 0 8px;color:#555;line-height:2em}
        .dragonizer-status-action{color:#0073aa;margin-top:auto}
        .dragonizer-status-success{background-color:#f0f8f0}
        .dragonizer-status-info{background-color:#f0f8ff}
        .dragonizer-status-warning{background-color:#fff8e5}
        .dragonizer-status-error{background-color:#fff0f0}
        .dragonizer-details{background:#f9f9f9;border-radius:6px;padding:20px;height:100%;display:flex;flex-direction:column;justify-content:center}
        .dragonizer-details ul{list-style-type:none;margin:0;padding:0}
        .dragonizer-details li{display:flex;align-items:center;margin-bottom:15px;color:#555}
        .dragonizer-details .dashicons{color:#82878c;margin-right:12px;font-size:18px}
        @media screen and (max-width:782px){.dragonizer-grid{flex-direction:column}.dragonizer-column{flex:1 1 auto}}
        .dragonizer-details li strong{margin-right:.25em}
        .dragonizer-details li .dashicons+strong{margin-right:.25em}
        .dragonizer-details li{white-space:nowrap}
        .dragonizer-details li strong::after{content:"\00a0"}
    </style>';

function dragonizer_display_error($type, $message, $title = '',  $action = '')
{
    $status_class = 'dragonizer-status-' . $type;

    echo '<div style="margin:35px 0" class="dragon-hidden dragonizer-column">';
    echo '<div class="dragonizer-main ' . esc_attr($status_class) . '">';
    echo '<div class="dragonizer-status-content">';
    if (!empty($title)) {
        echo '<h3>' . esc_html($title) . '</h3>';
    }
    echo '<p>' . esc_html($message) . '</p>';
    if (!empty($action)) {
        echo '<p class="dragonizer-status-action">' . esc_html($action) . '</p>';
    }
    echo '</div>';
    echo '</div>';
    echo '</div>';
}

function dragonizer_display_status_card($type, $current_time, $next_scheduled, $last_run, $expected_interval, $two_column = false)
{
    echo '<div class="dragonizer-column">';

    $time_until_next_run = $next_scheduled - $current_time;
    $time_since_last_run = $current_time - $last_run;
    $time_left = $expected_interval - $time_since_last_run;

    $max_delay = 1800; // 30 minutes in seconds

    if (!$next_scheduled) {
        $status = 'warning';
        $title = sprintf(__('%s Not Scheduled', 'dragonizer'), ucfirst($type));
        $message = sprintf(__('Automatic %s is not scheduled.', 'dragonizer'), $type);
        $action = __('Action: Enable WordPress Cron or set up a server cron job.', 'dragonizer');
    } elseif (!$last_run) {
        $status = 'info';
        $title = sprintf(__('%s Ready to Begin', 'dragonizer'), ucfirst($type));
        $message = sprintf(__('Automatic %s is set up and will run soon.', 'dragonizer'), $type);
        $action = sprintf(__('First run scheduled in: %s', 'dragonizer'), human_time_diff($current_time, $next_scheduled));
    } elseif ($time_until_next_run < -$max_delay) {
        $status = 'error';
        $title = sprintf(__('%s Significantly Delayed', 'dragonizer'), ucfirst($type));
        $message = sprintf(__('%s is %s overdue.', 'dragonizer'), ucfirst($type), human_time_diff($current_time, $current_time - $time_left));
        $action = __('Action: Verify WordPress Cron functionality or set up a server side cron.', 'dragonizer');
    } elseif ($time_until_next_run < 0) {
        $status = 'warning';
        $title = sprintf(__('%s Slightly Delayed', 'dragonizer'), ucfirst($type));
        $message = sprintf(__('%s is %s overdue.', 'dragonizer'), ucfirst($type), human_time_diff($current_time, $current_time - $time_left));
        $action = __('Action: Monitor the situation. If delays persist, check WordPress Cron settings.', 'dragonizer');
    } else {
        $status = 'success';
        $title = sprintf(__('%s Operating Normally', 'dragonizer'), ucfirst($type));
        $message = sprintf(__('Last run: %s ago. Next run: %s.', 'dragonizer'), human_time_diff($last_run, $current_time), human_time_diff($current_time, $next_scheduled));
        $action = __('Status: Functioning correctly. No action needed.', 'dragonizer');
    }

    echo '<div class="dragonizer-main dragonizer-status-' . esc_attr($status) . '">';
    echo '<div class="dragonizer-status-content">';
    echo '<h3>' . esc_html($title) . '</h3>';
    echo '<p>' . esc_html($message) . '</p>';
    echo '<p class="dragonizer-status-action">' . esc_html($action) . '</p>';
    echo '</div>';
    echo '</div>';

    if ($two_column) {
        echo '</div>';
        echo '<div class="dragonizer-column">';
        echo '<div class="dragonizer-details">';
    } else {
        echo '<div class="dragonizer-details" style="margin-top:20px">';
    }

    echo '<ul>';
    if ($last_run) {
        echo '<li><span class="dashicons dashicons-backup"></span> <strong>' . __('Last Run:', 'dragonizer') . '</strong> ' . human_time_diff($last_run, $current_time) . ' ' . __('ago', 'dragonizer') . '</li>';
        echo '<li><span class="dashicons dashicons-calendar-alt"></span> <strong>' . __('Next Run:', 'dragonizer') . '</strong> ' .
            ($time_until_next_run < 0 ? __('Overdue', 'dragonizer') : human_time_diff($current_time, $next_scheduled)) . '</li>';
    }
    echo '<li><span class="dashicons dashicons-clock"></span> <strong>' . __('Interval:', 'dragonizer') . '</strong> ' . human_time_diff(0, $expected_interval) . '</li>';
    echo '</ul>';
    echo '</div>';

    echo '</div>';
}

function dragonizer_check_cron_status()
{
    $status = dragonizer_test_cron_spawn();

    if (is_wp_error($status)) {
        $error_code = $status->get_error_code();
        $error_message = $status->get_error_message();
        if ('disable_wp_cron' === $error_code) {
            dragonizer_display_error('error', $error_message, __('Cron Information', 'dragonizer'));
        } elseif ('alternate_wp_cron' === $error_code) {
            dragonizer_display_error('info', $error_message, __('Cron Information', 'dragonizer'));
        } else {
            $guidance = dragonizer_get_cron_error_guidance($error_message);
            dragonizer_display_error('error', $error_message, __('Cron Error', 'dragonizer'), $guidance);
            return 'error';
        }
        return 'warning';
    }
    return true;
}

function dragonizer_get_cron_error_guidance($error_message)
{
    if (strpos($error_message, 'cURL error 6') !== false) {
        $guidance = __('This indicates a problem with your domain\'s DNS configuration or your server\'s DNS settings. Check your domain settings and contact your hosting provider for assistance.', 'dragonizer');
    } elseif (strpos($error_message, 'cURL error 7') !== false) {
        $guidance = __('This could be related to your HTTPS configuration, firewall settings, or network connectivity. Check your server\'s security settings and contact your hosting provider if the issue persists.', 'dragonizer');
    } elseif (strpos($error_message, 'cURL error 28') !== false) {
        $guidance = __('This suggests a network connectivity problem preventing your server from making loopback requests. Contact your hosting provider to investigate and resolve the issue.', 'dragonizer');
    } elseif (strpos($error_message, 'cURL error 35') !== false) {
        $guidance = __('Your site\'s secure connection (HTTPS) is encountering an issue. This may be due to misconfigured SSL/TLS settings or a problem with your server\'s self-connection capabilities.', 'dragonizer');
    } elseif (strpos($error_message, '401') !== false || strpos($error_message, '403') !== false) {
        $guidance = __('An access control restriction is preventing your server from accessing wp-cron.php. Check for BasicAuth, firewall rules, security plugins, or .htaccess restrictions.', 'dragonizer');
    } elseif (strpos($error_message, '404') !== false) {
        $guidance = __('The wp-cron.php file is missing. Try reinstalling WordPress from the Dashboard → Updates screen.', 'dragonizer');
    } elseif (strpos($error_message, '5') !== false && strpos($error_message, '5xx') === false) {
        $guidance = __('A server error is preventing the cron spawner from running. Check your server\'s error logs and contact your hosting provider for assistance.', 'dragonizer');
    } else {
        $guidance = __('An unexpected error occurred. Please check your server configuration and contact your hosting provider for assistance.', 'dragonizer');
    }

    return $guidance;
}

function dragonizer_test_cron_spawn()
{
    global $wp_version;

    if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
        return new WP_Error('disable_wp_cron', __('The DISABLE_WP_CRON constant is set to true. WP-Cron spawning is disabled.', 'dragonizer'));
    }

    if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
        return new WP_Error('alternate_wp_cron', __('The ALTERNATE_WP_CRON constant is set to true.', 'dragonizer'));
    }

    $sslverify     = version_compare($wp_version, '4.0', '<');
    $doing_wp_cron = sprintf('%.22F', microtime(true));

    $cron_request = apply_filters('cron_request', array(
        'url'  => add_query_arg('doing_wp_cron', $doing_wp_cron, site_url('wp-cron.php')),
        'key'  => $doing_wp_cron,
        'args' => array(
            'timeout'   => 3,
            'blocking'  => true,
            'sslverify' => apply_filters('https_local_ssl_verify', $sslverify),
        ),
    ), $doing_wp_cron);

    $cron_request['args']['blocking'] = true;

    $result = wp_remote_post($cron_request['url'], $cron_request['args']);

    if (is_wp_error($result)) {
        return $result;
    } elseif (wp_remote_retrieve_response_code($result) >= 300) {
        return new WP_Error('unexpected_http_response_code', sprintf(
            /* translators: %s: The HTTP response code. */
            __('Unexpected HTTP response code: %s', 'dragonizer'),
            intval(wp_remote_retrieve_response_code($result))
        ));
    } else {
        return true;
    }
}
