<?php
/**
 * Training Calendar List View
 * Displays upcoming classes with filters
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

// Add shortcode for calendar list view
if (!shortcode_exists('training_calendar')) {
    add_shortcode('training_calendar', 'dts_render_training_calendar');
}

// Helper function to convert 24-hour to 12-hour time
if (!function_exists('dts_convert_to_12hour')) {
function dts_convert_to_12hour($time24) {
    if (empty($time24)) return '';
    
    if (stripos($time24, 'am') !== false || stripos($time24, 'pm') !== false) {
        return $time24;
    }
    
    $time_obj = DateTime::createFromFormat('H:i', $time24);
    if (!$time_obj) {
        $time_obj = DateTime::createFromFormat('H:i:s', $time24);
    }
    
    if ($time_obj) {
        return $time_obj->format('g:i a');
    }
    
    return $time24;
}
}

if (!function_exists('dts_render_training_calendar')) {
function dts_render_training_calendar($atts) {
    $atts = shortcode_atts(array(
        'days' => 60,
        'show_filters' => true,
    ), $atts);
    
    $output = '<div class="training-calendar-list" style="padding: 0 !important; margin: 0 !important;">';
    
    if ($atts['show_filters']) {
        $output .= dts_render_calendar_filters();
    }
    
    $upcoming_classes = dts_get_upcoming_class_instances($atts['days']);
    
    if (empty($upcoming_classes)) {
        $output .= '<p>No upcoming classes scheduled.</p>';
    } else {
        $classes_by_date = array();
        foreach ($upcoming_classes as $class) {
            $date_key = $class['date']->format('Y-m-d');
            if (!isset($classes_by_date[$date_key])) {
                $classes_by_date[$date_key] = array();
            }
            $classes_by_date[$date_key][] = $class;
        }
        
        ksort($classes_by_date);
        
        $output .= '<div class="calendar-list-container">';
        foreach ($classes_by_date as $date_string => $day_classes) {
            $date_obj = DateTime::createFromFormat('Y-m-d', $date_string);
            
            $output .= '<div class="calendar-date-group" data-date="' . $date_string . '">';
            $output .= '<h3 class="calendar-date-header" style="background: #f15bb5; color: white; padding: 12px 20px; margin: 0 0 0 0;">' . $date_obj->format('l, F j, Y') . '</h3>';
            
            $output .= '<div class="calendar-date-classes" style="background: #EEE; padding: 20px;">';
            
            usort($day_classes, function($a, $b) {
                return strcmp($a['time'], $b['time']);
            });
            
            foreach ($day_classes as $class) {
                $topic_slug = sanitize_title($class['topic']);
                $type_slug = sanitize_title($class['type']);
                
                if ($topic_slug === 'puppies-adolescents' || $topic_slug === 'puppies-and-adolescents') {
                    $topic_slug = 'puppies-adolescents';
                }
                
                // Get data
                $joinable_id = $class['joinable_id'];
                $featured_image = get_the_post_thumbnail_url($joinable_id, 'medium');
                $duration = get_post_meta($joinable_id, 'duration', true);
                $series_length = get_post_meta($joinable_id, 'series_length', true);
                $price = get_post_meta($joinable_id, 'price', true);
                $excerpt = get_the_excerpt($joinable_id);
                $short_description = get_post_meta($joinable_id, 'short_description', true);
                
                // Get all topics
                $topics = wp_get_post_terms($joinable_id, 'training_topic', array('fields' => 'names'));
                $topics_list = !empty($topics) ? implode(', ', $topics) : '';
                
                $card_classes = 'calendar-class-item';
                if ($class['schedule_type'] === 'series') {
                    $card_classes .= ' series-class';
                }
                
                // Card with three-column layout
                $output .= '<div class="' . $card_classes . '" ';
                $output .= 'data-topic="' . esc_attr($topic_slug) . '" ';
                $output .= 'data-type="' . esc_attr($type_slug) . '" ';
                $output .= 'data-joinable-id="' . esc_attr($joinable_id) . '">';
                
                // Column 1: Image (25%)
                if ($featured_image) {
                    $output .= '<div class="card-image-column">';
                    $output .= '<img src="' . esc_url($featured_image) . '" class="card-image" alt="">';
                    $output .= '</div>';
                }
                
                // Column 2: Main content (50%)
                $output .= '<div class="card-main-content">';
                
                // Type label
                $output .= '<div class="type-label">';
                $output .= esc_html($class['type']);
                if ($class['schedule_type'] === 'series') {
                    $output .= ' <span class="fixed-badge">FIXED START DATE</span>';
                }
                $output .= '</div>';
                
                // Title
                $output .= '<h3 class="card-title">' . esc_html($class['title']) . '</h3>';
                
                // Excerpt
                if ($excerpt) {
                    $output .= '<p class="card-excerpt">' . esc_html(wp_trim_words($excerpt, 20)) . '</p>';
                }
                
                // Short description
                if ($short_description) {
                    $output .= '<p class="card-short-description">' . esc_html($short_description) . '</p>';
                }
                
                // Availability info
                $available = $class['capacity'] - $class['enrolled'];
                $output .= '<div class="availability-info">';
                if ($available > 0) {
                    $output .= '<span class="spots-available">' . $available . ' spots available</span>';
                } else {
                    $output .= '<span class="class-full">CLASS FULL</span>';
                }
                $output .= '</div>';
                
                // Buttons
                $output .= '<div class="card-buttons">';
                if ($available > 0) {
                    $register_url = dts_get_registration_url($joinable_id, $date_string, $class['time']);
                    $output .= '<a href="' . esc_url($register_url) . '" class="btn-register">REGISTER</a>';
                } else {
                    $output .= '<button class="btn-register disabled" disabled>CLASS FULL</button>';
                }
                $output .= '<a href="' . get_permalink($joinable_id) . '" class="btn-info">MORE INFORMATION</a>';
                $output .= '</div>';
                
                $output .= '</div>'; // End main content
                
                // Column 3: Info sidebar (25%)
                $output .= '<div class="card-info-sidebar">';
                
                // Time
                $output .= '<div class="info-item">';
                $output .= '<div class="info-label">Time</div>';
                $output .= '<div class="info-value">' . esc_html(dts_convert_to_12hour($class['time'])) . '</div>';
                $output .= '</div>';
                
                // Duration
                if ($duration) {
                    $output .= '<div class="info-item">';
                    $output .= '<div class="info-label">Duration</div>';
                    $output .= '<div class="info-value">' . esc_html($duration) . '</div>';
                    $output .= '</div>';
                }
                
                // Series Length
                if ($series_length) {
                    $output .= '<div class="info-item">';
                    $output .= '<div class="info-label">Length</div>';
                    $output .= '<div class="info-value">' . esc_html($series_length) . '</div>';
                    $output .= '</div>';
                }
                
                // Price
                if ($price) {
                    $output .= '<div class="info-item">';
                    $output .= '<div class="info-label">Price</div>';
                    $output .= '<div class="info-value">$' . esc_html($price) . '</div>';
                    $output .= '</div>';
                }
                
                // Topics
                if ($topics_list) {
                    $output .= '<div class="info-item">';
                    $output .= '<div class="info-label">Topics</div>';
                    $output .= '<div class="info-value">' . esc_html($topics_list) . '</div>';
                    $output .= '</div>';
                }
                
                $output .= '</div>'; // End info sidebar
                
                $output .= '</div>'; // End card
            }
            
            $output .= '</div>'; // .calendar-date-classes
            $output .= '</div>'; // .calendar-date-group
        }
        $output .= '</div>'; // .calendar-list-container
    }
    
    $output .= '</div>'; // .training-calendar-list
    
    return $output;
}
}

if (!function_exists('dts_render_calendar_filters')) {
function dts_render_calendar_filters() {
    // Get all upcoming classes to see what topics/types are actually in use
    $upcoming_classes = dts_get_upcoming_class_instances(60);
    
    // Collect unique topics and types that are actually scheduled
    $active_topics = array();
    $active_types = array();
    
    foreach ($upcoming_classes as $class) {
        $topic_slug = sanitize_title($class['topic']);
        $type_slug = sanitize_title($class['type']);
        
        // Normalize the topic slug
        if ($topic_slug === 'puppies-adolescents' || $topic_slug === 'puppies-and-adolescents') {
            $topic_slug = 'puppies-adolescents';
        }
        
        $active_topics[$topic_slug] = $class['topic'];
        $active_types[$type_slug] = $class['type'];
    }
    
    $output = '<div class="calendar-filters" style="background: white; padding: 20px; border-radius: 0px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">';
    
    // Topic filters - only show if there are topics
    if (!empty($active_topics)) {
        $output .= '<div class="filter-group" style="margin-bottom: 15px;">';
        $output .= '<label style="display: inline-block; min-width: 60px; font-weight: bold; margin-right: 10px;">Topic:</label>';
        $output .= '<div class="filter-buttons" data-filter-type="topic" style="display: inline-flex; gap: 10px; flex-wrap: wrap;">';
        $output .= '<button class="filter-btn active" data-filter="all" style="padding: 5px 15px; border: 1px solid #ddd; background: #007cba; color: white; border-radius: 0px; cursor: pointer;">All Topics</button>';
        
        // Define the topic order we want
        $topic_order = array(
            'puppies-adolescents' => 'Puppies & Adolescents',
            'family-dog' => 'Family Dog',
            'sport-fun' => 'Sport & Fun',
            'on-leash-reactivity' => 'On Leash Reactivity'
        );
        
        // Show topics in our defined order, but only if they have scheduled classes
        foreach ($topic_order as $slug => $label) {
            if (isset($active_topics[$slug])) {
                $output .= '<button class="filter-btn" data-filter="' . $slug . '" style="padding: 5px 15px; border: 1px solid #ddd; background: white; border-radius: 0px; cursor: pointer;">' . esc_html($active_topics[$slug]) . '</button>';
            }
        }
        
        $output .= '</div>';
        $output .= '</div>';
    }
    
    // Type filters - only show if there are types
    if (!empty($active_types)) {
        $output .= '<div class="filter-group" style="margin-bottom: 15px;">';
        $output .= '<label style="display: inline-block; min-width: 60px; font-weight: bold; margin-right: 10px;">Type:</label>';
        $output .= '<div class="filter-buttons" data-filter-type="type" style="display: inline-flex; gap: 10px; flex-wrap: wrap;">';
        $output .= '<button class="filter-btn active" data-filter="all" style="padding: 5px 15px; border: 1px solid #ddd; background: #007cba; color: white; border-radius: 0px; cursor: pointer;">All Types</button>';
        
        // Define the type order we want
        $type_order = array(
            'group-class' => 'Group Class',
            'workshop' => 'Workshop',
            'seminar' => 'Seminar'
        );
        
        // Show types in our defined order, but only if they have scheduled classes
        foreach ($type_order as $slug => $label) {
            if (isset($active_types[$slug])) {
                $output .= '<button class="filter-btn" data-filter="' . $slug . '" style="padding: 5px 15px; border: 1px solid #ddd; background: white; border-radius: 0px; cursor: pointer;">' . esc_html($active_types[$slug]) . '</button>';
            }
        }
        
        $output .= '</div>';
        $output .= '</div>';
    }
    
    $output .= '<div class="filter-status" style="margin-top: 10px; font-style: italic; color: #666;">';
    $output .= '<span id="filter-count">Showing all classes</span>';
    $output .= '</div>';
    
    $output .= '</div>';
    
    return $output;
}
}

if (!function_exists('dts_get_upcoming_class_instances')) {
function dts_get_upcoming_class_instances($days_ahead = 60) {
    $instances = array();
    
    // Get all published joinables
    $joinables = get_posts(array(
        'post_type' => 'joinables',
        'posts_per_page' => -1,
        'post_status' => 'publish'
    ));
    
    $today = new DateTime('now', wp_timezone());
    $end_date = clone $today;
    $end_date->modify('+' . $days_ahead . ' days');
    
    foreach ($joinables as $joinable) {
        $schedule_type = get_post_meta($joinable->ID, 'schedule_type', true);
        $capacity = intval(get_post_meta($joinable->ID, 'capacity', true));
        
        // Get taxonomies
        $topics = wp_get_post_terms($joinable->ID, 'training_topic', array('fields' => 'names'));
        $topic = !empty($topics) ? $topics[0] : 'Family Dog';
        
        $types = wp_get_post_terms($joinable->ID, 'training_type', array('fields' => 'names'));
        $class_type = !empty($types) ? $types[0] : 'Group Class';
        
        // Skip private lessons
        if ($class_type === 'Private Lesson') {
            continue;
        }
        
        if ($capacity <= 0) $capacity = 10;
        
        if ($schedule_type == 'rolling') {
            // Get rolling class instances
            $class_days = get_post_meta($joinable->ID, 'class_days', true);
            $class_time = get_post_meta($joinable->ID, 'class_time', true);
            
            if (!is_array($class_days)) {
                $class_days = maybe_unserialize($class_days);
                if (!is_array($class_days)) {
                    $class_days = array_map('trim', explode(',', $class_days));
                }
            }
            
            // Generate instances for each class day in the date range
            $check_date = clone $today;
            while ($check_date <= $end_date) {
                $day_name = strtolower($check_date->format('l'));
                
                if (in_array($day_name, $class_days)) {
                    $enrolled = dts_count_enrollments_for_date($joinable->ID, $check_date, 'rolling');
                    
                    $instances[] = array(
                        'joinable_id' => $joinable->ID,
                        'title' => get_the_title($joinable->ID),
                        'date' => clone $check_date,
                        'time' => $class_time,
                        'topic' => $topic,
                        'type' => $class_type,
                        'capacity' => $capacity,
                        'enrolled' => $enrolled,
                        'schedule_type' => 'rolling'
                    );
                }
                
                $check_date->modify('+1 day');
            }
        }
        elseif ($schedule_type == 'series') {
            // Get series start dates
            $series_dates = get_post_meta($joinable->ID, 'series_start_dates', true);
            
            if (empty($series_dates)) {
                $series_dates = get_post_meta($joinable->ID, 'series_start_date', true);
            }
            
            if (!empty($series_dates)) {
                if (!is_array($series_dates)) {
                    $series_dates = maybe_unserialize($series_dates);
                }
                
                if (is_array($series_dates)) {
                    foreach ($series_dates as $series) {
                        $start_date_string = '';
                        $start_time = '';
                        
                        if (is_array($series)) {
                            $start_date_string = isset($series['series_instance_start_date']) ? $series['series_instance_start_date'] : '';
                            $start_time = isset($series['series_instance_start_time']) ? $series['series_instance_start_time'] : '';
                        } else {
                            $start_date_string = $series;
                            $start_time = get_post_meta($joinable->ID, 'class_time', true);
                        }
                        
                        if (!empty($start_date_string)) {
                            $series_date = DateTime::createFromFormat('Y-m-d', $start_date_string);
                            
                            if ($series_date && $series_date >= $today && $series_date <= $end_date) {
                                $enrolled = dts_count_enrollments_for_date($joinable->ID, $series_date, 'series');
                                
                                $instances[] = array(
                                    'joinable_id' => $joinable->ID,
                                    'title' => get_the_title($joinable->ID),
                                    'date' => $series_date,
                                    'time' => $start_time,
                                    'topic' => $topic,
                                    'type' => $class_type,
                                    'capacity' => $capacity,
                                    'enrolled' => $enrolled,
                                    'schedule_type' => 'series',
                                    'series_start' => $start_date_string
                                );
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Sort by date and time
    usort($instances, function($a, $b) {
        $date_compare = $a['date']->format('Y-m-d') <=> $b['date']->format('Y-m-d');
        if ($date_compare === 0) {
            return $a['time'] <=> $b['time'];
        }
        return $date_compare;
    });
    
    return $instances;
}
}

if (!function_exists('dts_count_enrollments_for_date')) {
function dts_count_enrollments_for_date($joinable_id, $date, $schedule_type) {
    $args = array(
        'post_type' => 'registrations',
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => 'joinable_id',
                'value' => $joinable_id,
                'compare' => '='
            ),
            array(
                'relation' => 'OR',
                array(
                    'key' => 'status',
                    'value' => 'active',
                    'compare' => '='
                ),
                array(
                    'key' => 'status',
                    'compare' => 'NOT EXISTS'
                )
            )
        )
    );
    
    $registrations = get_posts($args);
    return count($registrations);
}
}

if (!function_exists('dts_get_registration_url')) {
function dts_get_registration_url($joinable_id, $start_date, $time) {
    $base_url = home_url('/register/');
    
    $params = array(
        'joinable_id' => $joinable_id,
        'start_date' => $start_date,
        'class_time' => $time
    );
    
    return add_query_arg($params, $base_url);
}
}