<?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() {
    if (defined('WP_DEBUG') && WP_DEBUG === true) {
        error_log('MMPro Calendar: Registering 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('popper-js', 'https://unpkg.com/popper.js/dist/umd/popper.min.js', array('jquery'), null, true);
    wp_register_script('tooltip-js', 'https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js', array('jquery', 'popper-js'), null, true);
    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')) {
        if (defined('WP_DEBUG') && WP_DEBUG === true) {
            error_log('MMPro Calendar: Registering ColorBox');
        }
        
        $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)) {
            if (defined('WP_DEBUG') && WP_DEBUG === true) {
                error_log('MMPro Calendar: Using ColorBox CDN');
            }
            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 {
            if (defined('WP_DEBUG') && WP_DEBUG === true) {
                error_log('MMPro Calendar: Using local ColorBox files');
            }
            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', 'tooltip-js', 'jquery-colorbox'), 
        MMPDB_PLUGIN_VERSION, 
        true
    );
}

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

// Register REST API endpoint for calendar events
add_action('rest_api_init', function () {
    register_rest_route('mmpro/v1', '/calendar/events', array(
        'methods' => 'GET',
        'callback' => 'mmpro_proxy_calendar_events',
        'permission_callback' => '__return_true'
    ));
    register_rest_route('mmpro/v1', '/calendar/categories', array(
        'methods' => 'GET',
        'callback' => 'mmpro_proxy_calendar_categories',
        'permission_callback' => '__return_true'
    ));
});

/**
 * Proxy function to fetch calendar events
 */
function mmpro_proxy_calendar_events($request) {
    $params = $request->get_params();
    
    // Build the target URL with all necessary parameters
    $target_url = add_query_arg(array(
        'AccountID' => $params['AccountID'],
        'ClubID' => $params['ClubID'],
        'EventCategoryIDs' => $params['EventCategoryIDs'],
        'start' => $params['start'],
        'end' => $params['end']
    ), rtrim($params['baseUrl'], '/'));
    
    // Set up the request arguments
    $args = array(
        'timeout' => 15,
        'headers' => array(
            'Accept' => 'application/json',
            'Origin' => get_site_url(),
            'Referer' => get_site_url()
        )
    );
    
    // Fetch the data server-side
    $response = wp_remote_get($target_url, $args);
    
    if (is_wp_error($response)) {
        error_log('MMPro Calendar Error: ' . $response->get_error_message());
        return new WP_Error('fetch_error', 'Failed to fetch events: ' . $response->get_error_message(), array('status' => 500));
    }
    
    $response_code = wp_remote_retrieve_response_code($response);
    if ($response_code !== 200) {
        error_log('MMPro Calendar Error: Received response code ' . $response_code);
        return new WP_Error('api_error', 'API returned error code: ' . $response_code, array('status' => $response_code));
    }
    
    $body = wp_remote_retrieve_body($response);
    
    // Attempt to decode JSON
    $data = json_decode($body);
    if (json_last_error() === JSON_ERROR_NONE) {
        return $data;
    }
    
    error_log('MMPro Calendar Error: Failed to parse JSON response - ' . json_last_error_msg());
    error_log('MMPro Calendar Response Body: ' . substr($body, 0, 1000)); // Log first 1000 chars of response
    
    return new WP_Error('parse_error', 'Failed to parse event data: ' . json_last_error_msg(), array('status' => 500));
}

/**
 * Proxy function to fetch calendar categories
 */
function mmpro_proxy_calendar_categories($request) {
    $params = $request->get_params();
    
    // Build the target URL with all necessary parameters
    $target_url = add_query_arg(array(
        'D' => $params['D']
    ), rtrim($params['baseUrl'], '/'));
    
    // Set up the request arguments
    $args = array(
        'timeout' => 15,
        'headers' => array(
            'Accept' => 'application/json',
            'Origin' => get_site_url(),
            'Referer' => get_site_url()
        )
    );
    
    // Fetch the data server-side
    $response = wp_remote_get($target_url, $args);
    
    if (is_wp_error($response)) {
        error_log('MMPro Calendar Error: ' . $response->get_error_message());
        return new WP_Error('fetch_error', 'Failed to fetch categories: ' . $response->get_error_message(), array('status' => 500));
    }
    
    $response_code = wp_remote_retrieve_response_code($response);
    if ($response_code !== 200) {
        error_log('MMPro Calendar Error: Received response code ' . $response_code);
        return new WP_Error('api_error', 'API returned error code: ' . $response_code, array('status' => $response_code));
    }
    
    $body = wp_remote_retrieve_body($response);
    
    // Attempt to decode JSON
    $data = json_decode($body);
    if (json_last_error() === JSON_ERROR_NONE) {
        return $data;
    }
    
    error_log('MMPro Calendar Error: Failed to parse JSON response - ' . json_last_error_msg());
    error_log('MMPro Calendar Response Body: ' . substr($body, 0, 1000)); // Log first 1000 chars of response
    
    return new WP_Error('parse_error', 'Failed to parse category data: ' . json_last_error_msg(), array('status' => 500));
}

function mmpro_calendar($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    
    // Ensure data path is set
    setDataPath();
    
    if (defined('WP_DEBUG') && WP_DEBUG === true) {
        error_log('DacDB+ Calendar Debug - Function Start');
        error_log('Attributes: ' . print_r($atts, true));
        error_log('Options: ' . print_r($options, true));
        error_log('Data Path: ' . $data_path);
    }
    
    $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('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('tooltip-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'];
        error_log('Using club_id from GET parameter: ' . $club_id);
    } elseif (isset($atts['club_id']) && !empty($atts['club_id'])) {
        $club_id = $atts['club_id'];
        error_log('Using club_id from shortcode attribute: ' . $club_id);
    } elseif (isset($options['dacdb_club']) && !empty($options['dacdb_club'])) {
        $club_id = $options['dacdb_club'];
        error_log('Using club_id from plugin options: ' . $club_id);
    }
    
    // Determine the default event category IDs
    $eids = '';
    if (isset($_GET['catids']) && !empty($_GET['catids'])) {
        $eids = $_GET['catids'];
        error_log('Using event IDs from GET catids: ' . $eids);
    } elseif (isset($_GET['catid']) && !empty($_GET['catid'])) {
        $eids = $_GET['catid'];
        error_log('Using event IDs from GET catid: ' . $eids);
    } elseif (isset($atts['catids']) && !empty($atts['catids'])) {
        $eids = $atts['catids'];
        error_log('Using event IDs from shortcode catids: ' . $eids);
    } elseif (isset($atts['catid']) && !empty($atts['catid'])) {
        $eids = $atts['catid'];
        error_log('Using event IDs from shortcode catid: ' . $eids);
    } elseif ($club_id == 0 && isset($options['district_events_types_page'])) {
        $eids = $options['district_events_types_page'];
        error_log('Using district event IDs from options: ' . $eids);
    } elseif (isset($options['club_events_types_page'])) {
        $eids = $options['club_events_types_page'];
        error_log('Using club event IDs from options: ' . $eids);
    }

    if (empty($club_id)) {
        error_log('WARNING: Club ID is empty after all checks');
    }
    if (empty($eids)) {
        error_log('WARNING: Event IDs are empty after all checks');
    }

    // 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')));
    
    if (defined('WP_DEBUG') && WP_DEBUG === true) {
        error_log('Calendar View: ' . $view);
    }

    // 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));

    $sector = isset($_GET['sector']) ? $_GET['sector'] : (isset($atts['sector']) ? $atts['sector'] : '');

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

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

    // Build the event URL with validated parameters
    $event_url = rtrim($data_path, '/') . '/R_GetEventsV2.cfm';
    $event_params = array(
        'AccountID' => $district_id,
        'ClubID' => $club_id,
        'EventCategoryIDs' => $eids
    );
    if (!empty($sector)) {
        $event_params['Sector'] = $sector;
    }
    
    // Instead of direct URLs, we'll use our proxy endpoints
    $proxy_event_url = rest_url('mmpro/v1/calendar/events');
    $proxy_category_url = rest_url('mmpro/v1/calendar/categories');

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

    // Update the localized data to use proxy URLs
    wp_localize_script('mmpro-calendar', 'mmproCalendarConfig', array(
        'eventUrl' => $proxy_event_url,
        'eventCategoryUrl' => $proxy_category_url,
        'eventBaseUrl' => $event_url,
        'categoryBaseUrl' => $eventID_json,
        'initialView' => $view,
        'views' => $views,
        'accountId' => $district_id,
        'clubId' => $club_id,
        'eventCategoryIds' => $eids
    ));

    // 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) {
                // console.warn("Failed to inject jQuery into iframe:", e); // Removed console.warn
            }
        }

        // Override ColorBox onComplete to inject jQuery
        jQuery(document).on("cbox_complete", function() {
            var iframe = document.getElementById("colorbox")?.querySelector("iframe"); // Added optional chaining for safety
            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;
                    }
                    </style>";
    
    // Wrap calendar in BEM-structured 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;
}