<?php
/**
 * View Template: Teacher Curriculum Preview (Fixed Elements & Global CTAs)
 * File Location: template-views/teacher-curriculum-preview.php
 */

global $wpdb;
$course_id  = isset($_GET['lesson_id']) ? intval($_GET['lesson_id']) : 0;
$teacher_id = isset($_GET['teacher_id']) ? intval($_GET['teacher_id']) : 0;

// Fetch Teacher Profile Information
$teacher_name = get_the_author_meta('display_name', $teacher_id) ?: 'Mrs. Oluchi Nwosu';
$teacher_bio  = get_the_author_meta('description', $teacher_id) ?: 'Certified Mathematics Instructor & Cognitive Analytics Specialist. Dedicated to foundational concept mastery and structured tracking parameters.';
$teacher_avatar = get_avatar_url($teacher_id, ['size' => 200]) ?: 'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?auto=format&fit=crop&q=80&w=200';

// Dynamic Meta Metrics
$milestone    = get_post_meta($course_id, 'lms_course_milestone_badge', true) ?: '8 Assessments';
$total_units  = get_post_meta($course_id, 'lms_course_total_units', true) ?: '12 Units';
$total_lessons = get_post_meta($course_id, 'lms_course_total_lessons', true) ?: '48 Lessons';
$duration_txt  = get_post_meta($course_id, 'lms_course_duration_text', true) ?: '36 Hours';

// Fetch all structural Modules (Tutor LMS Topics) linked to this course
$modules = get_posts([
    'post_type'      => 'topics',
    'post_status'    => 'publish',
    'post_parent'    => $course_id,
    'posts_per_page' => -1,
    'orderby'        => 'menu_order',
    'order'          => 'ASC'
]);
?>

<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 class="flex items-center gap-3">
            <button onclick="openOverlay('teacher-selection')" class="material-symbols-outlined text-primary p-2 hover:bg-surface-container rounded-full transition-all">
                arrow_back
            </button>
            <div>
                <div class="flex flex-wrap items-center gap-2">
                    <h3 class="text-headline-md font-headline-md text-on-surface">Curriculum Track Blueprint</h3>
                    <span class="flex items-center gap-1 px-2.5 py-1 bg-secondary-container text-on-secondary-container text-xs font-bold rounded-full border border-secondary shadow-sm">
                        <span class="material-symbols-outlined text-xs" style="font-variation-settings: 'FILL' 1;">verified</span>
                        uLesson Accredited
                    </span>
                </div>
                <p class="text-body-md text-on-surface-variant">Review customized structure designed by <strong><?php echo esc_html($teacher_name); ?></strong></p>
            </div>
        </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="bg-white border border-outline-variant rounded-2xl p-6 shadow-sm mb-8">
        <div class="flex flex-col md:flex-row items-center md:items-start justify-between gap-6 pb-6 border-b border-outline-variant">
            
            <div class="flex flex-col sm:flex-row items-center sm:items-start gap-4 text-center sm:text-left">
                <div class="w-20 h-20 rounded-full overflow-hidden border-2 border-primary flex-shrink-0">
                    <img class="w-full h-full object-cover" src="<?php echo esc_url($teacher_avatar); ?>" alt="<?php echo esc_attr($teacher_name); ?>"/>
                </div>
                <div class="min-w-0">
                    <h4 class="text-headline-sm font-bold text-on-surface"><?php echo esc_html($teacher_name); ?></h4>
                    <p class="text-body-md text-on-surface-variant mt-1 max-w-xl leading-relaxed">
                        <?php echo esc_html($teacher_bio); ?>
                    </p>
                </div>
            </div>

            <div class="flex flex-col sm:flex-row md:flex-col gap-2.5 w-full sm:w-auto flex-shrink-0">
                <span class="flex items-center justify-center gap-1 text-xs font-bold text-on-surface bg-surface-container px-3 py-2 rounded-xl border border-outline-variant">
                    <span class="material-symbols-outlined text-sm text-warm-orange" style="font-variation-settings: 'FILL' 1;">star</span> 4.9 Rating (120+ Reviews)
                </span>
                <button onclick="toggleTeacherChat()" class="flex items-center justify-center gap-1.5 text-xs font-bold bg-primary text-on-primary hover:opacity-90 transition-all px-4 py-2.5 rounded-xl shadow-sm w-full">
                    <span class="material-symbols-outlined text-sm">chat</span>
                    Chat Live Now
                </button>
                <button onclick="openOverlay('teacher-schedule-selection&lesson_id=<?php echo $course_id; ?>&teacher_id=<?php echo $teacher_id; ?>')" class="flex items-center justify-center gap-1.5 text-xs font-bold border-2 border-primary text-primary bg-transparent hover:bg-primary/5 transition-all px-4 py-2.5 rounded-xl w-full">
                    <span class="material-symbols-outlined text-sm">calendar_month</span>
                    Start Course
                </button>
            </div>
        </div>

        <div class="pt-5 grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-2 divide-y-0 md:divide-x divide-outline-variant/60">
            <div class="flex items-center gap-3 md:justify-center">
                <span class="material-symbols-outlined p-2 bg-primary/10 text-primary rounded-xl">analytics</span>
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wider text-on-surface-variant leading-none">Modules</p>
                    <p class="text-lg font-black text-on-surface mt-1"><?php echo esc_html($total_units); ?></p>
                </div>
            </div>
            <div class="flex items-center gap-3 md:justify-center md:pl-4">
                <span class="material-symbols-outlined p-2 bg-secondary/10 text-secondary rounded-xl">list_alt</span>
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wider text-on-surface-variant leading-none">Total Topics</p>
                    <p class="text-lg font-black text-on-surface mt-1"><?php echo esc_html($total_lessons); ?></p>
                </div>
            </div>
            <div class="flex items-center gap-3 md:justify-center md:pl-4">
                <span class="material-symbols-outlined p-2 bg-warm-orange/10 text-warm-orange rounded-xl">schedule</span>
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wider text-on-surface-variant leading-none">Duration</p>
                    <p class="text-lg font-black text-on-surface mt-1"><?php echo esc_html($duration_txt); ?></p>
                </div>
            </div>
            <div class="flex items-center gap-3 md:justify-center md:pl-4">
                <span class="material-symbols-outlined p-2 bg-green-600/10 text-green-600 rounded-xl">assignment</span>
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wider text-on-surface-variant leading-none">Milestones</p>
                    <p class="text-lg font-black text-on-surface mt-1"><?php echo esc_html($milestone); ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 pb-12">
        
        <div class="lg:col-span-2 space-y-4">
            <h4 class="text-label-lg font-bold text-primary uppercase tracking-wider flex items-center gap-2 mb-1">
                <span class="material-symbols-outlined text-sm">segment</span>
                Detailed Course Roadmap Breakdown
            </h4>

            <?php if (!empty($modules)) : ?>
                <?php foreach ($modules as $index => $mod) : 
                    // Query sub-lessons assigned matching this parent loop frame layout
                    $lessons = get_posts([
                        'post_type'   => 'lessons',
                        'post_status' => 'publish',
                        'post_parent' => $course_id,
                        'meta_query'  => [
                            [
                                'key'     => '_tutor_lesson_topic_id',
                                'value'   => $mod->ID,
                                'compare' => '='
                            ]
                        ],
                        'posts_per_page' => -1,
                        'orderby'        => 'menu_order',
                        'order'          => 'ASC'
                    ]);

                    $track_allocation = get_post_meta($mod->ID, '_topic_track_allocation', true) ?: '6 Hours';
                    $topic_description = get_post_meta($mod->ID, '_topic_custom_description', true) ?: $mod->post_excerpt;
                    if (empty($topic_description)) {
                        $topic_description = 'Students will review systematic learning nodes, structural tracking logic milestones, and core topic parameter definitions.';
                    }
                ?>
                    <div class="border border-outline-variant bg-white rounded-xl overflow-hidden shadow-sm">
                        <div onclick="toggleModuleAccordion(<?php echo $mod->ID; ?>)" class="bg-surface-container-low p-4 flex items-center justify-between cursor-pointer hover:bg-surface-container transition-all select-none">
                            <div class="flex items-center gap-3">
                                <span class="w-8 h-8 rounded-lg <?php echo ($index % 2 === 0) ? 'bg-primary text-on-primary' : 'bg-secondary text-on-secondary'; ?> font-bold flex items-center justify-center text-sm">
                                    <?php echo sprintf('%02d', $index + 1); ?>
                                </span>
                                <div>
                                    <h5 class="font-bold text-on-surface text-base leading-tight"><?php echo esc_html($mod->post_title); ?></h5>
                                    <p class="text-xs text-on-surface-variant mt-0.5">Track Allocation: <?php echo esc_html($track_allocation); ?> กค <?php echo count($lessons); ?> Topics Included</p>
                                </div>
                            </div>
                            <span id="icon-module-<?php echo $mod->ID; ?>" class="material-symbols-outlined text-on-surface-variant transition-transform duration-200">expand_less</span>
                        </div>

                        <div id="content-module-<?php echo $mod->ID; ?>" class="p-5 border-t border-outline-variant space-y-4">
                            <p class="text-body-md text-on-surface-variant"><?php echo esc_html($topic_description); ?></p>
                            
                            <div class="bg-background p-4 rounded-xl space-y-2">
                                <div class="flex items-center justify-between text-xs font-bold text-primary border-b border-outline-variant pb-1.5 mb-2">
                                    <span>ACCUMULATED TOPICS</span>
                                    <span>TRACK ESTIMATE</span>
                                </div>

                                <?php if (!empty($lessons)) : ?>
                                    <?php foreach ($lessons as $les) : 
                                        $duration = get_post_meta($les->ID, '_video_duration_min', true) ?: '1.5 Hours';
                                    ?>
                                        <div class="flex items-center justify-between text-sm text-on-surface py-0.5">
                                            <span class="flex items-center gap-2">
                                                <span class="w-1.5 h-1.5 rounded-full bg-primary flex-shrink-0"></span>
                                                <?php echo esc_html($les->post_title); ?>
                                            </span>
                                            <span class="text-xs text-on-surface-variant bg-surface-container px-2 py-0.5 rounded font-bold flex-shrink-0"><?php echo esc_html($duration); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else : ?>
                                    <p class="text-xs text-on-surface-variant italic">No items published in this module tracking layer yet.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else : ?>
                <div class="p-6 text-center bg-white border border-outline-variant rounded-2xl shadow-sm">
                    <p class="text-on-surface-variant text-sm">No structured dynamic module components found.</p>
                </div>
            <?php endif; ?>
        </div>

        <div class="space-y-6">
            <h4 class="text-label-lg font-bold text-secondary uppercase tracking-wider flex items-center gap-2">
                <span class="material-symbols-outlined text-sm">menu_book</span>
                Curriculum Resources
            </h4>
            
            <div class="bg-white border border-outline-variant rounded-xl p-5 shadow-sm space-y-4">
                <div class="flex items-start gap-3">
                    <span class="material-symbols-outlined text-primary bg-primary-container/30 p-2 rounded-lg">library_books</span>
                    <div>
                        <h5 class="font-bold text-on-surface text-sm">Luminous Core Mathematics Book 4</h5>
                        <p class="text-xs text-on-surface-variant">Official Reference Guide</p>
                    </div>
                </div>
                <div class="flex items-start gap-3">
                    <span class="material-symbols-outlined text-secondary bg-secondary-container/20 p-2 rounded-lg">analytics</span>
                    <div>
                        <h5 class="font-bold text-on-surface text-sm">Interactive Visual Math Dashboard</h5>
                        <p class="text-xs text-on-surface-variant">uLesson structural match tracks</p>
                    </div>
                </div>
            </div>

            <div class="bg-primary text-on-primary rounded-2xl p-5 shadow-md border border-primary-container">
                <h5 class="font-bold text-lg mb-2">Book Lesson Schedule</h5>
                <p class="text-xs opacity-90 mb-4 leading-relaxed">Lock in your slots with <?php echo esc_html($teacher_name); ?>. Proceeding allows you to pick specific weekly hours, select startup calendars, and confirm live routines.</p>
                <button onclick="openOverlay('teacher-schedule-selection&lesson_id=<?php echo $course_id; ?>&teacher_id=<?php echo $teacher_id; ?>')" class="w-full py-3 bg-white text-primary rounded-xl font-bold hover:bg-soft-lilac transition-all flex items-center justify-center gap-2 shadow-md">
                    <span class="material-symbols-outlined text-sm">calendar_month</span>
                    Start Course
                </button>
            </div>
        </div>

    </div>

    <div id="teacher-live-chat-box" class="hidden fixed bottom-6 right-6 w-80 md:w-96 bg-white rounded-2xl shadow-2xl border border-outline-variant z-50 overflow-hidden flex-col h-[400px] transition-all transform">
        <div class="bg-primary p-4 text-on-primary flex items-center justify-between shadow-sm flex-shrink-0">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-full border border-white/20 overflow-hidden relative">
                    <img class="w-full h-full object-cover" src="<?php echo esc_url($teacher_avatar); ?>" alt="<?php echo esc_attr($teacher_name); ?>"/>
                    <div class="absolute bottom-0 right-0 w-2.5 h-2.5 bg-green-500 rounded-full border-2 border-primary"></div>
                </div>
                <div>
                    <h5 class="font-bold text-sm leading-tight"><?php echo esc_html($teacher_name); ?></h5>
                    <p class="text-[10px] text-white/80 flex items-center gap-1">Online กค Active Now</p>
                </div>
            </div>
            <button onclick="toggleTeacherChat()" class="material-symbols-outlined text-on-primary p-1 hover:bg-white/10 rounded-full">close</button>
        </div>
        <div class="flex-1 p-4 bg-surface-container-lowest overflow-y-auto space-y-3 text-sm custom-scrollbar">
            <div class="bg-surface-container-low text-on-surface p-3 rounded-2xl rounded-tl-none max-w-[85%] border border-outline-variant">
                <p class="text-[11px] font-bold text-primary mb-1"><?php echo esc_html($teacher_name); ?></p>
                Hello! I'm ready to help guide your child through this tracking path. Let me know if you have any questions regarding structural topics or lesson milestones!
                <span class="block text-[9px] text-on-surface-variant text-right mt-1">10:24 AM</span>
            </div>
        </div>
        <div class="p-3 bg-white border-t border-outline-variant flex items-center gap-2 flex-shrink-0">
            <input type="text" class="flex-1 bg-surface-container rounded-xl px-4 py-2 text-sm border-none focus:ring-1 focus:ring-primary placeholder:text-on-surface-variant" placeholder="Type message here..."/>
            <button class="material-symbols-outlined bg-primary text-on-primary p-2 rounded-xl hover:opacity-90 transition-all">send</button>
        </div>
    </div>

    <button id="floating-chat-fab" onclick="toggleTeacherChat()" class="fixed bottom-6 right-6 w-14 h-14 bg-secondary text-on-primary rounded-full shadow-xl flex items-center justify-center hover:scale-110 transition-all active:scale-95 z-40 focus:outline-none" title="Chat with Teacher">
        <span class="material-symbols-outlined text-2xl" style="font-variation-settings: 'FILL' 1;">chat</span>
    </button>

</div>

<script>
    /**
     * Accordion Toggler Engine (Updated to use ID context matching the template parameters)
     */
    function toggleModuleAccordion(id) {
        const content = document.getElementById('content-module-' + id);
        const icon = document.getElementById('icon-module-' + id);
        
        if (content.classList.contains('hidden')) {
            content.classList.remove('hidden');
            icon.style.transform = 'rotate(0deg)';
            icon.textContent = 'expand_less';
        } else {
            content.classList.add('hidden');
            icon.style.transform = 'rotate(180deg)';
            icon.textContent = 'expand_more';
        }
    }

    /**
     * Managed Chat Layer visibility engine with full clean action transitions
     */
    function toggleTeacherChat() {
        const chatBox = document.getElementById('teacher-live-chat-box');
        const chatFab = document.getElementById('floating-chat-fab');
        
        if (chatBox.classList.contains('hidden')) {
            chatBox.classList.remove('hidden');
            chatBox.classList.add('flex');
            // Complete fading elimination of action selector button
            chatFab.classList.add('hidden');
        } else {
            chatBox.classList.add('hidden');
            chatBox.classList.remove('flex');
            // Clean restoration of primary floating component
            chatFab.classList.remove('hidden');
        }
    }
</script>