<?php
/**
 * View Template: Wide Teacher Selection Modal with Collapsible Filter Panel
 * File Location: template-views/teacher-selection.php
 */

global $wpdb;

// 1. Establish the current active class/curriculum context from tracking tags (Fallback to Primary 4)
$class_context = isset($_GET['class_context']) ? sanitize_text_field($_GET['class_context']) : 'Primary 4';
$curriculum_id = isset($_GET['curriculum_id']) ? intval($_GET['curriculum_id']) : 4;

// 2. Fetch searching & filtering vectors down into database contexts securely
$search_query = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';
$min_rating   = isset($_GET['min_rating']) ? floatval($_GET['min_rating']) : 0.0;

// 3. Assemble dynamic query structures linking courses to their author accounts
$where_clauses = array(
    "c.post_type = 'courses'",
    "c.post_status = 'publish'"
);

if ( ! empty( $search_query ) ) {
    $where_clauses[] = $wpdb->prepare(
        "(u.display_name LIKE %s OR c.post_title LIKE %s)",
        '%' . $wpdb->esc_like($search_query) . '%',
        '%' . $wpdb->esc_like($search_query) . '%'
    );
}

$where_sql = implode( " AND ", $where_clauses );

$query = "
    SELECT 
        c.ID as course_id,
        c.post_title as course_title,
        c.post_author as teacher_id,
        u.display_name as teacher_name
    FROM {$wpdb->posts} c
    JOIN {$wpdb->users} u ON c.post_author = u.ID
    WHERE {$where_sql}
    ORDER BY c.ID DESC
";

$available_lessons = $wpdb->get_results($query);
?>

<div class="p-6 md:p-8 relative max-h-[90vh] overflow-y-auto custom-scrollbar bg-background">
    
    <div class="flex justify-between items-start mb-6 sticky top-0 bg-background z-20 pb-4 border-b border-outline-variant">
        <div>
            <h3 class="text-headline-md font-headline-md text-on-surface flex items-center gap-2">
                <span class="material-symbols-outlined text-primary">groups</span>
                Select a Teacher for <?php echo esc_html($class_context); ?> Curriculum
            </h3>
            <p class="text-body-md text-on-surface-variant">Review available certified instructors, active schedules, and custom tutoring blueprints.</p>
        </div>
        <button onclick="closeOverlay()" class="material-symbols-outlined text-on-surface-variant p-2 hover:bg-surface-container rounded-full transition-all focus:outline-none">
            close
        </button>
    </div>

    <div class="mb-6 flex gap-4">
        <div class="flex-1 flex items-center bg-white rounded-xl px-4 py-3 gap-3 border border-outline-variant shadow-sm focus-within:border-primary transition-all">
            <span class="material-symbols-outlined text-on-surface-variant">search</span>
            <input id="teacher-search-input" value="<?php echo esc_attr($search_query); ?>" onkeyup="handleTeacherSearch(event)" class="bg-transparent border-none focus:ring-0 text-body-md w-full placeholder:text-on-surface-variant p-0" placeholder="Search teachers by name, qualification, or special skillsets..." type="text"/>
        </div>
        <button onclick="toggleFilterDrawer()" class="flex items-center gap-2 bg-primary text-on-primary font-bold px-5 py-3 rounded-xl hover:opacity-90 shadow-sm transition-all">
            <span class="material-symbols-outlined">tune</span>
            <span>Filter</span>
        </button>
    </div>

    <div id="filter-drawer-panel" class="hidden dynamic-drawer-animation mb-6 p-6 bg-surface-container-low rounded-2xl border border-outline-variant">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            
            <div>
                <label class="block text-label-lg font-bold text-primary mb-3">Available Days</label>
                <div class="space-y-2">
                    <label class="flex items-center gap-3 text-body-md text-on-surface-variant cursor-pointer">
                        <input type="checkbox" name="filter-days" value="weekdays" class="rounded border-outline text-primary focus:ring-primary w-5 h-5" checked/>
                        <span>Weekdays (Mon - Fri)</span>
                    </label>
                    <label class="flex items-center gap-3 text-body-md text-on-surface-variant cursor-pointer">
                        <input type="checkbox" name="filter-days" value="weekends" class="rounded border-outline text-primary focus:ring-primary w-5 h-5"/>
                        <span>Weekends (Sat - Sun)</span>
                    </label>
                </div>
            </div>

            <div>
                <label class="block text-label-lg font-bold text-primary mb-3">Time Preference</label>
                <div class="space-y-2">
                    <label class="flex items-center gap-3 text-body-md text-on-surface-variant cursor-pointer">
                        <input type="checkbox" name="filter-time" value="morning" class="rounded border-outline text-primary focus:ring-primary w-5 h-5"/>
                        <span>Morning (8:00 AM - 12:00 PM)</span>
                    </label>
                    <label class="flex items-center gap-3 text-body-md text-on-surface-variant cursor-pointer">
                        <input type="checkbox" name="filter-time" value="afternoon" class="rounded border-outline text-primary focus:ring-primary w-5 h-5" checked/>
                        <span>Afternoon (12:00 PM - 4:00 PM)</span>
                    </label>
                    <label class="flex items-center gap-3 text-body-md text-on-surface-variant cursor-pointer">
                        <input type="checkbox" name="filter-time" value="evening" class="rounded border-outline text-primary focus:ring-primary w-5 h-5"/>
                        <span>Evening (4:00 PM - 7:00 PM)</span>
                    </label>
                </div>
            </div>

            <div>
                <label class="block text-label-lg font-bold text-primary mb-3">Minimum Rating</label>
                <div class="space-y-3">
                    <div class="flex items-center gap-2">
                        <input type="radio" name="rating-filter" value="4.5" class="text-primary focus:ring-primary w-5 h-5" <?php checked($min_rating, 4.5); ?> onclick="applyRatingFilter(4.5)"/>
                        <span class="text-body-md text-on-surface-variant flex items-center gap-1">
                            4.5+ Stars <span class="material-symbols-outlined text-sm text-warm-orange" style="font-variation-settings: 'FILL' 1;">star</span>
                        </span>
                    </div>
                    <div class="flex items-center gap-2">
                        <input type="radio" name="rating-filter" value="4.0" class="text-primary focus:ring-primary w-5 h-5" <?php checked($min_rating, 4.0); ?> onclick="applyRatingFilter(4.0)"/>
                        <span class="text-body-md text-on-surface-variant flex items-center gap-1">
                            4.0+ Stars <span class="material-symbols-outlined text-sm text-warm-orange" style="font-variation-settings: 'FILL' 1;">star</span>
                        </span>
                    </div>
                </div>
            </div>

        </div>
        
        <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-outline-variant">
            <button onclick="clearAllFilters()" class="px-4 py-2 text-label-lg font-bold text-on-surface-variant hover:text-primary transition-colors">Clear Filters</button>
            <button onclick="toggleFilterDrawer()" class="px-5 py-2 bg-secondary text-on-primary text-label-lg font-bold rounded-xl shadow-sm hover:opacity-90">Apply Filters</button>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        
        <?php if (!empty($available_lessons)) : ?>
            <?php foreach ($available_lessons as $lesson) : 
                // Pull dynamic metadata fields managed via instructor custom profile records
                $title       = get_user_meta($lesson->teacher_id, 'lms_teacher_title', true) ?: 'Senior Tutor';
                $experience  = get_user_meta($lesson->teacher_id, 'lms_teacher_experience', true) ?: '5 yrs exp';
                $bio_summary = get_user_meta($lesson->teacher_id, '_tutor_profile_bio', true) ?: 'Dedicated specialist focusing on active development tracks.';
                
                // Aggregate operational tracking timelines for active working schedules
                $sch_table   = $wpdb->prefix . 'lms_teacher_schedules';
                $days        = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT day_of_week FROM $sch_table WHERE teacher_id = %d LIMIT 3", $lesson->teacher_id));
                $days_badge  = !empty($days) ? implode(', ', array_map(function($d){ return substr($d, 0, 3); }, $days)) : 'Mon, Wed, Fri';

                // Aggregate rating metrics derived dynamically across matching review tables
                $rev_table   = $wpdb->prefix . 'lms_teacher_reviews';
                $rating_data = $wpdb->get_row($wpdb->prepare("SELECT AVG(rating_score) as avg_score, COUNT(id) as total_count FROM $rev_table WHERE teacher_id = %d", $lesson->teacher_id));
                
                $avg_score   = $rating_data->avg_score ? number_format($rating_data->avg_score, 1) : '4.8';
                $total_revs  = $rating_data->total_count ? $rating_data->total_count . '+ reviews' : '90+ reviews';
                
                // Filter out item elements client side if minimum metrics are specified
                if ($min_rating > 0 && floatval($avg_score) < $min_rating) {
                    continue; 
                }
            ?>
                <div class="border border-outline-variant bg-white rounded-xl p-5 hover:border-primary hover:shadow-md transition-all flex flex-col justify-between">
                    <div class="flex items-start gap-4">
                        <div class="w-16 h-16 rounded-full bg-primary-fixed overflow-hidden flex-shrink-0 border-2 border-outline-variant">
                            <img class="w-full h-full object-cover" src="https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?auto=format&fit=crop&q=80&w=200" alt="<?php echo esc_attr($lesson->teacher_name); ?>"/>
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center justify-between gap-2">
                                <h4 class="font-bold text-on-surface text-base"><?php echo esc_html($lesson->teacher_name); ?></h4>
                                <span class="px-2 py-0.5 bg-secondary-container text-on-secondary-container text-[10px] font-bold rounded-full flex-shrink-0">
                                    <?php echo esc_html($title); ?>
                                </span>
                            </div>
                            <p class="text-label-sm text-on-surface-variant flex items-center gap-1 mt-0.5">
                                <span class="material-symbols-outlined text-sm text-warm-orange" style="font-variation-settings: 'FILL' 1;">star</span>
                                <span class="font-bold text-on-surface"><?php echo esc_html($avg_score); ?></span> (<?php echo esc_html($total_revs); ?>) · <?php echo esc_html($experience); ?>
                            </p>
                            <p class="text-xs text-on-surface-variant mt-2 line-clamp-2"><?php echo esc_html($bio_summary); ?></p>
                        </div>
                    </div>
                    <div class="flex items-center justify-between mt-4 pt-3 border-t border-soft-lilac">
                        <span class="text-xs text-secondary font-bold bg-secondary-container/20 px-2 py-1 rounded">
                            <?php echo esc_html($days_badge); ?>
                        </span>
                        <button onclick="openOverlay('teacher-curriculum-preview&lesson_id=<?php echo $lesson->course_id; ?>&teacher_id=<?php echo $lesson->teacher_id; ?>')" class="py-2 px-4 bg-primary text-on-primary text-xs font-bold rounded-lg hover:opacity-90 transition-all flex items-center gap-1">
                            View Lesson <span class="material-symbols-outlined text-xs">arrow_forward</span>
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else : ?>
            <div class="col-span-full p-12 text-center bg-white border border-outline-variant rounded-2xl">
                <span class="material-symbols-outlined text-4xl text-on-surface-variant/40 mb-2">search_off</span>
                <p class="text-on-surface-variant text-sm font-medium">No matching teachers or course track blueprints found.</p>
            </div>
        <?php endif; ?>

    </div>
</div>

<script>
    // Toggle the display of the collapsible filter drawer
    function toggleFilterDrawer() {
        const panel = document.getElementById('filter-drawer-panel');
        if (panel.classList.contains('hidden')) {
            panel.classList.remove('hidden');
        } else {
            panel.classList.add('hidden');
        }
    }

    // Intercept input actions and load search configurations inside overlay layout loops
    function handleTeacherSearch(event) {
        if (event.key === 'Enter') {
            const query = encodeURIComponent(document.getElementById('teacher-search-input').value);
            openOverlay('teacher-selection&search=' + query + '&class_context=<?php echo urlencode($class_context); ?>&curriculum_id=<?php echo $curriculum_id; ?>');
        }
    }

    // Apply minimum rating metrics dynamically
    function applyRatingFilter(rating) {
        const query = encodeURIComponent(document.getElementById('teacher-search-input').value);
        openOverlay('teacher-selection&search=' + query + '&min_rating=' + rating + '&class_context=<?php echo urlencode($class_context); ?>&curriculum_id=<?php echo $curriculum_id; ?>');
    }

    // Clear parameters and trigger clean UI reconstruction loop
    function clearAllFilters() {
        openOverlay('teacher-selection&class_context=<?php echo urlencode($class_context); ?>&curriculum_id=<?php echo $curriculum_id; ?>');
    }
</script>