<?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'];
// Handle course registration
if (isset($_POST['register_courses'])) {
    if (isset($_POST['selected_courses']) && !empty($_POST['selected_courses'])) {
        $successCount = 0;
        $resultsCount = 0;
        
        foreach ($_POST['selected_courses'] as $courseName) {
            // Get course details
            $courseQuery = "SELECT * FROM course WHERE course = '$courseName' AND program = '$program'";
            $courseResult = mysqli_query($conn, $courseQuery);
            
            if (mysqli_num_rows($courseResult) > 0) {
                $courseData = mysqli_fetch_assoc($courseResult);
                $courseCode = substr($courseName, 0, min(5, strlen($courseName)));
                
                // Check if already registered
                $checkQuery = "SELECT id FROM registered_course 
                              WHERE student_id = '$userlogin' AND course_name = '$courseName'";
                $checkResult = mysqli_query($conn, $checkQuery);
                
                if (mysqli_num_rows($checkResult) == 0) {
                    // Insert into registered_course table
                    $insertQuery = "INSERT INTO registered_course 
                                   (student_id, course_code, course_name, program, intake, academic_year, semester) 
                                   VALUES ('$userlogin', '$courseCode', '$courseName', '$program', '$intake', 
                                           '{$courseData['year']}', '{$courseData['semester']}')";
                    
                    if (mysqli_query($conn, $insertQuery)) {
                        $successCount++;
                         $currentYearin = date('Y');
                        // Also insert into results table with empty values
                        $resultsQuery = "INSERT INTO results 
                                        (studentid, course, term, year, intake, ca, ca1, ca2, exam, email) 
                                        VALUES ('$userlogin', '$courseName', '$currentSemester', 
                                                '$currentYearin', '$intake', '', '', '', '', '')";
                        
                        if (mysqli_query($conn, $resultsQuery)) {
                            $resultsCount++;
                        }
                        
                        
                        
                        
                        
                        
                        
                    }
                }
            }
        }
        
        if ($successCount > 0) {
            $message = "<div class='alert alert-success' role='alert'>
                        <i class='fas fa-check-circle me-2'></i>Successfully registered $successCount course(s)!";
            if ($resultsCount > 0) {
                $message .= " $resultsCount course(s) added to results.";
            }
            $message .= "</div>";
        } else {
            $message = "<div class='alert alert-info' role='alert'>
                        <i class='fas fa-info-circle me-2'></i>No new courses were registered.
                      </div>";
        }
    } else {
        $message = "<div class='alert alert-warning' role='alert'>
                    <i class='fas fa-exclamation-triangle me-2'></i>Please select at least one course to register.
                  </div>";
    }
}


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Course Registration</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #f8f9fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 30px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
        }

        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .header p {
            color: #6c757d;
            font-size: 1.1rem;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            background: #6c757d;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            text-decoration: none;
            margin-bottom: 20px;
            transition: background 0.3s ease;
        }

        .back-btn:hover {
            background: #5a6268;
            color: white;
        }

        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .course-list {
            max-height: 100%;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
        }

        .course-item {
            display: flex;
            align-items: center;
            padding: 15px;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }

        .course-item:hover {
            background: #f8f9fa;
            border-color: #007bff;
        }

        .course-item.selected {
            background: #e3f2fd;
            border-color: #007bff;
        }

        .course-checkbox {
            margin-right: 15px;
            transform: scale(1.2);
        }

        .course-info {
            flex: 1;
        }

        .course-code {
            font-weight: bold;
            color: #2c3e50;
        }

        .badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            margin-left: 8px;
        }

        .badge-year {
            background: #6c757d;
            color: white;
        }

        .badge-semester {
            background: #17a2b8;
            color: white;
        }

        .select-all {
            display: flex;
            align-items: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
            margin-bottom: 15px;
        }

        .select-all input {
            margin-right: 10px;
            transform: scale(1.2);
        }

        .actions {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
        }

        .btn-cancel {
            background: #6c757d;
            color: white;
        }

        .btn-cancel:hover {
            background: #5a6268;
        }

        .btn-register {
            background: #dc3545;
            color: white;
        }

        .btn-register:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .note-box {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
            color: #856404;
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>

    <div class="content">
        <div class="container">
            <div class="">
                <h1><i class="fas fa-book me-2"></i>Course Registration</h1>
                <p>Select courses you are currently taking in <?php echo $currentYear; ?>, <?php echo $currentSemester; ?> only</p>
            </div>

            <?php if (isset($message)) echo $message; ?>

            

            <form method="POST" action="">
               

                <div class="course-list">  
                    <?php
                    // Get available courses
                    $availableQuery = "SELECT * FROM course 
                                     WHERE program = '$program' and year='$currentYear' and semester='$currentSemester'
                                     AND course.course NOT IN (
                                         SELECT results.course FROM results 
                                         WHERE studentid = '$userlogin'
                                     )
                                     ORDER BY year, semester, course ASC";
                    
                    $availableResult = mysqli_query($conn, $availableQuery);
                    
                    if (mysqli_num_rows($availableResult) > 0) {
                        while ($course = mysqli_fetch_assoc($availableResult)) {
                            $courseName = $course['course'];
                            $courseCode = substr($courseName, 0, min(5, strlen($courseName)));
                            ?>
                            <div class="course-item">
                                <input type="checkbox" name="selected_courses[]" 
                                       value="<?php echo htmlspecialchars($courseName); ?>" 
                                       class="course-checkbox" 
                                       id="course_<?php echo htmlspecialchars($courseName); ?>">
                                <div class="course-info">
                                    <label for="course_<?php echo strtoupper(htmlspecialchars($courseName)); ?>" style="cursor: pointer;">
                                        <span class="course-code"></span> 
                                        <?php echo strtoupper(htmlspecialchars($courseName)); ?>
                                        <span class="badge badge-year">Year <?php echo $course['year']; ?></span>
                                        <span class="badge badge-semester">Semester <?php echo $course['semester']; ?></span>
                                    </label>
                                </div>
                            </div>
                            <?php
                        }
                    } else {
                        echo '<div class="empty-state">';
                        echo '<i class="fas fa-check-circle"></i>';
                        echo '<h3>All courses registered</h3>';
                        echo '<p>No more courses available for registration.</p>';
                        echo '</div>';
                    }
                    ?>
                </div>

                <?php if (mysqli_num_rows($availableResult) > 0) { ?>
                <div class="actions">
                    <button type="submit" name="register_courses" class="btn btn-dark">
                        <i class="fas fa-save me-2"></i> Register Selected Courses
                    </button>
                </div>
                <?php } ?>
                <br><br>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const courseCheckboxes = document.querySelectorAll('.course-checkbox');
            const courseItems = document.querySelectorAll('.course-item');

            // Select all functionality
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    courseCheckboxes.forEach(checkbox => {
                        checkbox.checked = selectAllCheckbox.checked;
                        updateCourseItemStyle(checkbox);
                    });
                });
            }

            // Update course item style
            courseCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    updateCourseItemStyle(this);
                    updateSelectAllState();
                });
                updateCourseItemStyle(checkbox);
            });

            function updateCourseItemStyle(checkbox) {
                const courseItem = checkbox.closest('.course-item');
                if (checkbox.checked) {
                    courseItem.classList.add('selected');
                } else {
                    courseItem.classList.remove('selected');
                }
            }

            function updateSelectAllState() {
                if (!selectAllCheckbox) return;
                
                const checkedBoxes = document.querySelectorAll('.course-checkbox:checked');
                const allBoxes = document.querySelectorAll('.course-checkbox');
                
                selectAllCheckbox.checked = checkedBoxes.length === allBoxes.length && allBoxes.length > 0;
            }
        });
    </script>
</body>
</html>