<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['studentid'];
$intake = $_SESSION['intake'];
$program = $_SESSION['program'];

// Function to calculate current year and semester based on intake
function calculateCurrentYearSemester($intake) {
    $intakeDate = DateTime::createFromFormat('F Y', $intake);
    if (!$intakeDate) {
        return ['year' => 1, 'semester' => 1];
    }
    
    $currentDate = new DateTime();
    $interval = $currentDate->diff($intakeDate);
    $monthsDifference = ($interval->y * 12) + $interval->m;
    $currentSemester = floor($monthsDifference / 6) + 1;
    $currentYear = ceil($currentSemester / 2);
    $semesterInYear = ($currentSemester % 2 == 0) ? 2 : 1;
    
    return [
        'year' => max(1, $currentYear),
        'semester' => $semesterInYear,
        'total_semesters' => $currentSemester
    ];
}

$currentInfo = calculateCurrentYearSemester($intake);
$currentYear = $currentInfo['year'];
$currentSemester = $currentInfo['semester'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Courses -Student Portal</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: var(--primary);
            --secondary-color: #2c3e50;
            --accent-color: #3498db;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
            min-height: 100vh;
            padding: 0;
            margin: 0;
        }
        
        .content {
            padding: 5px;
        }
        
        /* Card Styles */
        .card-custom {
            background: white;
            border-radius:1px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            border: none;
            margin-bottom: 25px;
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .card-custom:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(0,0,0,0.15);
        }
        
        .card-header-custom {
            background: var(--primary-color);
            color: white;
            padding: 20px 25px;
            border-bottom: none;
        }
        
        /* Table Styles */
        .table-responsive-custom {
            border-radius: 0 0 16px 16px;
            overflow: hidden;
        }
        
        .courses-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin: 0;
        }
        
        .courses-table th {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            color: var(--secondary-color);
            font-weight: 600;
            padding: 16px 20px;
            border-bottom: 2px solid #dee2e6;
            font-size: 0.9rem;
        }
        
        .courses-table td {
            padding: 16px 20px;
            border-bottom: 1px solid #f1f3f4;
            vertical-align: middle;
            transition: background-color 0.2s ease;
        }
        
        .courses-table tr:last-child td {
            border-bottom: none;
        }
        
        .courses-table tr:hover td {
            background-color: #f8fafc;
        }
        
        /* Status Badges */
        .status-completed { 
            color: var(--success-color); 
            font-weight: 600;
            background: rgba(40, 167, 69, 0.1);
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .status-current { 
            color: var(--accent-color); 
            font-weight: 600;
            background: rgba(52, 152, 219, 0.1);
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .status-pending { 
            color: var(--warning-color); 
            font-weight: 600;
            background: rgba(255, 193, 7, 0.1);
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .status-registered { 
            color: var(--info-color); 
            font-weight: 600;
            background: rgba(23, 162, 184, 0.1);
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        /* Badges */
        .year-badge {
            background: #6c757d;
            color: white;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .semester-badge {
            background: var(--primary-color);
            color: white;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .course-code {
            font-weight: 700;
            color: var(--secondary-color);
            font-size: 0.95rem;
        }
        
        /* Button Styles */
        .btn-register {
            background: linear-gradient(135deg, var(--success-color), #218838);
            border: none;
            padding: 12px 25px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s ease;
            color: white;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
        }
        
        .btn-register:hover {
            background: linear-gradient(135deg, #218838, #1e7e34);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40, 167, 69, 0.3);
            color: white;
        }
        
        /* Filter Section */
        .filter-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
        }
        
        /* Stats Cards */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            border-left: 4px solid var(--primary-color);
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .content {
                padding: 15px;
            }
            
            .card-header-custom {
                padding: 15px 20px;
            }
            
            .courses-table th,
            .courses-table td {
                padding: 12px 15px;
                font-size: 0.85rem;
            }
            
            .table-responsive-custom {
                font-size: 0.9rem;
            }
            
            .btn-register {
                padding: 10px 20px;
                font-size: 0.9rem;
            }
            
            .stats-container {
                grid-template-columns: 1fr;
            }
        }
        
        @media (max-width: 576px) {
            .content {
                padding: 10px;
            }
            
            .courses-table {
                font-size: 0.8rem;
            }
            
            .courses-table th,
            .courses-table td {
                padding: 8px 10px;
            }
            
            .status-completed,
            .status-current,
            .status-pending,
            .status-registered {
                padding: 4px 8px;
                font-size: 0.75rem;
            }
            
            .year-badge,
            .semester-badge {
                padding: 4px 8px;
                font-size: 0.7rem;
            }
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 50px 20px;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        /* Loading Animation */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>

    <div class="content">
        <div class="container-fluid">
            <!-- Stats Overview -->
            <div class="stats-container fade-in">
                <?php
                // Get course statistics
                $totalQuery = "SELECT COUNT(*) as total FROM registered_course WHERE student_id = '$userlogin'";
                $totalResult = mysqli_query($conn, $totalQuery);
                $totalCourses = mysqli_fetch_assoc($totalResult)['total'];
                
                $completedQuery = "SELECT COUNT(*) as completed FROM registered_course rc 
                                 JOIN results r ON rc.student_id = r.studentid AND rc.course_name = r.course 
                                 WHERE rc.student_id = '$userlogin' AND (r.ca + r.ca1 + r.ca2 + r.exam) >= 40";
                $completedResult = mysqli_query($conn, $completedQuery);
                $completedCourses = mysqli_fetch_assoc($completedResult)['completed'];
                
                $inProgressQuery = "SELECT COUNT(*) as in_progress FROM registered_course rc 
                                  JOIN submit s ON rc.student_id = s.student_id AND rc.course_name = s.course 
                                  WHERE rc.student_id = '$userlogin'";
                $inProgressResult = mysqli_query($conn, $inProgressQuery);
                $inProgressCourses = mysqli_fetch_assoc($inProgressResult)['in_progress'];
                
                $registeredQuery = "SELECT COUNT(*) as registered FROM registered_course 
                                  WHERE student_id = '$userlogin' 
                                  AND course_name NOT IN (
                                      SELECT course FROM submit WHERE student_id = '$userlogin'
                                  )
                                  AND course_name NOT IN (
                                      SELECT course FROM results WHERE studentid = '$userlogin' AND (ca + ca1 + ca2 + exam) >= 40
                                  )";
                $registeredResult = mysqli_query($conn, $registeredQuery);
                $registeredCourses = mysqli_fetch_assoc($registeredResult)['registered'];
                ?>
           
            </div>

            

            <!-- Registered Courses Display -->
            <div class="card-custom fade-in">
                <div class="card-header-custom d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="mb-1"><i class="fas fa-book me-2"></i>Registered Courses</h5>
                        <p class="mb-0 opacity-90">In <?php echo $currentYear; ?>,<?php echo $currentSemester; ?></p>
                    </div>
                    <a href="reg_course.php" class="btn btn-light btn-sm">
                        <i class="fas fa-plus-circle me-2"></i>Register New Courses
                    </a>
                </div>
                
                <div class="table-responsive-custom">
                  <?PHP
$yearly=date('Y');
  $registeredQuery = "
    SELECT *
    FROM results
    WHERE studentid = '$userlogin' AND term='$currentSemester' AND year='$yearly'
    ORDER BY year, term, course ASC
";

$registeredResult = mysqli_query($conn, $registeredQuery);

                    if (mysqli_num_rows($registeredResult) > 0) {
                        ?>
                        <table class="courses-table">
                            <thead>
                                <tr>
                                    <th>Course Name</th>
                                    <th>Year</th>
                                    <th>Semester</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                while ($course = mysqli_fetch_assoc($registeredResult)) {
                                    $statusClass = '';
                                    $statusIcon = '';
                                    
                                    
                                    ?>
                                   
                                        
                                        <td><?php echo strtoupper(htmlspecialchars($course['course'])); ?></td>
                                        <td>
                                            <span class="year-badge"> <?php echo htmlspecialchars($course['year']); ?></span>
                                        </td>
                                        <td>
                                            <span class="semester-badge"> <?php echo htmlspecialchars($course['term']); ?></span>
                                        </td>
                                        <td>
                                            <span class="<?php echo $statusClass; ?>">
                                                <i class="fas fa-clipboard-check me-1"></i> Registered
                                            </span>
                                        </td>
                                        
                                    </tr>
                                    <?php
                                }
                                ?>
                            </tbody>
                        </table>
                        <br><br>
                        <?php
                    } else {
                        echo '<div class="empty-state">';
                        echo '<i class="fas fa-book-open"></i>';
                        echo '<h5 class="text-muted">No courses registered yet</h5>';
                        echo '<p class="text-muted">Start by registering your courses using the button above.</p>';
                       
                        echo '</a>';
                        echo '</div>';
                    }
                    ?>
                </div>
            </div>
        </div>
        
        <br><br>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Filter functionality
            const filterYear = document.getElementById('filterYear');
            const filterSemester = document.getElementById('filterSemester');
            const courseRows = document.querySelectorAll('.course-row');
            
            function filterCourses() {
                const selectedYear = filterYear.value;
                const selectedSemester = filterSemester.value;
                
                courseRows.forEach(row => {
                    const rowYear = row.getAttribute('data-year');
                    const rowSemester = row.getAttribute('data-semester');
                    
                    const yearMatch = !selectedYear || rowYear === selectedYear;
                    const semesterMatch = !selectedSemester || rowSemester === selectedSemester;
                    
                    if (yearMatch && semesterMatch) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            }
            
            if (filterYear && filterSemester) {
                filterYear.addEventListener('change', filterCourses);
                filterSemester.addEventListener('change', filterCourses);
            }
        });
    </script>
</body>
</html>