<?php
/**
 * Calendar functionality for Member Minder Pro plugin
 * 
 * This file contains the calendar shortcode implementation.
 * It requires the following global variables to be set:
 * - $fDebug: Debug flag
 * - $data_path: Path to data files
 * - $file_path: Path to file storage
 * - $options: Plugin options
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Register calendar scripts and styles
 */
function mmpro_register_calendar_assets() {
    // Register styles
    wp_register_style('mmpro-calendar-style', plugins_url('css/show-calendar.css', dirname(__FILE__)), array(), MMPDB_PLUGIN_VERSION);
    wp_register_style('mmpro-tooltip', plugins_url('css/tooltip.css', dirname(__FILE__)), array(), MMPDB_PLUGIN_VERSION);
    
    // Register scripts - using WordPress's jQuery
    wp_register_script('fullcalendar-bundle', 'https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js', array('jquery'), '6.1.15', true);
    
    // Ensure ColorBox is registered before we depend on it
    if (!wp_script_is('jquery-colorbox', 'registered')) {
        $colorbox_cdn_js = 'https://cdn.jsdelivr.net/gh/jackmoore/colorbox@1.6.4/jquery.colorbox-min.js';
        $colorbox_cdn_css = 'https://cdn.jsdelivr.net/gh/jackmoore/colorbox@1.6.4/example1/colorbox.css';
        
        if (url_exists($colorbox_cdn_js) && url_exists($colorbox_cdn_css)) {
            wp_register_script('jquery-colorbox', $colorbox_cdn_js, array('jquery'), '1.6.4', true);
            wp_register_style('jquery-colorbox-style', $colorbox_cdn_css, array(), '1.6.4');
        } else {
            wp_register_script('jquery-colorbox', plugins_url('js/vendor/jquery.colorbox-min.js', dirname(__FILE__)), array('jquery'), '1.6.4', true);
            wp_register_style('jquery-colorbox-style', plugins_url('css/vendor/colorbox.css', dirname(__FILE__)), array(), '1.6.4');
        }
    }
    
    wp_register_script('mmpro-calendar', plugins_url('js/show-calendar.js', dirname(__FILE__)), 
        array('jquery', 'fullcalendar-bundle', 'tippy-js', 'jquery-colorbox'), 
        MMPDB_PLUGIN_VERSION, 
        true
    );
}

// Register assets on init
add_action('init', 'mmpro_register_calendar_assets');

function mmpro_calendar($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    
    // Ensure data path is set
    setDataPath();
    
    $calendar = "";
    $views = "dayGridMonth,listMonth";

    // Ensure assets are registered (in case init hook hasn't run)
    if (!wp_script_is('mmpro-calendar', 'registered')) {
        mmpro_register_calendar_assets();
    }

    // Enqueue required styles and scripts for calendar
    wp_enqueue_style('mmpro-calendar-style');
    wp_enqueue_style('tippy-css');
    wp_enqueue_style('mmpro-tooltip');
    wp_enqueue_style('jquery-colorbox-style');
    
    wp_enqueue_script('jquery');
    wp_enqueue_script('jquery-colorbox');
    wp_enqueue_script('popper-js');
    wp_enqueue_script('tippy-js');
    wp_enqueue_script('fullcalendar-bundle');
    wp_enqueue_script('mmpro-calendar');

    // plugin parameters
    // All variable values are set in order: 
    //    URL string > shortcode attribute > plugin settings > default value.

    // Determine the club ID to render in the calendar (if any)
    $club_id = '';
    if (isset($_GET['club_id']) && !empty($_GET['club_id'])) {
        $club_id = $_GET['club_id'];
    } elseif (isset($atts['club_id']) && !empty($atts['club_id'])) {
        $club_id = $atts['club_id'];
    } elseif (isset($options['dacdb_club']) && !empty($options['dacdb_club'])) {
        $club_id = $options['dacdb_club'];
    }
    
    // Convert club_id to integer for proper comparison
    $club_id = !empty($club_id) ? intval($club_id) : 0;
    
    // Determine the default event category IDs
    $eids = '';
    if (isset($_GET['catids']) && !empty($_GET['catids'])) {
        $eids = $_GET['catids'];
    } elseif (isset($_GET['catid']) && !empty($_GET['catid'])) {
        $eids = $_GET['catid'];
    } elseif (isset($atts['catids']) && !empty($atts['catids'])) {
        $eids = $atts['catids'];
    } elseif (isset($atts['catid']) && !empty($atts['catid'])) {
        $eids = $atts['catid'];
    } elseif ($club_id === 0) {
        // District site - only use district settings
        if (isset($options['district_events_types_page']) && !empty($options['district_events_types_page'])) {
            $eids = $options['district_events_types_page'];
        }
    } else {
        // Club site - only use club settings
        if (isset($options['club_events_types_page']) && !empty($options['club_events_types_page'])) {
            $eids = $options['club_events_types_page'];
        }
    }

    // Set the layout of the rendered calendar
    $view = (isset($_GET['view']) && in_array($_GET['view'], ['list', 'listMonth', '1'])) ? 'listMonth' : (isset($atts['view']) && in_array($atts['view'], ['list', 'listMonth', '1']) ? 'listMonth' : (isset($_GET['view']) && in_array($_GET['view'], ['month', '0', 'dayGridMonth']) || (isset($atts['view']) && in_array($atts['view'], ['month', '0', 'dayGridMonth'])) ? 'dayGridMonth' : (!empty($options['cal_display']) && in_array($options['cal_display'], ['listMonth', 'dayGridMonth']) ? $options['cal_display'] : 'dayGridMonth')));

    // Set the default calendar limit
    $callimit = (isset($_GET['cal_limit']) && $_GET['cal_limit'] >= 1 && $_GET['cal_limit'] <= 9) ? $_GET['cal_limit'] : (isset($atts['cal_limit']) && $atts['cal_limit'] >= 1 && $atts['cal_limit'] <= 9 ? $atts['cal_limit'] : (!empty($options['cal_limit']) && $options['cal_limit'] >= 1 && $options['cal_limit'] <= 9 ? $options['cal_limit'] : 5));

    // Get sector parameter from shortcode or GET
    $sector = isset($_GET['sector']) ? $_GET['sector'] : (isset($atts['sector']) ? $atts['sector'] : '');

    // Validate sector is a string if provided
    if (!empty($sector) && !is_string($sector)) {
        $sector = '';
    }

    // Build URLs for XML and json sources
    $district_id = isset($options['dacdb_district']) ? $options['dacdb_district'] : '';
    $eids = !empty($eids) ? $eids : '';
    $sector = !empty($sector) ? $sector : '';

    // Validate required parameters
    if (empty($district_id)) {
        return '<div class="alert alert-danger">Calendar configuration error: District ID is not set</div>';
    }

    // Build the event URL
    $event_url = rtrim($data_path, '/') . '/R_GetEventsV2.cfm';
    
    // Build the event category URL
    $eventID_json = rtrim($data_path, '/') . '/wp_eventcategory.cfm';
    $eventID_json = add_query_arg(array('D' => $district_id), $eventID_json);

    // Create calendar configuration
    $calendar_config = array(
        'eventUrl' => $event_url,
        'eventCategoryUrl' => $eventID_json,
        'initialView' => $view,
        'views' => $views,
        'accountId' => $district_id,
        'clubId' => $club_id,
        'eventCategoryIds' => $eids,
        'sector' => $sector
    );
    
    // Localize script with configuration
    wp_localize_script('mmpro-calendar', 'mmproCalendarConfig', $calendar_config);

    // Add initialization script with jQuery injection for ColorBox iframes
    wp_add_inline_script('mmpro-calendar', '
        // Function to inject jQuery into ColorBox iframes
        function injectjQuery(iframe) {
            try {
                if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.jQuery = jQuery;
                    iframe.contentWindow.$ = jQuery;
                }
            } catch (e) {
                // Silent fail
            }
        }

        // Override ColorBox onComplete to inject jQuery
        jQuery(document).on("cbox_complete", function() {
            var iframe = document.getElementById("colorbox")?.querySelector("iframe");
            if (iframe) {
                injectjQuery(iframe);
            }
        });
    ', 'after');

    // Add scoped styles for calendar
    $calendar .= "<style>
                    .mmpro-calendar .entry-content tr td {
                        padding: 4px 4px !important;
                    }
                    .mmpro-calendar .fc-timegrid-event {
                        line-height: 1.1em;
                    }
                    /* Ensure calendar styles don't leak */
                    .mmpro-calendar {
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;
                    }
                    .mmpro-calendar * {
                        box-sizing: border-box;
                    }
                    /* Override any theme font settings */
                    .mmpro-calendar .fc {
                        font-family: inherit;
                    }
                    .mmpro-calendar .fc button {
                        font-family: inherit;
                    }
                    /* Calendar container styling */
                    .mmpro-calendar {
                        position: relative;
                        z-index: auto !important;
                    }
                    .mmpro-calendar .fc {
                        z-index: auto !important;
                    }
                    .mmpro-calendar .fc-view-harness {
                        z-index: auto !important;
                    }
                    </style>";
    
    // Wrap calendar in container
    $calendar .= "<div class='mmpro-calendar'>";
    $calendar .= "<div class='mmpro-calendar__container'></div>";
    $calendar .= "<div class='mmpro-calendar__color-key'></div>";
    $calendar .= "</div>";

    return $calendar;
}

/**
 * Debug shortcode to test calendar API with sector filtering
 * Usage: [mmpro_test_calendar sector="South Bay"]
 */
function mmpro_test_calendar_shortcode($atts) {
    $atts = shortcode_atts(array(
        'sector' => '',
        'show_response' => 'false'
    ), $atts);   
    if (!current_user_can('manage_options')) {
        return '<p>Access denied. Admin privileges required.</p>';
    }
    
    $sector = sanitize_text_field($atts['sector']);
    
    // Validate that sector is a string if provided
    if (!empty($sector) && !is_string($sector)) {
        return '<p><strong>Error:</strong> Sector must be a string (e.g., "South Bay", "East Bay", "Southern Region")</p>';
    }
    $show_response = filter_var($atts['show_response'], FILTER_VALIDATE_BOOLEAN);
    
    $result = mmpro_test_calendar_api($sector);
    
    $output = '<div style="background: #f5f5f5; padding: 15px; border: 1px solid #ddd; margin: 10px 0;">';
    $output .= '<h3>Calendar API Test Results</h3>';
    
    if (is_string($result)) {
        $output .= '<p><strong>Error:</strong> ' . esc_html($result) . '</p>';
    } else {
        $output .= '<p><strong>URL:</strong> ' . esc_url($result['url']) . '</p>';
        $output .= '<p><strong>Response Code:</strong> ' . esc_html($result['response_code']) . '</p>';
        $output .= '<p><strong>JSON Valid:</strong> ' . ($result['json_valid'] ? 'Yes' : 'No') . '</p>';
        $output .= '<p><strong>Event Count:</strong> ' . esc_html($result['event_count']) . '</p>';
        $output .= '<p><strong>Parameters:</strong> <pre>' . esc_html(print_r($result['params'], true)) . '</pre></p>';
        
        if (!$result['json_valid'] && $result['json_error']) {
            $output .= '<p><strong>JSON Error:</strong> ' . esc_html($result['json_error']) . '</p>';
        }
    }
    
    $output .= '</div>';
    
    return $output;
}
add_shortcode('mmpro_test_calendar', 'mmpro_test_calendar_shortcode');

/**
 * Debug helper function to test API directly
 */
function mmpro_test_calendar_api($sector = '') {
    global $options, $data_path;
    
    if (empty($options['dacdb_district'])) {
        return 'Error: District ID not set';
    }
    
    $api_url = rtrim($data_path, '/') . '/R_GetEventsV2.cfm';
    $params = array(
        'AccountID' => $options['dacdb_district'],
        'ClubID' => $options['dacdb_club'] ?? '0',
        'EventCategoryIDs' => $options['club_events_types_page'] ?? '',
        'start' => date('Y-m-d'),
        'end' => date('Y-m-d', strtotime('+1 month'))
    );
    
    if (!empty($sector)) {
        $params['Sector'] = $sector;
        $params['sector'] = $sector;
    }
    
    $target_url = add_query_arg($params, $api_url);
    
    $args = array(
        'timeout' => 15,
        'headers' => array(
            'Accept' => 'application/json',
            'Origin' => get_site_url(),
            'Referer' => get_site_url()
        )
    );
    
    $response = wp_remote_get($target_url, $args);
    
    if (is_wp_error($response)) {
        return 'Error: ' . $response->get_error_message();
    }
    
    $response_code = wp_remote_retrieve_response_code($response);
    $body = wp_remote_retrieve_body($response);
    
    // Try to parse JSON to see if it's valid
    $json_data = json_decode($body, true);
    $json_error = json_last_error();
    $json_error_msg = $json_error !== JSON_ERROR_NONE ? json_last_error_msg() : null;
    $event_count = $json_error === JSON_ERROR_NONE ? count($json_data) : 0;
    
    $result = array(
        'url' => $target_url,
        'response_code' => $response_code,
        'body_length' => strlen($body),
        'json_valid' => $json_error === JSON_ERROR_NONE,
        'json_error' => $json_error_msg,
        'event_count' => $event_count,
        'params' => $params
    );
    
    return $result;
}