<?php
/**
 * Template Name: Master Events
 * Description: Template for the master trainer's events management page
 */

// Define constant to indicate we are in a page template
if (!defined('HVAC_IN_PAGE_TEMPLATE')) {
    define('HVAC_IN_PAGE_TEMPLATE', true);
}

get_header();

// Check master trainer permissions FIRST
if (!current_user_can('hvac_master_events_view') && !current_user_can('manage_options')) {
    ?>
    <div class="hvac-page-wrapper">
        <div class="container">
            <h1>Access Denied</h1>
            <p>You do not have permission to access this page.</p>
            <p>If you believe this is an error, please contact an administrator.</p>
            <a href="<?php echo home_url(); ?>" class="button">Return to Home</a>
        </div>
    </div>
    <?php
    get_footer();
    exit;
}

// Render master trainer navigation
if (class_exists('HVAC_Master_Menu_System')) {
    $master_menu = HVAC_Master_Menu_System::instance();
    $master_menu->render_master_menu();
}

// Render breadcrumbs
if (class_exists('HVAC_Breadcrumbs')) {
    echo HVAC_Breadcrumbs::instance()->render_breadcrumbs();
}

echo '<div class="hvac-page-wrapper hvac-master-events-page">';
echo '<div class="container">';

// Render the master events content
echo '<h1>Events Management</h1>';
echo '<div class="hvac-master-events-content">';

// First try the_content() to get any shortcode from post_content
ob_start();
if (have_posts()) {
    while (have_posts()) {
        the_post();
        the_content();
    }
}
$post_content = ob_get_clean();

// If post_content is empty or just contains the shortcode without rendering, try direct shortcode
if (empty(trim(strip_tags($post_content))) || strpos($post_content, '[hvac_master_events]') !== false) {
    // Ensure the shortcode class is initialized
    if (class_exists('HVAC_Master_Events_Overview')) {
        $instance = HVAC_Master_Events_Overview::instance();
        if (method_exists($instance, 'render_events_overview')) {
            echo $instance->render_events_overview();
        } else {
            echo do_shortcode('[hvac_master_events]');
        }
    } else {
        echo '<div class="hvac-notice">Master events system is not available. Please contact an administrator.</div>';
    }
} else {
    echo $post_content;
}

echo '</div>'; // .hvac-master-events-content
echo '</div>'; // .container
echo '</div>'; // .hvac-page-wrapper

get_footer();