<?php
session_start();
ob_start();
include "../include/config.php";

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

// Initialize variables
$show_courses = false;
$available_courses = null;
$student_info = null;

// Handle registration form submission
if (isset($_POST['register_courses'])) {
    if (!empty($_POST['selected_courses']) && !empty($_POST['studentid'])) {
        $studentid = mysqli_real_escape_string($conn, $_POST['studentid']);
        $year = mysqli_real_escape_string($conn, $_POST['year']);
        $term = mysqli_real_escape_string($conn, $_POST['term']);
        $success_count = 0;
        
        // Get student information
        $student_query = "SELECT * FROM students WHERE studentid = '$studentid' LIMIT 1";
        $student_result = mysqli_query($conn, $student_query);
        
        if ($student_result && mysqli_num_rows($student_result) > 0) {
            $student_info = mysqli_fetch_assoc($student_result);
            $program = $student_info['program'];
            $intake = $student_info['intake'];
            $email = $student_info['email'];
                        $studentName = $student_info['studentname'];

            foreach ($_POST['selected_courses'] as $course_id) {
                $course_id = intval($course_id);
                
                // Get course details
                $course_query = "SELECT * FROM course WHERE id = '$course_id'";
                $course_result = mysqli_query($conn, $course_query);
                
                if ($course_result && mysqli_num_rows($course_result) > 0) {
                    $course_data = mysqli_fetch_assoc($course_result);
                    $course_name = $course_data['course'];
                    
                    // Check if already registered in results table ONLY
                    $check_query = "SELECT id FROM results 
                                   WHERE studentid = '$studentid' 
                                   AND course = '$course_name' 
                                   AND year = '$year' 
                                   AND term = '$term'";
                    $check_result = mysqli_query($conn, $check_query);
                    
                    if (mysqli_num_rows($check_result) == 0) {
                        // Insert into results table ONLY
                        $insert_query = "INSERT INTO results 
                                        (studentid, course, term, year, intake, ca, ca1, ca2, exam, email) 
                                        VALUES ('$studentid', '$course_name', '$term', '$year', 
                                                '$intake', '', '', '', '', '$email')";
                        
                        if (mysqli_query($conn, $insert_query)) {
                            $success_count++;
                        }
                    }
                }
            }
            
            if ($success_count > 0) {
                $_SESSION['success'] = "Successfully registered $success_count course(s) for student $studentid";
            } else {
                $_SESSION['error'] = "No new courses were registered (courses may already be registered)";
            }
        } else {
            $_SESSION['error'] = "Student not found";
        }
        
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    } else {
        $_SESSION['error'] = "Please select at least one course to register";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

// Handle search form submission
if (isset($_POST['search_student'])) {
    $studentid = mysqli_real_escape_string($conn, $_POST['studentid']);
    $year = mysqli_real_escape_string($conn, $_POST['year']);
    $term = mysqli_real_escape_string($conn, $_POST['term']);
    
    // Get student information
    $student_query = "SELECT * FROM students WHERE studentid = '$studentid' LIMIT 1";
    $student_result = mysqli_query($conn, $student_query);
    
    if ($student_result && mysqli_num_rows($student_result) > 0) {
        $student_info = mysqli_fetch_assoc($student_result);
        $program = $student_info['program'];
        $intake = $student_info['intake'];
        
        // Get courses NOT already registered for this student in the selected year/term
        // ONLY checking results table
        $query = "SELECT c.* 
                  FROM course c 
                  WHERE c.program = '$program' 
                 
                
                  AND c.course NOT IN (
                      SELECT r.course 
                      FROM results r 
                      WHERE r.studentid = '$studentid' 
                      AND r.year = '$year' 
                      AND r.term = '$term'
                  )
                  ORDER BY c.course ASC";
        
        $available_courses = mysqli_query($conn, $query);
        $show_courses = true;
    } else {
        $_SESSION['error'] = "Student not found with ID: $studentid";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Course Registration - Admin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background: #f8f9fa;
            padding-top: 60px;
        }
        .header {
            background: var(--primary) !important;
            color: white;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.2);
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            margin-bottom: 25px;
            transition: transform 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
        }
        .card-header {
            background: var(--primary) !important;
            color: white;
            font-weight: 600;
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
            font-size: 1.1rem;
        }
        .btn-register {
            background: var(--primary) !important;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-register:hover {
            background: linear-gradient(135deg, #218838 0%, #1e9e8a 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
        }
        .btn-search {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-search:hover {
            background: linear-gradient(135deg, #0069d9 0%, #004085 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
        }
        .course-table th {
            background: #f8f9fa;
            border-top: none;
            font-weight: 600;
            color: #495057;
        }
        .course-table tr {
            transition: background-color 0.2s ease;
        }
        .course-table tr:hover {
            background-color: rgba(40, 167, 69, 0.05);
        }
        .select-all-container {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }
        .badge-custom {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 500;
        }
        .student-info-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-left: 4px solid #28a745;
        }
        .search-form-card {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }
        .alert-custom {
            border-radius: 10px;
            border: none;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }
        .no-courses {
            padding: 50px 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }
        .form-control {
            border-radius: 5px;
            border: 1px solid #dee2e6;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
        }
        .custom-checkbox .custom-control-input:checked~.custom-control-label::before {
            background-color: #28a745;
            border-color: #28a745;
        }
        .table-info {
            background: #e8f4f8;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .course-item {
            padding: 15px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        .course-item:hover {
            background: #f8f9fa;
            border-color: #28a745;
        }
        .course-item.selected {
            background: #d4edda;
            border-color: #28a745;
        }
        .course-info {
            margin-left: 10px;
        }
        .course-checkbox {
            transform: scale(1.2);
            margin-right: 10px;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .action-btn {
            width: 35px;
            height: 35px;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }
        .action-btn:hover {
            transform: scale(1.1);
        }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <div class="row">
        <div class="col-12">
            <div class="header text-center">
                <h2><i class="fa fa-book mr-2"></i> Admin Course Registration</h2>
                <p class="mb-0">Register courses for students - Results Table Only</p>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="row">
            <div class="col-12">
                <div class="alert alert-success alert-custom alert-dismissible fade show">
                    <i class="fa fa-check-circle mr-2"></i> 
                    <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            </div>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="row">
            <div class="col-12">
                <div class="alert alert-danger alert-custom alert-dismissible fade show">
                    <i class="fa fa-exclamation-circle mr-2"></i> 
                    <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-12">
            <?php if ($show_courses && $student_info): ?>
                <!-- Table Information -->
                <div class="table-info">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-2"><i class="fa fa-info-circle mr-2"></i> About this Operation:</h6>
                            <p class="mb-0">Courses will be registered in the <strong>results table only</strong>.</p>
                            <ul class="mb-0 pl-3">
                                <li><code>results</code> table: Course registration with empty marks</li>
                                <li>System checks for existing registrations in results table</li>
                                <li>Prevents duplicate course registration</li>
                            </ul>
                        </div>
                        <div class="col-md-4 text-right">
                            <span class="badge badge-success badge-custom">
                                <i class="fa fa-table mr-1"></i> Results Table Only
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Student Information -->
                <div class="card mb-4">
                    <div class="card-body student-info-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h5 class="mb-3"><i class="fa fa-user-graduate mr-2"></i> Student Information</h5>
                                <div class="row">
                                    <div class="col-md-4 mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="fa fa-id-card mr-2 text-muted"></i>
                                            <div>
                                                <small class="text-muted d-block">Student ID</small>
                                                <strong><?php echo htmlspecialchars($student_info['studentid']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="fa fa-user mr-2 text-muted"></i>
                                            <div>
                                                <small class="text-muted d-block">Full Name</small>
                                                <strong><?php echo htmlspecialchars($student_info['fullname']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="fa fa-book-reader mr-2 text-muted"></i>
                                            <div>
                                                <small class="text-muted d-block">Program</small>
                                                <strong><?php echo htmlspecialchars($student_info['program']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="fa fa-calendar-alt mr-2 text-muted"></i>
                                            <div>
                                                <small class="text-muted d-block">Intake</small>
                                                <strong><?php echo htmlspecialchars($student_info['intake']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="fa fa-calendar mr-2 text-muted"></i>
                                            <div>
                                                <small class="text-muted d-block">Registration For</small>
                                                <strong><?php echo htmlspecialchars($_POST['year']); ?> - Semester <?php echo htmlspecialchars($_POST['term']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="fa fa-envelope mr-2 text-muted"></i>
                                            <div>
                                                <small class="text-muted d-block">Email</small>
                                                <strong><?php echo htmlspecialchars($student_info['email']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-center">
                                <div class="bg-light p-3 rounded">
                                    <h2 class="text-success mb-0"><?php echo $available_courses ? mysqli_num_rows($available_courses) : 0; ?></h2>
                                    <small class="text-muted">Available Courses</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Available Courses List -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-0"><i class="fa fa-list-alt mr-2"></i> Available Courses for Registration</h5>
                            <small class="text-white">Year <?php echo htmlspecialchars($_POST['year']); ?>, Semester <?php echo htmlspecialchars($_POST['term']); ?></small>
                        </div>
                        <div>
                            <button type="button" class="btn btn-sm btn-outline-light" onclick="window.location.href='<?php echo $_SERVER['PHP_SELF']; ?>'">
                                <i class="fa fa-search mr-1"></i> New Search
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if ($available_courses && mysqli_num_rows($available_courses) > 0): ?>
                            <form method="POST" action="" id="registerForm">
                                <input type="hidden" name="studentid" value="<?php echo htmlspecialchars($student_info['studentid']); ?>">
                                <input type="hidden" name="year" value="<?php echo htmlspecialchars($_POST['year']); ?>">
                                <input type="hidden" name="term" value="<?php echo htmlspecialchars($_POST['term']); ?>">
                                
                                <!-- Bulk Actions -->
                                <div class="select-all-container mb-4">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <div class="form-check mb-0">
                                                <input class="form-check-input" type="checkbox" id="selectAll">
                                                <label class="form-check-label h6 mb-0" for="selectAll">
                                                    <i class="fa fa-check-square mr-2"></i> Select All Available Courses
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-right">
                                            <div class="btn-group">
                                                <button type="submit" name="register_courses" class="btn btn-sm btn-register">
                                                    <i class="fa fa-save mr-1"></i> Register Selected
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Courses Table View -->
                                <div class="table-responsive">
                                    <table class="table table-hover course-table">
                                        <thead>
                                            <tr>
                                                <th width="40">#</th>
                                                <th width="60">Select</th>
                                                <th>Course Code</th>
                                                <th>Course Name</th>
                                                <th>Year</th>
                                                <th>Semester</th>
                                                <th>Credits</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $counter = 1;
                                            mysqli_data_seek($available_courses, 0);
                                            while($course = mysqli_fetch_assoc($available_courses)): 
                                                $course_code = substr($course['course'], 0, min(5, strlen($course['course'])));
                                            ?>
                                                <tr>
                                                    <td class="text-muted"><?php echo $counter++; ?></td>
                                                    <td>
                                                        <div class="custom-control custom-checkbox">
                                                            <input type="checkbox" class="custom-control-input course-checkbox" 
                                                                   name="selected_courses[]" 
                                                                   value="<?php echo htmlspecialchars($course['id']); ?>"
                                                                   id="course_<?php echo $course['id']; ?>">
                                                            <label class="custom-control-label" for="course_<?php echo $course['id']; ?>"></label>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="font-weight-bold"><?php echo strtoupper($course_code); ?></div>
                                                    </td>
                                                    <td>
                                                        <div class="font-weight-bold"><?php echo strtoupper(htmlspecialchars($course['course'])); ?></div>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-info badge-custom">
                                                            Year <?php echo $course['year']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-primary badge-custom">
                                                            Semester <?php echo $course['semester']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-secondary badge-custom">
                                                            <?php echo $course['credits'] ?? 'N/A'; ?> Credits
                                                        </span>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <!-- Selected Count -->
                                <div class="mt-4 pt-3 border-top">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <span id="selectedCount" class="badge badge-success badge-custom">0</span>
                                            <span class="ml-2">course(s) selected for registration</span>
                                        </div>
                                        <div>
                                            <button type="button" class="btn btn-secondary mr-2" onclick="window.location.href='<?php echo $_SERVER['PHP_SELF']; ?>'">
                                                <i class="fa fa-arrow-left mr-1"></i> Back to Search
                                            </button>
                                            <button type="submit" name="register_courses" class="btn btn-register">
                                                <i class="fa fa-save mr-1"></i> Register Selected Courses
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        <?php else: ?>
                            <div class="no-courses text-center">
                                <i class="fa fa-check-circle fa-4x text-success mb-4"></i>
                                <h4>All Courses Already Registered</h4>
                                <p class="text-muted mb-4">
                                    Student <strong><?php echo htmlspecialchars($student_info['fullname']); ?></strong> has already registered 
                                    all available courses for Year <?php echo htmlspecialchars($_POST['year']); ?>, 
                                    Semester <?php echo htmlspecialchars($_POST['term']); ?> in the results table.
                                </p>
                                <div class="mt-3">
                                    <button onclick="window.location.href='<?php echo $_SERVER['PHP_SELF']; ?>'" class="btn btn-register">
                                        <i class="fa fa-search mr-1"></i> Search Another Student
                                    </button>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($available_courses) mysqli_free_result($available_courses); ?>
                
            <?php else: ?>
                <!-- Search Form -->
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="search-form-card">
                            <h4 class="text-center mb-4"><i class="fa fa-search mr-2"></i> Find Student for Course Registration</h4>
                            <form method="POST" action="">
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label><i class="fa fa-id-card mr-2"></i> Student ID</label>
                                        <input type="text" class="form-control form-control-lg" name="studentid" required 
                                               placeholder="Enter student ID" autofocus>
                                        <small class="form-text text-muted">Enter the student's ID number</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label><i class="fa fa-calendar mr-2"></i> Academic Year</label>
                                        <select name="year" class="form-control" required>
                                            <option value="">Select Year</option>
                                            <?php 
                                            $current_year = date('Y');
                                            for ($i = $current_year; $i >= $current_year - 5; $i--) {
                                                echo "<option value='$i'>$i</option>";
                                            }
                                            ?>
                                        </select>
                                        <small class="form-text text-muted">Select the academic year</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label><i class="fa fa-calendar-check mr-2"></i> Semester</label>
                                        <select name="term" class="form-control" required>
                                            <option value="">Select Semester</option>
                                            <option value="1">Semester 1</option>
                                            <option value="2">Semester 2</option>
                                            <option value="3">Semester 3</option>
                                            <option value="4">Semester 4</option>
                                        </select>
                                        <small class="form-text text-muted">Select the semester</small>
                                    </div>
                                </div>
                                <div class="text-center mt-4">
                                    <button style="background: var(--primary) !important; color: white !important;" type="submit" name="search_student" class="btn btn-search  px-5 py-3">
                                        
                                        <i class="fa fa-search mr-2"></i> Find Student & Courses
                                    </button>
                                </div>
                            </form>
                            
                            <div class="alert alert-info alert-custom mt-4">
                                <div class="d-flex">
                                    <i class="fa fa-info-circle fa-2x mr-3"></i>
                                    <div>
                                        <h6 class="alert-heading">How This Works:</h6>
                                        <ol class="mb-0 pl-3">
                                            <li>Enter student ID, year, and semester</li>
                                            <li>System finds student and their program</li>
                                            <li>Shows available courses for that program/year/semester</li>
                                            <li>System checks <strong>results table only</strong> for existing registrations</li>
                                            <li>Select courses to register in results table only</li>
                                            <li>Courses are added with empty marks for later grading</li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    // Select all courses checkbox
    $('#selectAll').change(function() {
        $('.course-checkbox').prop('checked', $(this).prop('checked'));
        updateSelectedCount();
    });
    
    // Update selected count when checkboxes change
    $('.course-checkbox').change(function() {
        updateSelectedCount();
        
        // Uncheck select all if any checkbox is unchecked
        if (!$(this).prop('checked')) {
            $('#selectAll').prop('checked', false);
        }
        
        // Check if all are selected
        var allChecked = $('.course-checkbox').length === $('.course-checkbox:checked').length;
        $('#selectAll').prop('checked', allChecked);
    });
    
    // Update selected count
    function updateSelectedCount() {
        var selected = $('.course-checkbox:checked').length;
        $('#selectedCount').text(selected);
    }
    
    // Form validation
    $('#registerForm').submit(function(e) {
        var selectedCount = $('.course-checkbox:checked').length;
        
        if (selectedCount === 0) {
            e.preventDefault();
            alert('Please select at least one course to register.');
            return false;
        }
        
        var studentName = '<?php echo isset($student_info) ? addslashes($student_info["fullname"]) : ""; ?>';
        var confirmMsg = 'Are you sure you want to register ' + selectedCount + ' course(s) for this student?\n\n';
        confirmMsg += 'Student: ' + studentName + '\n';
        confirmMsg += 'Courses will be added to RESULTS TABLE ONLY with empty marks.\n\n';
        confirmMsg += 'This action cannot be undone.';
        
        if (!confirm(confirmMsg)) {
            e.preventDefault();
            return false;
        }
        
        return true;
    });
    
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        $('.alert').alert('close');
    }, 5000);
    
    // Initialize count
    updateSelectedCount();
});
</script>
</body>
</html>
<?php
if (isset($conn)) {
    mysqli_close($conn);
}
?>