@extends('front_end.layouts.home')

@php
$showLeftSidebar = false;
$showRightSidebar = false;
@endphp
@section('title', $course->title . ' - Learning')

@section('content')
<div class="bg-white shadow-sm border-0 rounded-0 h-100">
    <div class="row g-0 h-100">
        <!-- Sidebar - Course Structure -->
        <div class="col-md-3 border-end h-100" style="overflow-y: auto;">
            <div class="p-3 bg-dark text-white">
                <div class="d-flex align-items-center">
                    <a href="{{ route('courses.show', $course->slug) }}" class="text-white me-3">
                        <i class="fas fa-arrow-left"></i>
                    </a>
                    <div class="text-truncate">
                        <h6 class="mb-0 text-truncate">{{ $course->title }}</h6>
                        <div class="d-flex align-items-center">
                            <div class="progress flex-grow-1 me-2" style="height: 5px;">
                                <div class="progress-bar" role="progressbar" style="width: {{ $enrollment->getProgressPercentage() }}%;" aria-valuenow="{{ $enrollment->getProgressPercentage() }}" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                            <span class="small">{{ $enrollment->getProgressPercentage() }}%</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="accordion course-sections" id="accordionCourse">
                @foreach($course->sections as $section)
                <div class="accordion-item border-0 border-bottom">
                    <h2 class="accordion-header" id="heading{{ $section->id }}">
                        <button class="accordion-button collapsed py-2 px-3" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{ $section->id }}" aria-expanded="{{ $currentLesson && $currentLesson->section_id == $section->id ? 'true' : 'false' }}" aria-controls="collapse{{ $section->id }}">
                            <div class="w-100">
                                <div class="d-flex align-items-center">
                                    <div class="flex-grow-1">
                                        <div class="fw-bold small text-truncate">{{ $section->title }}</div>
                                        <div class="text-muted smaller">
                                            {{ $section->lessons->count() }} lessons • 
                                            {{ $section->lessons->sum('duration') }} min
                                        </div>
                                    </div>
                                    @php
                                        $completedLessons = 0;
                                        foreach($section->lessons as $lesson) {
                                            if(isset($lessonProgress[$lesson->id]) && $lessonProgress[$lesson->id]->is_completed) {
                                                $completedLessons++;
                                            }
                                        }
                                        $sectionProgress = $section->lessons->count() > 0 
                                            ? round(($completedLessons / $section->lessons->count()) * 100) 
                                            : 0;
                                    @endphp
                                    <div class="ms-2 small">
                                        {{ $completedLessons }}/{{ $section->lessons->count() }}
                                    </div>
                                </div>
                                <div class="progress mt-1" style="height: 4px;">
                                    <div class="progress-bar" role="progressbar" style="width: {{ $sectionProgress }}%;" aria-valuenow="{{ $sectionProgress }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </button>
                    </h2>
                    <div id="collapse{{ $section->id }}" class="accordion-collapse collapse {{ $currentLesson && $currentLesson->section_id == $section->id ? 'show' : '' }}" aria-labelledby="heading{{ $section->id }}" data-bs-parent="#accordionCourse">
                        <div class="accordion-body p-0">
                            <ul class="list-group list-group-flush">
                                @foreach($section->lessons as $lesson)
                                <li class="list-group-item border-0 py-2 px-3 {{ $currentLesson && $currentLesson->id == $lesson->id ? 'bg-light' : '' }}">
                                    <a href="{{ route('courses.learn', ['slug' => $course->slug, 'lessonId' => $lesson->id]) }}" 
                                       class="d-flex align-items-start text-decoration-none text-dark">
                                        <div class="me-2 mt-1">
                                            @if(isset($lessonProgress[$lesson->id]) && $lessonProgress[$lesson->id]->is_completed)
                                                <i class="fas fa-check-circle text-success"></i>
                                            @else
                                                <i class="far fa-circle text-muted"></i>
                                            @endif
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div class="text-truncate {{ $currentLesson && $currentLesson->id == $lesson->id ? 'fw-bold' : '' }}">
                                                    {{ $lesson->title }}
                                                </div>
                                                <div class="ms-2 text-muted small">{{ $lesson->duration }} min</div>
                                            </div>
                                            @if($lesson->is_free)
                                                <span class="badge bg-success">Free</span>
                                            @endif
                                        </div>
                                    </a>
                                </li>
                                @endforeach
                            </ul>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="col-md-9 d-flex flex-column h-100">
            <!-- Content Tabs -->
            <ul class="nav nav-tabs">
                <li class="nav-item">
                    <a class="nav-link active" id="content-tab" data-bs-toggle="tab" href="#content" role="tab" aria-controls="content" aria-selected="true">Content</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="overview-tab" data-bs-toggle="tab" href="#overview" role="tab" aria-controls="overview" aria-selected="false">Overview</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="questions-tab" data-bs-toggle="tab" href="#questions" role="tab" aria-controls="questions" aria-selected="false">Q&A</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="announcements-tab" data-bs-toggle="tab" href="#announcements" role="tab" aria-controls="announcements" aria-selected="false">Announcements <span class="badge bg-primary rounded-pill">{{ $course->announcements->count() }}</span></a>
                </li>
            </ul>

            <div class="tab-content flex-grow-1" style="overflow-y: auto;">
                <!-- Content Tab -->
                <div class="tab-pane fade show active" id="content" role="tabpanel" aria-labelledby="content-tab">
                    <div class="p-4">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4>{{ $currentLesson->title }}</h4>
                            <div>
                                @if(isset($lessonProgress[$currentLesson->id]) && $lessonProgress[$currentLesson->id]->is_completed)
                                    <button class="btn btn-success btn-sm" disabled>
                                        <i class="fas fa-check-circle me-1"></i> Completed
                                    </button>
                                @else
                                    <button class="btn btn-primary btn-sm" id="markAsComplete" data-course="{{ $course->slug }}" data-lesson="{{ $currentLesson->id }}">
                                        <i class="fas fa-check-circle me-1"></i> Mark as Complete
                                    </button>
                                @endif
                            </div>
                        </div>

                        @if($currentLesson->video_url)
                        <div class="ratio ratio-16x9 mb-4">
                            <iframe src="{{ $currentLesson->video_url }}" title="{{ $currentLesson->title }}" allowfullscreen></iframe>
                        </div>
                        @endif

                        <div class="lesson-content mb-4">
                            {!! nl2br(e($currentLesson->content)) !!}
                        </div>

                        @if($currentLesson->attachment)
                        <div class="card mb-4">
                            <div class="card-body">
                                <h5 class="card-title">Downloadable Resources</h5>
                                <a href="{{ asset('storage/' . $currentLesson->attachment) }}" class="btn btn-outline-primary" download>
                                    <i class="fas fa-download me-2"></i>Download Attachment
                                </a>
                            </div>
                        </div>
                        @endif

                        <!-- Navigation between lessons -->
                        <div class="d-flex justify-content-between mt-5 pt-4 border-top">
                            @php
                                $prevLesson = null;
                                $nextLesson = null;
                                $foundCurrent = false;
                                $lessonIndex = 0;
                                
                                foreach($course->sections as $section) {
                                    foreach($section->lessons as $lesson) {
                                        if($foundCurrent) {
                                            $nextLesson = $lesson;
                                            break 2;
                                        }
                                        
                                        if($lesson->id == $currentLesson->id) {
                                            $foundCurrent = true;
                                        } else {
                                            $prevLesson = $lesson;
                                        }
                                        
                                        $lessonIndex++;
                                    }
                                    if($foundCurrent && $nextLesson) {
                                        break;
                                    }
                                }
                            @endphp

                            @if($prevLesson)
                            <a href="{{ route('courses.learn', ['slug' => $course->slug, 'lessonId' => $prevLesson->id]) }}" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Previous Lesson
                            </a>
                            @else
                            <div></div>
                            @endif

                            @if($nextLesson)
                            <a href="{{ route('courses.learn', ['slug' => $course->slug, 'lessonId' => $nextLesson->id]) }}" class="btn btn-primary">
                                Next Lesson<i class="fas fa-arrow-right ms-2"></i>
                            </a>
                            @else
                            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#courseCompletedModal">
                                <i class="fas fa-trophy me-2"></i>Complete Course
                            </button>
                            @endif
                        </div>
                    </div>
                </div>

                <!-- Overview Tab -->
                <div class="tab-pane fade" id="overview" role="tabpanel" aria-labelledby="overview-tab">
                    <div class="p-4">
                        <h4 class="mb-4">Course Overview</h4>
                        <div class="course-description mb-4">
                            {!! nl2br(e($course->description)) !!}
                        </div>

                        @if($course->what_you_will_learn)
                        <div class="mb-4">
                            <h5 class="mb-3">What You'll Learn</h5>
                            <div class="row">
                                @foreach(explode("\n", $course->what_you_will_learn) as $point)
                                    @if(trim($point))
                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex">
                                            <i class="fas fa-check text-success me-2 mt-1"></i>
                                            <span>{{ trim($point) }}</span>
                                        </div>
                                    </div>
                                    @endif
                                @endforeach
                            </div>
                        </div>
                        @endif

                        <div class="mb-4">
                            <h5 class="mb-3">Your Progress</h5>
                            <div class="progress mb-3" style="height: 10px;">
                                <div class="progress-bar" role="progressbar" style="width: {{ $enrollment->getProgressPercentage() }}%;" aria-valuenow="{{ $enrollment->getProgressPercentage() }}" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                            <div class="d-flex justify-content-between">
                                <div>Completed: {{ $enrollment->getCompletedLessonsCount() }} / {{ $course->sections->flatMap->lessons->count() }} lessons</div>
                                <div>{{ $enrollment->getProgressPercentage() }}% complete</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Questions Tab -->
                <div class="tab-pane fade" id="questions" role="tabpanel" aria-labelledby="questions-tab">
                    <div class="p-4">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4>Questions & Answers</h4>
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#askQuestionModal">
                                <i class="fas fa-question-circle me-2"></i>Ask a Question
                            </button>
                        </div>

                        <div class="mb-4">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search questions...">
                                <button class="btn btn-outline-secondary" type="button">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>

                        @if($questions->count() > 0)
                            @foreach($questions as $question)
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="d-flex align-items-center">
                                            <img src="{{ $question->user->profile_photo ? asset('storage/' . $question->user->profile_photo) : asset('assets/images/default-avatar.jpg') }}" 
                                                class="rounded-circle me-2" alt="{{ $question->user->name }}" width="40" height="40">
                                            <div>
                                                <div class="fw-bold">{{ $question->user->name }}</div>
                                                <div class="text-muted small">{{ $question->created_at->diffForHumans() }}</div>
                                            </div>
                                        </div>
                                        <div>
                                            <span class="badge {{ $question->is_resolved ? 'bg-success' : 'bg-secondary' }}">
                                                {{ $question->is_resolved ? 'Resolved' : 'Open' }}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <h5 class="card-title">{{ Str::limit(strip_tags($question->question), 100) }}</h5>
                                    <p class="card-text">{{ $question->question }}</p>
                                </div>
                                
                                <!-- Answers -->
                                @if($question->answers->count() > 0)
                                <div class="list-group list-group-flush">
                                    @foreach($question->answers as $answer)
                                    <div class="list-group-item {{ $answer->is_best_answer ? 'bg-success bg-opacity-10' : '' }}">
                                        <div class="d-flex align-items-start mb-2">
                                            <img src="{{ $answer->user->profile_photo ? asset('storage/' . $answer->user->profile_photo) : asset('assets/images/default-avatar.jpg') }}" 
                                                class="rounded-circle me-2" alt="{{ $answer->user->name }}" width="40" height="40">
                                            <div class="flex-grow-1">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <div class="fw-bold">{{ $answer->user->name }}</div>
                                                        <div class="text-muted small">{{ $answer->created_at->diffForHumans() }}</div>
                                                    </div>
                                                    @if($answer->is_best_answer)
                                                    <div class="text-success">
                                                        <i class="fas fa-check-circle me-1"></i>Best Answer
                                                    </div>
                                                    @elseif($question->user_id == Auth::id())
                                                    <form action="{{ route('courses.markBestAnswer', $answer->id) }}" method="POST">
                                                        @csrf
                                                        <button type="submit" class="btn btn-sm btn-outline-success">Mark as Best</button>
                                                    </form>
                                                    @endif
                                                </div>
                                                <div class="mt-2">
                                                    {{ $answer->answer }}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    @endforeach
                                </div>
                                @endif
                                
                                <div class="card-footer bg-light">
                                    <form action="{{ route('courses.answerQuestion', $question->id) }}" method="POST">
                                        @csrf
                                        <div class="mb-3">
                                            <textarea class="form-control" name="answer" rows="2" placeholder="Write your answer here"></textarea>
                                        </div>
                                        <button type="submit" class="btn btn-primary">Submit Answer</button>
                                    </form>
                                </div>
                            </div>
                            @endforeach
                        @else
                            <div class="text-center py-5">
                                <i class="fas fa-question-circle fa-3x text-muted mb-3"></i>
                                <h5>No Questions Yet</h5>
                                <p class="text-muted">Be the first to ask a question about this course</p>
                            </div>
                        @endif
                    </div>
                </div>

                <!-- Announcements Tab -->
                <div class="tab-pane fade" id="announcements" role="tabpanel" aria-labelledby="announcements-tab">
                    <div class="p-4">
                        <h4 class="mb-4">Course Announcements</h4>
                        
                        @if($course->announcements->count() > 0)
                            @foreach($course->announcements as $announcement)
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">{{ $announcement->title }}</h5>
                                        <span class="text-muted small">{{ $announcement->created_at->format('M d, Y') }}</span>
                                    </div>
                                </div>
                                <div class="card-body">
                                    {!! nl2br(e($announcement->content)) !!}
                                </div>
                            </div>
                            @endforeach
                        @else
                            <div class="text-center py-5">
                                <i class="fas fa-bullhorn fa-3x text-muted mb-3"></i>
                                <h5>No Announcements</h5>
                                <p class="text-muted">There are no announcements for this course yet.</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Ask Question Modal -->
<div class="modal fade" id="askQuestionModal" tabindex="-1" aria-labelledby="askQuestionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="askQuestionModalLabel">Ask a Question</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('courses.askQuestion', ['slug' => $course->slug, 'lessonId' => $currentLesson->id]) }}" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="question" class="form-label">Your Question</label>
                        <textarea class="form-control" id="question" name="question" rows="5" required></textarea>
                        <div class="form-text">Be specific and imagine you're asking a question to another person.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Submit Question</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Course Completed Modal -->
<div class="modal fade" id="courseCompletedModal" tabindex="-1" aria-labelledby="courseCompletedModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body text-center p-5">
                <div class="mb-4">
                    <i class="fas fa-trophy fa-5x text-warning"></i>
                </div>
                <h3 class="mb-3">Congratulations!</h3>
                <p class="lead mb-4">You've completed the course "{{ $course->title }}"</p>
                <div class="d-grid gap-2">
                    <a href="{{ route('courses.show', $course->slug) }}" class="btn btn-primary">
                        <i class="fas fa-star me-2"></i>Rate and Review
                    </a>
                    <a href="{{ route('student.dashboard') }}" class="btn btn-outline-primary">
                        <i class="fas fa-arrow-right me-2"></i>Find Another Course
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        // Mark lesson as complete
        $('#markAsComplete').on('click', function() {
            const courseSlug = $(this).data('course');
            const lessonId = $(this).data('lesson');
            
            $.ajax({
                url: `/courses/${courseSlug}/learn/${lessonId}/complete`,
                type: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#markAsComplete').html('<i class="fas fa-check-circle me-1"></i> Completed')
                            .removeClass('btn-primary')
                            .addClass('btn-success')
                            .prop('disabled', true);
                            
                        // Update progress bar
                        $('.progress-bar').css('width', response.progress_percentage + '%');
                        
                        // If the course is completed
                        if (response.is_course_completed) {
                            $('#courseCompletedModal').modal('show');
                        }
                    }
                },
                error: function(xhr) {
                    console.error('Error marking lesson as complete', xhr);
                }
            });
        });

        // Auto expand current lesson's section
        $(document).ready(function() {
            $('.accordion-collapse.show').closest('.accordion-item').find('.accordion-button').removeClass('collapsed');
        });
    });
</script>
@endpush
@endsection