@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'My Courses')

@section('left_sidebar')
@include('front_end.pages.courses.courses_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- Header Section -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center">
                            <a href="{{ route('student.dashboard') }}" class="text-white me-3">
                                <i class="fas fa-arrow-left fa-lg"></i>
                            </a>
                            <div>
                                <h4 class="mb-0 text-white">My Courses</h4>
                                <p class="mb-0 text-white">{{ $enrollments->total() }} courses enrolled</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container py-5">
        <!-- Filter Tabs -->
        <div class="mb-4">
            <ul class="nav nav-pills" id="coursesTab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="all-tab" data-bs-toggle="tab" data-bs-target="#all-courses" type="button" role="tab" aria-controls="all-courses" aria-selected="true">All Courses</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="in-progress-tab" data-bs-toggle="tab" data-bs-target="#in-progress-courses" type="button" role="tab" aria-controls="in-progress-courses" aria-selected="false">In Progress</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="completed-tab" data-bs-toggle="tab" data-bs-target="#completed-courses" type="button" role="tab" aria-controls="completed-courses" aria-selected="false">Completed</button>
                </li>
            </ul>
        </div>

        <!-- Search Bar -->
        <div class="row mb-4">
            <div class="col-md-8">
                <div class="input-group">
                    <span class="input-group-text bg-white">
                        <i class="fas fa-search"></i>
                    </span>
                    <input type="text" class="form-control" id="searchCourse" placeholder="Search your courses">
                    <button class="btn btn-primary" type="button" id="searchButton">Search</button>
                </div>
            </div>
            <div class="col-md-4">
                <select class="form-select" id="sortCourses">
                    <option value="newest">Recently Enrolled</option>
                    <option value="oldest">Oldest First</option>
                    <option value="a-z">Title: A-Z</option>
                    <option value="z-a">Title: Z-A</option>
                    <option value="progress">Progress</option>
                </select>
            </div>
        </div>

        <!-- Courses Tab Content -->
        <div class="tab-content" id="coursesTabContent">
            <!-- All Courses Tab -->
            <div class="tab-pane fade show active" id="all-courses" role="tabpanel" aria-labelledby="all-tab">
                @if($enrollments->count() > 0)
                <div class="row g-4">
                    @foreach($enrollments as $enrollment)
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 border-0 shadow-sm hover-shadow transition-all">
                            <a href="{{ route('courses.learn', $enrollment->course->slug) }}">
                                <img src="{{ $enrollment->course->thumbnail ? asset('storage/' . $enrollment->course->thumbnail) : asset('assets/images/course-placeholder.jpg') }}" 
                                     class="card-img-top" alt="{{ $enrollment->course->title }}">
                            </a>
                            <div class="card-body p-4">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="badge bg-{{ $enrollment->course->level == 'beginner' ? 'success' : ($enrollment->course->level == 'intermediate' ? 'warning' : 'danger') }}">
                                        {{ ucfirst($enrollment->course->level) }}
                                    </span>
                                    <small class="text-muted">Enrolled {{ $enrollment->created_at->diffForHumans() }}</small>
                                </div>
                                <h5 class="card-title mb-2">
                                    <a href="{{ route('courses.learn', $enrollment->course->slug) }}" class="text-decoration-none text-dark">{{ $enrollment->course->title }}</a>
                                </h5>
                                <p class="text-muted small mb-3">
                                    <i class="fas fa-user-tie me-1"></i> {{ $enrollment->course->instructor->name ?? 'Unknown Instructor' }}
                                </p>
                                
                                <!-- Progress Bar -->
                                <div class="progress mb-2" style="height: 6px;">
                                    <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 align-items-center text-muted small mb-3">
                                    <span>{{ $enrollment->getProgressPercentage() }}% complete</span>
                                    <span>{{ $enrollment->getCompletedLessonsCount() }}/{{ $enrollment->course->sections->flatMap->lessons->count() ?? 0 }} lessons</span>
                                </div>
                            </div>
                            <div class="card-footer bg-white border-top-0 p-4">
                                <a href="{{ route('courses.learn', $enrollment->course->slug) }}" class="btn btn-primary w-100">
                                    @if($enrollment->getProgressPercentage() == 0)
                                        <i class="fas fa-play-circle me-2"></i>Start Learning
                                    @elseif($enrollment->getProgressPercentage() == 100)
                                        <i class="fas fa-redo-alt me-2"></i>Review Course
                                    @else
                                        <i class="fas fa-play-circle me-2"></i>Continue Learning
                                    @endif
                                </a>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>

                <!-- Pagination -->
                <div class="d-flex justify-content-center mt-5">
                    {{ $enrollments->links('pagination::bootstrap-5') }}
                </div>
                @else
                <div class="text-center py-5">
                    <i class="fas fa-graduation-cap fa-4x text-muted mb-4"></i>
                    <h4>You haven't enrolled in any courses yet</h4>
                    <p class="text-muted mb-4">Browse our course catalog and start your learning journey today!</p>
                    <a href="{{ route('courses.index') }}" class="btn btn-primary">Browse Courses</a>
                </div>
                @endif
            </div>

            <!-- In Progress Courses Tab -->
            <div class="tab-pane fade" id="in-progress-courses" role="tabpanel" aria-labelledby="in-progress-tab">
                @php
                $inProgressEnrollments = $enrollments->filter(function($enrollment) {
                    $progress = $enrollment->getProgressPercentage();
                    return $progress > 0 && $progress < 100;
                });
                @endphp
                
                @if($inProgressEnrollments->count() > 0)
                <div class="row g-4">
                    @foreach($inProgressEnrollments as $enrollment)
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 border-0 shadow-sm hover-shadow transition-all">
                            <a href="{{ route('courses.learn', $enrollment->course->slug) }}">
                                <img src="{{ $enrollment->course->thumbnail ? asset('storage/' . $enrollment->course->thumbnail) : asset('assets/images/course-placeholder.jpg') }}" 
                                     class="card-img-top" alt="{{ $enrollment->course->title }}">
                            </a>
                            <div class="card-body p-4">
                                <h5 class="card-title mb-2">
                                    <a href="{{ route('courses.learn', $enrollment->course->slug) }}" class="text-decoration-none text-dark">{{ $enrollment->course->title }}</a>
                                </h5>
                                <p class="text-muted small mb-3">
                                    <i class="fas fa-user-tie me-1"></i> {{ $enrollment->course->instructor->name ?? 'Unknown Instructor' }}
                                </p>
                                
                                <!-- Progress Bar -->
                                <div class="progress mb-2" style="height: 6px;">
                                    <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 align-items-center text-muted small mb-3">
                                    <span>{{ $enrollment->getProgressPercentage() }}% complete</span>
                                    <span>Last accessed: {{ $enrollment->last_accessed_at ? $enrollment->last_accessed_at->diffForHumans() : 'N/A' }}</span>
                                </div>
                            </div>
                            <div class="card-footer bg-white border-top-0 p-4">
                                <a href="{{ route('courses.learn', $enrollment->course->slug) }}" class="btn btn-primary w-100">
                                    <i class="fas fa-play-circle me-2"></i>Continue Learning
                                </a>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
                @else
                <div class="text-center py-5">
                    <i class="fas fa-hourglass-half fa-4x text-muted mb-4"></i>
                    <h4>No courses in progress</h4>
                    <p class="text-muted mb-4">You don't have any courses in progress. Start learning to see courses here!</p>
                </div>
                @endif
            </div>

            <!-- Completed Courses Tab -->
            <div class="tab-pane fade" id="completed-courses" role="tabpanel" aria-labelledby="completed-tab">
                @php
                $completedEnrollments = $enrollments->filter(function($enrollment) {
                    return $enrollment->getProgressPercentage() == 100;
                });
                @endphp
                
                @if($completedEnrollments->count() > 0)
                <div class="row g-4">
                    @foreach($completedEnrollments as $enrollment)
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 border-0 shadow-sm hover-shadow transition-all">
                            <div class="card-img-overlay text-end p-2">
                                <span class="badge bg-success p-2">
                                    <i class="fas fa-check-circle me-1"></i>Completed
                                </span>
                            </div>
                            <a href="{{ route('courses.learn', $enrollment->course->slug) }}">
                                <img src="{{ $enrollment->course->thumbnail ? asset('storage/' . $enrollment->course->thumbnail) : asset('assets/images/course-placeholder.jpg') }}" 
                                     class="card-img-top" alt="{{ $enrollment->course->title }}">
                            </a>
                            <div class="card-body p-4">
                                <h5 class="card-title mb-2">
                                    <a href="{{ route('courses.learn', $enrollment->course->slug) }}" class="text-decoration-none text-dark">{{ $enrollment->course->title }}</a>
                                </h5>
                                <p class="text-muted small mb-3">
                                    <i class="fas fa-user-tie me-1"></i> {{ $enrollment->course->instructor->name ?? 'Unknown Instructor' }}
                                </p>
                                
                                <!-- Completed Info -->
                                <div class="d-flex justify-content-between align-items-center text-muted small mb-3">
                                    <span>Completed on: {{ $enrollment->completed_at ? $enrollment->completed_at->format('M d, Y') : 'Unknown' }}</span>
                                    <span>
                                        <i class="fas fa-clock me-1"></i>{{ $enrollment->course->total_duration ?? 0 }} hours
                                    </span>
                                </div>
                                
                                @if(!$enrollment->hasReview())
                                <div class="alert alert-light border small p-2 text-center mb-3">
                                    <i class="fas fa-star text-warning me-1"></i>
                                    <span>Share your feedback with others</span>
                                </div>
                                @endif
                            </div>
                            <div class="card-footer bg-white border-top-0 p-4">
                                <div class="row g-2">
                                    <div class="col-6">
                                        <a href="{{ route('courses.learn', $enrollment->course->slug) }}" class="btn btn-outline-primary w-100">
                                            <i class="fas fa-redo-alt me-2"></i>Review
                                        </a>
                                    </div>
                                    <div class="col-6">
                                        @if($enrollment->hasReview())
                                        <button class="btn btn-outline-success w-100" disabled>
                                            <i class="fas fa-check me-2"></i>Reviewed
                                        </button>
                                        @else
                                        <a href="{{ route('courses.show', $enrollment->course->slug) }}#reviews" class="btn btn-outline-warning w-100">
                                            <i class="fas fa-star me-2"></i>Rate
                                        </a>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
                @else
                <div class="text-center py-5">
                    <i class="fas fa-award fa-4x text-muted mb-4"></i>
                    <h4>No completed courses yet</h4>
                    <p class="text-muted mb-4">Keep learning and your completed courses will appear here!</p>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        // Search functionality
        $('#searchButton').on('click', function() {
            const searchTerm = $('#searchCourse').val().toLowerCase();
            
            $('.card').each(function() {
                const courseTitle = $(this).find('.card-title').text().toLowerCase();
                const instructorName = $(this).find('.text-muted small').text().toLowerCase();
                
                if (courseTitle.includes(searchTerm) || instructorName.includes(searchTerm)) {
                    $(this).parent().show();
                } else {
                    $(this).parent().hide();
                }
            });
        });
        
        // Reset search when changing tabs
        $('.nav-link').on('click', function() {
            $('#searchCourse').val('');
            $('.card').parent().show();
        });
        
        // Sort functionality
        $('#sortCourses').on('change', function() {
            const sortValue = $(this).val();
            const courseCards = $('.tab-pane.active .row .col-md-6').get();
            
            courseCards.sort(function(a, b) {
                switch(sortValue) {
                    case 'a-z':
                        const titleA = $(a).find('.card-title').text().toUpperCase();
                        const titleB = $(b).find('.card-title').text().toUpperCase();
                        return (titleA < titleB) ? -1 : (titleA > titleB) ? 1 : 0;
                        
                    case 'z-a':
                        const titleADesc = $(a).find('.card-title').text().toUpperCase();
                        const titleBDesc = $(b).find('.card-title').text().toUpperCase();
                        return (titleADesc > titleBDesc) ? -1 : (titleADesc < titleBDesc) ? 1 : 0;
                        
                    case 'progress':
                        const progressA = parseInt($(a).find('.progress-bar').attr('aria-valuenow')) || 0;
                        const progressB = parseInt($(b).find('.progress-bar').attr('aria-valuenow')) || 0;
                        return progressB - progressA;
                        
                    case 'oldest':
                        // We don't have direct access to enrollment date in DOM, this is simplified
                        // In reality, you might want to add data attributes with timestamps
                        return 1; // Reverse of 'newest'
                        
                    case 'newest':
                    default:
                        return -1; // Default sorting (newest first)
                }
            });
            
            // Reattach sorted items
            const parent = $('.tab-pane.active .row');
            $.each(courseCards, function(index, item) {
                parent.append(item);
            });
        });
    });
</script>
@endpush
@endsection