<?php
session_start();
ob_start(); // Start output buffering

include "../include/config.php";
$userlogin = isset($_SESSION['email']) ? $_SESSION['email'] : '';
$email = $userlogin;
$intake = isset($_SESSION['department']) ? $_SESSION['department'] : '';

// --- Server-side: handle update submission on the same page ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['updateCourse'])) {
    // Basic validation / sanitization
    $id = isset($_POST['course_id']) ? intval($_POST['course_id']) : 0;
    $courseName = isset($_POST['courseName']) ? trim($_POST['courseName']) : '';
    $semester = isset($_POST['semester']) ? trim($_POST['semester']) : '';
    $year = isset($_POST['year']) ? trim($_POST['year']) : '';
    // programs may be an array
    $programs_array = isset($_POST['programs']) ? (array)$_POST['programs'] : [];
    $programs_str = implode(',', $programs_array);

    if ($id <= 0 || $courseName === '' || $semester === '' || $year === '') {
        header("Location: ".$_SERVER['PHP_SELF']."?error=" . urlencode("Missing required fields for update."));
        exit;
    }

    // Use prepared statement to update
    $stmt = $conn->prepare("UPDATE course SET course = ?, semester = ?, year = ?, program = ? WHERE id = ?");
    if (!$stmt) {
        header("Location: ".$_SERVER['PHP_SELF']."?error=" . urlencode("Prepare failed: " . $conn->error));
        exit;
    }
    $stmt->bind_param("ssssi", $courseName, $semester, $year, $programs_str, $id);
    if ($stmt->execute()) {
        $stmt->close();
        header("Location: ".$_SERVER['PHP_SELF']."?success=" . urlencode("Course updated successfully."));
        exit;
    } else {
        $err = $stmt->error;
        $stmt->close();
        header("Location: ".$_SERVER['PHP_SELF']."?error=" . urlencode("Update failed: " . $err));
        exit;
    }
}

// --- Server-side: handle delete via GET (you may prefer POST) ---
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    if ($delete_id > 0) {
        $stmt = $conn->prepare("DELETE FROM course WHERE id = ?");
        $stmt->bind_param("i", $delete_id);
        if ($stmt->execute()) {
            $stmt->close();
            header("Location: ".$_SERVER['PHP_SELF']."?success=" . urlencode("Course deleted."));
            exit;
        } else {
            $err = $stmt->error;
            $stmt->close();
            header("Location: ".$_SERVER['PHP_SELF']."?error=" . urlencode("Delete failed: " . $err));
            exit;
        }
    }
}

if (isset($_SESSION['email'])) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Course Management</title>
    <!-- keep your includes -->
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="var(--primary)">
    <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

    <style>
        /* your existing styles (kept minimal here for brevity) */
        body { padding:0; margin:0; font-size:16px; background:white; }
        .content { margin-left:200px; padding:15px; }
        .program-checkboxes { max-height:200px; overflow-y:auto; border:1px solid #ddd; padding:10px; border-radius:5px; margin-top:10px; }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content" style="padding:20px">
    <!-- Success/Error Messages -->
    <?php if (isset($_GET['error'])) { ?>
        <div class="alert alert-danger" style="text-align:center;">
            <p><i class="fa fa-exclamation-circle"></i> <?php echo htmlspecialchars($_GET['error']); ?></p>
        </div>
    <?php } ?>
    <?php if (isset($_GET['success'])) { ?>
        <div class="alert alert-success" style="text-align:center;">
            <p><i class="fa fa-check"></i> <?php echo htmlspecialchars($_GET['success']); ?></p>
        </div>
    <?php } ?>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4>Course Management</h4>
        <button style="background: var(--secondary); color: white;" class="btn" data-toggle="modal" data-target="#addCourseModal">
            <i  class="fa fa-plus"></i> New Course
        </button>
 
    </div>

    <!-- CSV Upload Section (unchanged) -->
    <div class="card mb-4">
        <div class="card-header  text-white" style="background:var(--primary);">
            <h5 class="mb-0">Bulk Upload Courses via CSV</h5>
        </div>
        <div class="card-body">
            <div class="csv-download">
                <a href="generate_csv_template.php" class="btn btn-outline-success btn-sm">
                    <i class="fa fa-download"></i> Download CSV Template
                </a>
                <p class="csv-template">CSV format: course, semester, program (one per line)</p>
            </div>

            <form method="POST" enctype="multipart/form-data" action="upload_courses.php">
                <div class="form-group">
                    <label for="csvFile">Select CSV File</label>
                    <input type="file" class="form-control-file" id="csvFile" name="csvFile" accept=".csv" required>
                </div>
                <button type="submit" name="uploadCsv" class="btn" style="background:var(--primary);">
                    <i class="fa fa-upload"></i> Upload CSV
                </button>
            </form>
        </div>
    </div>

    <!-- Courses Table -->
    <div class="card">
        <div class="card-header bg-secondary text-white">
            <h5 class="mb-0">Existing Courses</h5>
        </div>
        <div class="card-body">
            <div class="mb-3">
                <input type="text" id="courseSearch" class="form-control" placeholder="Search courses...">
            </div>

            <div style="overflow:auto; max-height:500px;">
                <table class="table table-bordered table-hover align-middle" id="coursesTable">
                    <thead class="thead-light">
                        <tr>
                            <th>ID</th>
                            <th>Course</th>
                            <th>Semester</th>
                            <th>Year</th>
                            <th>Program(s)</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // fetch courses normally (don't GROUP BY id)
                        $sql = "SELECT id, course, semester, year, program FROM course ORDER BY id DESC";
                        $result = $conn->query($sql);

                        if ($result && $result->num_rows > 0) {
                            while($row = $result->fetch_assoc()) {
                                // prepare a safe data-programs attribute (escape quotes)
                                $programsEsc = htmlspecialchars($row['program'], ENT_QUOTES);
                                // make button with data attributes so JS can fill modal
                                echo "<tr>
                                    <td>{$row['id']}</td>
                                    <td>".htmlspecialchars($row['course'])."</td>
                                    <td>".htmlspecialchars($row['semester'])."</td>
                                    <td>".htmlspecialchars($row['year'])."</td>
                                    <td>".htmlspecialchars($row['program'])."</td>
                                    <td>
                                        <button class='btn btn-sm btn-info edit-btn' 
                                            data-id='".htmlspecialchars($row['id'], ENT_QUOTES)."' 
                                            data-course='".htmlspecialchars($row['course'], ENT_QUOTES)."' 
                                            data-semester='".htmlspecialchars($row['semester'], ENT_QUOTES)."' 
                                            data-year='".htmlspecialchars($row['year'], ENT_QUOTES)."' 
                                            data-programs='". $programsEsc ."'>
                                            <i class='fa fa-edit'></i> Edit
                                        </button>
                                        <a href='?delete_id={$row['id']}' class='btn btn-sm btn-danger' 
                                           onclick='return confirm(\"Are you sure you want to delete this course?\");'>
                                            <i class='fa fa-trash'></i> Delete
                                        </a>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr>
                                <td colspan='6' class='text-center text-muted'>No courses found</td>
                            </tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Course Modal (unchanged from your original) -->
<div class="modal fade" id="addCourseModal" tabindex="-1" role="dialog" aria-labelledby="addCourseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Course</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <form method="POST" action="add_course.php">
                    <div class="form-group">
                        <label for="courseNameAdd">Course Name</label>
                        <input type="text" class="form-control" id="courseNameAdd" name="courseName" required>
                    </div>
                    <div class="form-group">
                        <label for="semesterAdd">Semester</label>
                        <select class="form-control" id="semesterAdd" name="semester" required>
                            <option value="">-- Select Semester --</option>
                            <option value="1">Semester 1</option>
                            <option value="2">Semester 2</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="yearAdd">Year</label>
                        <select class="form-control" id="yearAdd" name="year" required>
                            <option value="">-- Select year --</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="programsAdd">Program(s)</label>
                        <div class="select-all">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="selectAllProgramsAdd">
                                <label class="form-check-label" for="selectAllProgramsAdd">Select All Programs</label>
                            </div>
                        </div>
                        <div class="program-checkboxes" id="programCheckboxesAdd">
                            <?php
                            $programs = $conn->query("SELECT id, program FROM programs ORDER BY program");
                            if ($programs && $programs->num_rows > 0) {
                                while($program = $programs->fetch_assoc()) {
                                    echo "<div class='program-item form-check'>
                                        <input class='form-check-input program-checkbox-add' type='checkbox' 
                                               name='programs[]' value='".htmlspecialchars($program['program'], ENT_QUOTES)."' id='program_add_{$program['id']}'>
                                        <label class='form-check-label' for='program_add_{$program['id']}'>
                                            ".htmlspecialchars($program['program'])."
                                        </label>
                                    </div>";
                                }
                            } else {
                                echo '<p class="text-muted">No programs found. Please add programs first.</p>';
                            }
                            ?>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" name="addCourse" class="btn btn-primary">Add Course</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- EDIT COURSE Modal (fills with JS) -->
<div class="modal fade" id="editCourseModal" tabindex="-1" role="dialog" aria-labelledby="editCourseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <form method="POST" id="editCourseForm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                <input type="hidden" name="course_id" id="edit_course_id">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Course</h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                        <div class="form-group">
                            <label for="editCourseName">Course Name</label>
                            <input type="text" class="form-control" id="editCourseName" name="courseName" required>
                        </div>
                        <div class="form-group">
                            <label for="editSemester">Semester</label>
                            <select class="form-control" id="editSemester" name="semester" required>
                                <option value="">-- Select Semester --</option>
                                <option value="1">Semester 1</option>
                                <option value="2">Semester 2</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editYear">Year</label>
                            <select class="form-control" id="editYear" name="year" required>
                                <option value="">-- Select year --</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="editPrograms">Program(s)</label>
                            <div class="select-all">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="selectAllProgramsEdit">
                                    <label class="form-check-label" for="selectAllProgramsEdit">Select All Programs</label>
                                </div>
                            </div>
                            <div class="program-checkboxes" id="programCheckboxesEdit">
                                <?php
                                // reuse programs list for edit modal
                                $programs2 = $conn->query("SELECT id, program FROM programs ORDER BY program");
                                if ($programs2 && $programs2->num_rows > 0) {
                                    while($program = $programs2->fetch_assoc()) {
                                        echo "<div class='program-item form-check'>
                                            <input class='form-check-input program-checkbox-edit' type='checkbox' 
                                                   name='programs[]' value='".htmlspecialchars($program['program'], ENT_QUOTES)."' id='program_edit_{$program['id']}'>
                                            <label class='form-check-label' for='program_edit_{$program['id']}'>
                                                ".htmlspecialchars($program['program'])."
                                            </label>
                                        </div>";
                                    }
                                } else {
                                    echo '<p class="text-muted">No programs found. Please add programs first.</p>';
                                }
                                ?>
                            </div>
                        </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="updateCourse" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Live search for courses
document.getElementById('courseSearch').addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();
    let rows = document.querySelectorAll('#coursesTable tbody tr');
    rows.forEach(row => {
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(filter) ? '' : 'none';
    });
});

// Add: select all for Add modal
document.getElementById('selectAllProgramsAdd')?.addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.program-checkbox-add');
    checkboxes.forEach(cb => cb.checked = this.checked);
});

// Add: select all for Edit modal
document.getElementById('selectAllProgramsEdit')?.addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.program-checkbox-edit');
    checkboxes.forEach(cb => cb.checked = this.checked);
});

// When you click an Edit button in the table, fill the edit modal and show it
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const course = this.getAttribute('data-course') || '';
        const semester = this.getAttribute('data-semester') || '';
        const year = this.getAttribute('data-year') || '';
        const programs = this.getAttribute('data-programs') || ''; // comma-separated

        // fill fields
        document.getElementById('edit_course_id').value = id;
        document.getElementById('editCourseName').value = course;
        document.getElementById('editSemester').value = semester;
        document.getElementById('editYear').value = year;

        // clear all edit program checkboxes then check those that match
        const editCheckboxes = document.querySelectorAll('.program-checkbox-edit');
        editCheckboxes.forEach(cb => cb.checked = false);

        if (programs.trim() !== '') {
            // programs stored as CSV in DB: split by comma
            const arr = programs.split(',').map(s => s.trim()).filter(Boolean);
            editCheckboxes.forEach(cb => {
                if (arr.includes(cb.value)) cb.checked = true;
            });
        }

        // set selectAll checkbox state for edit modal
        const allChecked = Array.from(editCheckboxes).every(cb => cb.checked);
        const noneChecked = Array.from(editCheckboxes).every(cb => !cb.checked);
        const selectAllEdit = document.getElementById('selectAllProgramsEdit');
        if (selectAllEdit) {
            selectAllEdit.checked = allChecked;
            selectAllEdit.indeterminate = !allChecked && !noneChecked;
        }

        // show modal
        $('#editCourseModal').modal('show');
    });
});

// Keep Add modal 'select all' indeterminate logic (optional)
const programCheckboxesAdd = document.querySelectorAll('.program-checkbox-add');
programCheckboxesAdd.forEach(cb => {
    cb.addEventListener('change', function() {
        const all = Array.from(programCheckboxesAdd).every(x => x.checked);
        const none = Array.from(programCheckboxesAdd).every(x => !x.checked);
        const selectAll = document.getElementById('selectAllProgramsAdd');
        if (selectAll) {
            selectAll.checked = all;
            selectAll.indeterminate = !all && !none;
        }
    });
});

// Keep Edit modal individual checkboxes logic
const programCheckboxesEdit = document.querySelectorAll('.program-checkbox-edit');
programCheckboxesEdit.forEach(cb => {
    cb.addEventListener('change', function() {
        const all = Array.from(programCheckboxesEdit).every(x => x.checked);
        const none = Array.from(programCheckboxesEdit).every(x => !x.checked);
        const selectAll = document.getElementById('selectAllProgramsEdit');
        if (selectAll) {
            selectAll.checked = all;
            selectAll.indeterminate = !all && !none;
        }
    });
});
</script>

</body>
</html>
<?php
} else {
    header("location:../index.php");
    exit;
}
?>


<!-- Modal -->
<div class="modal fade" id="exampleModal1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">De-Register course</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
<form action="deregister.php" method="POST">
    <input class="form-control" type="text" name="studentid" placeholder="STD">
<select name="year" class="form-control">
    <option value="term">Select year</option>
    <?php
    $select=mysqli_query($conn,'select *from year');
    while ($row=mysqli_fetch_array($select)) {?>
        // code...
    
    <option value="<?php echo $row['year'];?>"><?php echo $row['year'];?></option>
    <?php
}
?>

</select>
<select name="term" class="form-control">
    <option value="term">Select Semester</option>
    <option value="1">1</option>
        <option value="2">2</option>

</select>

      </div>
      <div class="modal-footer">
        <button type="submit" name="decourse" type="button" class="btn" style="background:var(--primary); color:white;">Filter now</button>
      </div>
      </form>
    </div>
  </div>
</div>