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

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

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

// Handle delete request
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $delete_stmt = $conn->prepare("DELETE FROM results WHERE id = ?");
    $delete_stmt->bind_param("i", $delete_id);
    
    if ($delete_stmt->execute()) {
        $_SESSION['success'] = "Course deleted successfully";
    } else {
        $_SESSION['error'] = "Error deleting course";
    }
    
    $delete_stmt->close();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Handle bulk delete
if (isset($_POST['bulk_delete'])) {
    if (!empty($_POST['selected_courses'])) {
        $selected_courses = $_POST['selected_courses'];
        $placeholders = implode(',', array_fill(0, count($selected_courses), '?'));
        $types = str_repeat('i', count($selected_courses));
        
        $delete_stmt = $conn->prepare("DELETE FROM results WHERE id IN ($placeholders)");
        $delete_stmt->bind_param($types, ...$selected_courses);
        
        if ($delete_stmt->execute()) {
            $_SESSION['success'] = count($selected_courses) . " course(s) deleted successfully";
        } else {
            $_SESSION['error'] = "Error deleting selected courses";
        }
        
        $delete_stmt->close();
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    } else {
        $_SESSION['error'] = "No courses selected for deletion";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

// Handle decourse form submission
if (isset($_POST['decourse'])) {
    $studentid = mysqli_real_escape_string($conn, $_POST['studentid']);
    $semester = mysqli_real_escape_string($conn, $_POST['term']);
    $year = mysqli_real_escape_string($conn, $_POST['year']);
  
    // 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);
    }

    // Get courses for this student
    $query = "SELECT * FROM results 
              WHERE studentid = '$studentid' 
              AND year = '$year' 
              AND term = '$semester'";
    
    $courses_result = mysqli_query($conn, $query);
    $show_courses = true;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Course Deregistration</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);
            color: white;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(208, 63, 77, 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-deregister {
background: var(--primary) !important;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-deregister:hover {
            background: var(--primary) !important;
            color: white !important;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(208, 63, 77, 0.3);
        }
        .btn{
           background: var(--primary) !important;
            color: white !important;
            border: none !important;
            border-radius: 5px !important;
            transition: all 0.3s ease !important; 
        }
        .btn-danger-custom {
             background: var(--primary);
            color: white;
            border: none;
            border-radius: 5px;
            transition: all 0.3s ease;
        }
        .btn-danger-custom:hover {
            background: linear-gradient(135deg, #c82333 0%, #bd2130 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(220, 53, 69, 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(208, 63, 77, 0.05);
        }
        .total-marks {
            font-weight: bold;
            color: #d03f4d;
            font-size: 1.1rem;
        }
        .select-all-container {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #d03f4d;
        }
        .badge-custom {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 500;
        }
        .student-info-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }
        .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);
        }
        .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: #d03f4d;
            box-shadow: 0 0 0 0.2rem rgba(208, 63, 77, 0.25);
        }
        .custom-checkbox .custom-control-input:checked~.custom-control-label::before {
            background-color: #d03f4d;
            border-color: #d03f4d;
        }
    </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> Course Deregistration </h2>
                <p class="mb-0">Manage and deregister student courses for selected semesters</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 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($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'] ?? 'N/A'); ?></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">Year/Semester</small>
                                                <strong><?php echo htmlspecialchars($year); ?> - Semester <?php echo htmlspecialchars($semester); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <?php if ($student_info): ?>
                                    <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'] ?? 'N/A'); ?></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'] ?? 'N/A'); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-4 text-center">
                                <div class="bg-light p-3 rounded">
                                    <h2 class="text-danger mb-0"><?php echo $courses_result ? mysqli_num_rows($courses_result) : 0; ?></h2>
                                    <small class="text-muted">Total Courses</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Courses List with Delete Options -->
                <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> Registered Courses</h5>
                            <small class="text-white">Semester <?php echo htmlspecialchars($semester); ?>, <?php echo htmlspecialchars($year); ?></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 ($courses_result && mysqli_num_rows($courses_result) > 0): ?>
                            <form method="POST" action="" id="coursesForm">
                                <!-- 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 Courses
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-right">
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-sm btn-danger-custom" data-toggle="modal" data-target="#bulkDeleteModal">
                                                    <i class="fa fa-trash mr-1"></i> Delete Selected
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Courses Table -->
                                <div class="table-responsive">
                                    <table class="table table-hover course-table">
                                        <thead>
                                            <tr>
                                                <th width="40">#</th>
                                                <th width="60">Select</th>
                                                <th>Course</th>
                                              
                                                <th>Grade</th>
                                                <th>Status</th>
                                                <th width="120">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $counter = 1;
                                            mysqli_data_seek($courses_result, 0);
                                            while($course = mysqli_fetch_assoc($courses_result)): 
                                                // Calculate total marks
                                                $ca = floatval($course['ca'] ?? 0);
                                                $ca1 = floatval($course['ca1'] ?? 0);
                                                $ca2 = floatval($course['ca2'] ?? 0);
                                                $exam = floatval($course['exam'] ?? 0);
                                                $total_marks = $ca + $ca1 + $ca2 + $exam;
                                                
                                                // Determine status and grade
                                                if ($total_marks > 0) {
                                                    $status = 'Graded';
                                                    $status_badge = 'badge-success';
                                                    // Grade calculation
                                                    if ($total_marks >= 70) $grade = 'A';
                                                    elseif ($total_marks >= 60) $grade = 'B';
                                                    elseif ($total_marks >= 50) $grade = 'C';
                                                    elseif ($total_marks >= 40) $grade = 'D';
                                                    else $grade = 'F';
                                                    $grade_badge = ($grade == 'F') ? 'badge-danger' : 'badge-success';
                                                } else {
                                                    $status = 'Registered';
                                                    $status_badge = 'badge-primary';
                                                    $grade = '-';
                                                    $grade_badge = 'badge-secondary';
                                                }
                                            ?>
                                                <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 htmlspecialchars($course['course']); ?></div>
                                                        <?php if (!empty($course['intake'])): ?>
                                                            <small class="text-muted">Intake: <?php echo htmlspecialchars($course['intake']); ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                 
                                                    <td>
                                                        <span class="badge badge-custom <?php echo $grade_badge; ?>">
                                                            <?php echo $grade; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-custom <?php echo $status_badge; ?>">
                                                            <?php echo $status; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="action-buttons">
                                                            <a href="?delete_id=<?php echo $course['id']; ?>&studentid=<?php echo $studentid; ?>&term=<?php echo $semester; ?>&year=<?php echo $year; ?>&decourse=1" 
                                                               class="btn btn-sm btn-danger-custom action-btn"
                                                               onclick="return confirm('Are you sure you want to delete this course?\n\nCourse: <?php echo addslashes($course['course']); ?>')"
                                                               data-toggle="tooltip" title="Delete Course" class="background:red !important; color:white !important;">
                                                                <i style="font-size:25px" class="fa fa-trash"></i>
                                                            </a>
                                                        </div>
                                                    </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-info badge-custom">0</span>
                                            <span class="ml-2">course(s) selected</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="button" class="btn btn-danger-custom" data-toggle="modal" data-target="#bulkDeleteModal">
                                                <i class="fa fa-trash mr-1"></i> Delete Selected
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        <?php else: ?>
                            <div class="no-courses text-center">
                                <i class="fa fa-book fa-4x text-muted mb-4"></i>
                                <h4>No Courses Found</h4>
                                <p class="text-muted mb-4">
                                    Student <strong><?php echo htmlspecialchars($studentid); ?></strong> has no registered courses for 
                                    Year <?php echo htmlspecialchars($year); ?>, Semester <?php echo htmlspecialchars($semester); ?>
                                </p>
                                <div class="mt-3">
                                    <button onclick="window.location.href='<?php echo $_SERVER['PHP_SELF']; ?>'" class="btn btn-deregister">
                                        <i class="fa fa-search mr-1"></i> Search Again
                                    </button>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($courses_result) mysqli_free_result($courses_result); ?>
                
            <?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 Courses</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>
                                    </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>
                                    </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>
                                    </div>
                                </div>
                                <div class="text-center mt-4">
                                    <button type="submit" name="decourse" class="btn btn-deregister px-5 py-3">
                                        <i class="fa fa-search mr-2"></i> Find 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 to use this system:</h6>
                                        <ol class="mb-0 pl-3">
                                            <li>Enter the student ID</li>
                                            <li>Select the academic year and semester</li>
                                            <li>View all registered courses</li>
                                            <li>Select individual courses or use "Select All"</li>
                                            <li>Delete selected courses using the delete button</li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Bulk Delete Modal -->
<div class="modal fade" id="bulkDeleteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fa fa-exclamation-triangle mr-2"></i> Confirm Bulk Delete</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete <span id="deleteCount" class="font-weight-bold text-danger">0</span> selected course(s)?</p>
                <p class="text-muted"><small>This action cannot be undone. All selected courses will be permanently removed from the system.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn " data-dismiss="modal">Cancel</button>
                <button type="submit" name="bulk_delete" form="coursesForm" class="btn">
                    <i class="fa fa-trash mr-1"></i> Delete Selected Courses
                </button>
            </div>
        </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() {
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
    
    // 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);
        $('#deleteCount').text(selected);
        
        // Disable delete button if none selected
        $('[name="bulk_delete"]').prop('disabled', selected === 0);
    }
    
    // Bulk delete modal handler
    $('#bulkDeleteModal').on('show.bs.modal', function() {
        var selected = $('.course-checkbox:checked').length;
        if (selected === 0) {
            return false;
        }
    });
    
    // 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);
}
?>