<?php
include('../includes/db.php');
require_once __DIR__ . '/../includes/auth.php';
ec_require_login();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Courses Management</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">

<style>
:root{
  --bg: #f4f6fb;
  --card: #ffffff;
  --line: #e7ebf3;
  --text: #162033;
  --muted: #6c7891;
  --primary: #2f6fed;
  --primary-dark: #1f56c8;
  --success: #1fa463;
  --success-dark: #188552;
  --warning: #f4b400;
  --danger: #e7515a;
  --shadow-sm: 0 6px 18px rgba(15, 23, 42, 0.05);
  --shadow-md: 0 18px 50px rgba(15, 23, 42, 0.14);
  --radius-xl: 18px;
  --radius-lg: 16px;
  --radius-md: 12px;
  --radius-sm: 10px;
}

body{
  background: var(--bg);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  color: var(--text);
}

.ec-main{
  min-height: 100vh;
}

.rms-content{
  padding: 24px 14px 30px;
}

.page-shell{
  max-width: 100%;
}

.section-card{
  background: var(--card);
  border: 1px solid var(--line);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-sm);
}

.hero-card{
  padding: 20px 22px;
  margin-bottom: 16px;
}

.hero-title{
  margin: 0;
  font-size: 2rem;
  font-weight: 700;
  letter-spacing: -0.02em;
  color: #152238;
}

.hero-subtitle{
  margin: 6px 0 0;
  color: var(--muted);
  font-size: .94rem;
}

.page-actions{
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.filters-card{
  padding: 14px;
  margin-bottom: 16px;
}

.filter-input{
  min-height: 44px;
  border-radius: 12px;
  border: 1px solid #d7dfeb;
  background: #fff;
  font-size: .95rem;
}

.filter-input:focus,
.form-control:focus,
.form-select:focus{
  border-color: #9bb9ff;
  box-shadow: 0 0 0 .18rem rgba(47,111,237,.10);
}

.table-card{
  padding: 14px;
}

.course-table{
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 10px;
  margin-bottom: 0;
}

.course-table thead th{
  border: 0 !important;
  background: transparent !important;
  color: #74819a;
  font-size: .76rem;
  text-transform: uppercase;
  letter-spacing: .06em;
  font-weight: 700;
  padding: 0 12px 6px;
  white-space: nowrap;
}

.course-table tbody tr{
  background: #fff;
  box-shadow: 0 5px 16px rgba(15, 23, 42, 0.05);
  transition: all .18s ease;
}

.course-table tbody tr:hover{
  transform: translateY(-1px);
  box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
}

.course-table tbody td{
  border: 0 !important;
  padding: 14px 12px;
  vertical-align: middle;
}

.course-table tbody td:first-child{
  border-top-left-radius: 14px;
  border-bottom-left-radius: 14px;
}

.course-table tbody td:last-child{
  border-top-right-radius: 14px;
  border-bottom-right-radius: 14px;
  white-space: nowrap;
}

.status-badge{
  display: inline-flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 999px;
  font-size: .76rem;
  font-weight: 700;
}

.status-active{
  background: #dff7e7;
  color: #199756;
}

.status-inactive{
  background: #fde7e7;
  color: #d44957;
}

.code-text{
  font-weight: 600;
  color: #334155;
}

.pointer{
  cursor: pointer;
}

.pointer:hover .course-name{
  color: var(--primary);
}

.course-cell{
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 260px;
}

.course-img{
  width: 42px;
  height: 42px;
  object-fit: cover;
  border-radius: 12px;
  border: 1px solid #e5ebf4;
  background: #f8faff;
  flex-shrink: 0;
}

.course-name{
  font-weight: 600;
  color: #2563eb;
  line-height: 1.35;
  transition: color .18s ease;
}

.btn{
  border-radius: 12px;
  font-weight: 600;
  box-shadow: none !important;
}

.btn:hover{
  transform: translateY(-1px);
}

.btn-primary{
  background: linear-gradient(135deg, var(--primary), var(--primary-dark));
  border: none;
}

.btn-primary:hover{
  background: linear-gradient(135deg, var(--primary), var(--primary-dark));
}

.btn-success{
  background: linear-gradient(135deg, var(--success), var(--success-dark));
  border: none;
}

.btn-success:hover{
  background: linear-gradient(135deg, var(--success), var(--success-dark));
}

.btn-warning{
  background: #f6c23e;
  border: none;
  color: #3a2c00;
}

.btn-warning:hover{
  background: #efb319;
  color: #3a2c00;
}

.btn-danger{
  background: #e74a5b;
  border: none;
}

.btn-danger:hover{
  background: #dc3545;
}

.btn-outline-secondary{
  background: #fff;
  border-color: #cfd7e3;
  color: #5b6880;
}

.btn-outline-secondary:hover{
  background: #f8faff;
  border-color: #c7d0dd;
  color: #334155;
}

.action-btn{
  width: 34px;
  height: 34px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
}

.action-btn i{
  font-size: .92rem;
}

.modal{
  z-index: 1080;
}

.modal-backdrop{
  z-index: 1070;
  background: rgba(15, 23, 42, .48);
}

.modal.show .modal-dialog{
  margin-top: 1.2rem;
  margin-bottom: 1.2rem;
}

.modal-dialog.modal-lg{
  max-width: 860px;
}

.modal-content{
  border: 0;
  border-radius: 22px;
  overflow: hidden;
  box-shadow: var(--shadow-md);
  background: #fff;
}

.modal-header{
  border-bottom: 1px solid var(--line);
  background: linear-gradient(180deg, #ffffff 0%, #f9fbff 100%);
  padding: 16px 22px;
}

.modal-title{
  font-size: 1.14rem;
  font-weight: 700;
  color: #16233c;
  display: flex;
  align-items: center;
  gap: 8px;
}

.modal-title i{
  color: var(--primary);
}

.modal-body{
  padding: 22px !important;
  background: #fcfdff;
}

.modal-footer{
  border-top: 1px solid var(--line);
  background: #fff;
  padding: 14px 22px 18px;
}

.modal-dialog-scrollable .modal-body{
  max-height: calc(100vh - 220px);
}

.btn-close{
  opacity: .7;
}

.btn-close:hover{
  opacity: 1;
}

.form-label{
  font-size: .86rem;
  font-weight: 600;
  color: #344055;
  margin-bottom: 7px;
}

.form-control,
.form-select{
  min-height: 46px;
  border-radius: 12px;
  border: 1px solid #d7dfeb;
  background: #fff;
  color: #24324a;
  font-size: .95rem;
}

textarea.form-control{
  min-height: auto;
}

.modal-section{
  background: #fff;
  border: 1px solid #ebeff6;
  border-radius: 16px;
  padding: 16px;
}

.modal-section-title{
  font-size: .82rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: .05em;
  color: #7a869d;
  margin-bottom: 12px;
}

.module-box{
  background: #fff;
  border: 1px solid #e4eaf4;
  border-radius: 14px;
  padding: 10px;
}

.module-box .form-control{
  border: 0;
  box-shadow: none !important;
  min-height: 42px;
  background: transparent;
}

.module-remove{
  width: 38px;
  height: 38px;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.module-add-btn{
  border-radius: 10px;
  font-weight: 600;
}

#current_image{
  width: 72px;
  height: 72px;
  border-radius: 16px;
  object-fit: cover;
  border: 1px solid #e4eaf4;
  background: #f7faff;
}

.text-muted{
  color: #7b8797 !important;
}

#courseDetailContent{
  color: #24324a;
}

@media (max-width: 991.98px){
  .rms-content{
    padding: 18px 10px 24px;
  }

  .hero-title{
    font-size: 1.65rem;
  }

  .page-actions{
    width: 100%;
  }

  .page-actions .btn{
    flex: 1 1 auto;
  }

  .modal.show .modal-dialog{
    margin: .75rem;
  }

  .modal-dialog.modal-lg{
    max-width: none;
  }

  .modal-dialog-scrollable .modal-body{
    max-height: calc(100vh - 170px);
  }
}
</style>
</head>
<body>
<?php
$ACTIVE = 'courses';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<main class="ec-main">
  <div class="rms-content">
    <div class="container-fluid page-shell">

      <div class="section-card hero-card">
        <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
          <div>
            <h1 class="hero-title">Course Management</h1>
            <p class="hero-subtitle">Manage course records, search quickly, and update course details with a cleaner modern layout.</p>
          </div>
          <div class="page-actions">
            
            <button class="btn btn-primary px-3" data-bs-toggle="modal" data-bs-target="#addCourseModal">
              <i class="bi bi-plus-circle me-1"></i> Manage
            </button>
          </div>
        </div>
      </div>

      <div class="section-card filters-card">
        <div class="row g-3">
          <div class="col-md-4">
            <input type="text" id="searchStatus" class="form-control filter-input" placeholder="Search by Status">
          </div>
          <div class="col-md-4">
            <input type="text" id="searchCode" class="form-control filter-input" placeholder="Search by Code">
          </div>
          <div class="col-md-4">
            <input type="text" id="searchName" class="form-control filter-input" placeholder="Search by Course Name">
          </div>
        </div>
      </div>

      <div class="section-card table-card">
        <div class="table-responsive">
          <table class="course-table align-middle">
            <thead>
              <tr>
                <th>Status</th>
                <th>Code</th>
                <th>Course</th>
                <th style="width:130px;">Actions</th>
              </tr>
            </thead>
            <tbody id="courseTable">
              <?php
              $res = mysqli_query($conn, "SELECT id, status, code, course_name, image FROM courses ORDER BY id DESC");
              while ($row = mysqli_fetch_assoc($res)):
              ?>
              <tr data-id="<?= (int)$row['id'] ?>">
                <td>
                  <span class="status-badge <?= $row['status']=='Active' ? 'status-active' : 'status-inactive' ?>">
                    <?= htmlspecialchars($row['status']) ?>
                  </span>
                </td>

                <td class="code-text"><?= htmlspecialchars($row['code']) ?></td>

                <td class="pointer" onclick="viewCourseDetails('<?= (int)$row['id'] ?>')">
                  <div class="course-cell">
                    <?php if (!empty($row['image'])): ?>
                      <img src="../uploads/courses/<?= htmlspecialchars($row['image']) ?>" class="course-img" alt="">
                    <?php else: ?>
                      <img src="../assets/no-image.png" class="course-img" alt="">
                    <?php endif; ?>
                    <div class="course-name"><?= htmlspecialchars($row['course_name']) ?></div>
                  </div>
                </td>

                <td>
                  <div class="d-flex gap-2 justify-content-start">
                    <button class="btn btn-sm btn-warning action-btn editCourseBtn" data-id="<?= (int)$row['id'] ?>" title="Edit">
                      <i class="bi bi-pencil"></i>
                    </button>

                    <button class="btn btn-sm btn-danger action-btn" onclick="deleteCourse('<?= (int)$row['id'] ?>')" title="Delete">
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      </div>

    </div>
  </div>
</main>

<!-- Add Course Modal -->
<div class="modal fade" id="addCourseModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
    <form id="addCourseForm" class="modal-content" enctype="multipart/form-data">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-journal-plus"></i> Add New Course</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <div class="modal-section mb-3">
          <div class="modal-section-title">Basic Information</div>
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Status</label>
              <select class="form-select" name="status" required>
                <option value="">-- Select --</option>
                <option value="Active">Active</option>
                <option value="Inactive">Inactive</option>
              </select>
            </div>

            <div class="col-md-6">
              <label class="form-label">Course Type</label>
              <select class="form-select" id="add_course_type" name="type" required>
                <option value="single">Single Course</option>
                <option value="bundle">Bundle</option>
              </select>
            </div>

            <div class="col-md-6">
              <label class="form-label">Course Code</label>
              <input type="text" name="code" class="form-control" required>
            </div>

            <div class="col-md-6">
              <label class="form-label">Duration (Months)</label>
              <input type="number" name="duration" class="form-control" required>
            </div>

            <div class="col-12">
              <label class="form-label">Course Name</label>
              <input type="text" name="course_name" class="form-control" required>
            </div>
          </div>
        </div>

        <div class="modal-section mb-3" id="add_modules_input">
          <div class="modal-section-title">Modules</div>
          <div id="addModulesList" class="vstack gap-2"></div>
          <button type="button" id="btnAddModuleAdd" class="btn btn-sm btn-outline-primary module-add-btn mt-2">
            <i class="bi bi-plus-lg me-1"></i> Add module
          </button>
        </div>

        <div class="modal-section mb-3 d-none" id="add_bundle_input">
          <div class="modal-section-title">Bundle Courses</div>
          <label class="form-label">Select Courses for Bundle</label>
          <select name="bundle_courses[]" class="form-select" multiple>
            <?php
            $crs = mysqli_query($conn, "SELECT id, course_name FROM courses ORDER BY course_name");
            while ($c = mysqli_fetch_assoc($crs)) {
                echo "<option value='{$c['id']}'>".htmlspecialchars($c['course_name'])."</option>";
            }
            ?>
          </select>
          <small class="text-muted">Hold CTRL/⌘ to select multiple courses.</small>
        </div>

        <div class="modal-section">
          <div class="modal-section-title">Descriptions & Image</div>
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Short Description</label>
              <textarea name="description" class="form-control" rows="2"></textarea>
            </div>

            <div class="col-12">
              <label class="form-label">Full Course Description</label>
              <textarea name="course_description" class="form-control" rows="4"></textarea>
            </div>

            <div class="col-12">
              <label class="form-label">Course Image</label>
              <input type="file" name="image" class="form-control" accept="image/*">
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary px-3" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-success px-3">
          <i class="bi bi-check2-circle me-1"></i> Save Course
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Course Modal -->
<div class="modal fade" id="editCourseModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
    <form id="editCourseForm" class="modal-content" enctype="multipart/form-data">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-pencil-square"></i> Edit Course</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <input type="hidden" name="id" id="edit_id">

        <div class="modal-section mb-3">
          <div class="modal-section-title">Basic Information</div>
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Status</label>
              <select class="form-select" id="edit_status" name="status" required>
                <option value="Active">Active</option>
                <option value="Inactive">Inactive</option>
              </select>
            </div>

            <div class="col-md-6">
              <label class="form-label">Course Type</label>
              <select class="form-select" id="edit_course_type" name="type">
                <option value="single">Single Course</option>
                <option value="bundle">Bundle</option>
              </select>
            </div>

            <div class="col-md-6">
              <label class="form-label">Course Code</label>
              <input type="text" id="edit_code" name="code" class="form-control" required>
            </div>

            <div class="col-md-6">
              <label class="form-label">Duration (Months)</label>
              <input type="number" id="edit_duration" name="duration" class="form-control">
            </div>

            <div class="col-12">
              <label class="form-label">Course Name</label>
              <input type="text" id="edit_course_name" name="course_name" class="form-control" required>
            </div>
          </div>
        </div>

        <div class="modal-section mb-3" id="edit_modules_input">
          <div class="modal-section-title">Modules</div>
          <div id="editModulesList" class="vstack gap-2"></div>
          <button type="button" id="btnAddModuleEdit" class="btn btn-sm btn-outline-primary module-add-btn mt-2">
            <i class="bi bi-plus-lg me-1"></i> Add module
          </button>
        </div>

        <div class="modal-section mb-3 d-none" id="edit_bundle_input">
          <div class="modal-section-title">Bundle Courses</div>
          <label class="form-label">Select Courses for Bundle</label>
          <select id="edit_bundle_select" name="bundle_courses[]" class="form-select" multiple>
            <?php
            $crs = mysqli_query($conn, "SELECT id, course_name FROM courses ORDER BY course_name");
            while ($c = mysqli_fetch_assoc($crs)) {
                echo "<option value='{$c['id']}'>".htmlspecialchars($c['course_name'])."</option>";
            }
            ?>
          </select>
          <small class="text-muted">Hold CTRL/⌘ to select multiple courses.</small>
        </div>

        <div class="modal-section">
          <div class="modal-section-title">Descriptions & Image</div>
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Short Description</label>
              <textarea id="edit_description" name="description" class="form-control" rows="2"></textarea>
            </div>

            <div class="col-12">
              <label class="form-label">Full Course Description</label>
              <textarea id="edit_course_description" name="course_description" class="form-control" rows="4"></textarea>
            </div>

            <div class="col-12">
              <label class="form-label">Course Image</label>
              <input type="file" name="image" class="form-control" accept="image/*">
              <div class="mt-2">
                <img id="current_image" src="../assets/no-image.png" class="course-img">
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary px-3" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-success px-3">
          <i class="bi bi-check2-circle me-1"></i> Update Course
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Course Details Modal -->
<div class="modal fade" id="courseDetailsModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content border-0 shadow">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-info-circle"></i> Course Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="courseDetailContent">Loading...</div>
      </div>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ===== Utilities =====
function uid(){ return (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : ('id_'+Math.random().toString(36).slice(2)); }

function moduleRow(name){
  const id = uid();
  return (
    `<div class="module-box d-flex gap-2 align-items-center" data-row="${id}">
       <input type="text" name="modules[]" class="form-control" placeholder="Module title" value="${name||""}">
       <button type="button" class="btn btn-outline-danger btn-sm module-remove" data-action="remove" title="Remove module">
         <i class="bi bi-trash"></i>
       </button>
     </div>`
  );
}

function initModulesList(listSelector, modulesArr){
  const $list = $(listSelector);
  $list.empty();
  const mods = (Array.isArray(modulesArr) && modulesArr.length) ? modulesArr : [""];
  mods.forEach(m => $list.append(moduleRow(m)));
}

// ===== Live search =====
$('#searchStatus, #searchCode, #searchName').on('input', function(){
  const status = $('#searchStatus').val().toLowerCase();
  const code   = $('#searchCode').val().toLowerCase();
  const name   = $('#searchName').val().toLowerCase();

  $('#courseTable tr').each(function(){
    const text = $(this).text().toLowerCase();
    $(this).toggle(text.includes(status) && text.includes(code) && text.includes(name));
  });
});

// ===== Add modal type toggle =====
$('#add_course_type').on('change', function(){
  if($(this).val()==='bundle'){
    $('#add_modules_input').addClass('d-none');
    $('#add_bundle_input').removeClass('d-none');
  } else {
    $('#add_modules_input').removeClass('d-none');
    $('#add_bundle_input').addClass('d-none');
    if(!$('#addModulesList').children().length) initModulesList('#addModulesList', [""]);
  }
}).trigger('change');

// ===== Edit modal type toggle =====
$('#edit_course_type').on('change', function(){
  if($(this).val()==='bundle'){
    $('#edit_modules_input').addClass('d-none');
    $('#edit_bundle_input').removeClass('d-none');
  } else {
    $('#edit_modules_input').removeClass('d-none');
    $('#edit_bundle_input').addClass('d-none');
    if(!$('#editModulesList').children().length) initModulesList('#editModulesList', [""]);
  }
});

// ===== Modules add/remove buttons =====
$(document).on('click', '#btnAddModuleAdd', () => $('#addModulesList').append(moduleRow("")));
$(document).on('click', '#btnAddModuleEdit', () => $('#editModulesList').append(moduleRow("")));
$(document).on('click', '#addModulesList [data-action="remove"]', function(){ $(this).closest('[data-row]').remove(); });
$(document).on('click', '#editModulesList [data-action="remove"]', function(){ $(this).closest('[data-row]').remove(); });

// ===== Open Add modal with one row =====
$('#addCourseModal').on('shown.bs.modal', function(){
  initModulesList('#addModulesList', [""]);
});

// ===== Add course =====
$('#addCourseForm').on('submit', function(e){
  e.preventDefault();
  let formData = new FormData(this);

  $.ajax({
    url:'add_course.php',
    type:'POST',
    data: formData,
    processData:false,
    contentType:false,
    success:function(res){
      if(res.trim()==='success'){
        alert('Course added!');
        location.reload();
      } else {
        alert('Error: '+res);
      }
    }
  });
});

// ===== Edit: open and fill =====
$(document).on('click', '.editCourseBtn', function(){
  const id = $(this).data('id');

  $.ajax({
    url:'get_course.php',
    type:'POST',
    dataType:'json',
    data:{id:id},
    success:function(data){
      if(!data || data.error){
        alert('Course not found');
        return;
      }

      $('#edit_id').val(data.id);
      $('#edit_status').val(data.status);
      $('#edit_code').val(data.code);
      $('#edit_course_name').val(data.course_name);
      $('#edit_duration').val(data.duration);
      $('#edit_description').val(data.description);
      $('#edit_course_description').val(data.course_description);
      $('#current_image').attr('src', data.image_url);

      const mods = Array.isArray(data.modules_array) ? data.modules_array : [];
      initModulesList('#editModulesList', mods);

      if(data.type==='bundle'){
        $('#edit_modules_input').addClass('d-none');
        $('#edit_bundle_input').removeClass('d-none');
        $('#edit_bundle_select').val(data.bundle_ids);
        $('#edit_course_type').val('bundle').trigger('change');
      } else {
        $('#edit_modules_input').removeClass('d-none');
        $('#edit_bundle_input').addClass('d-none');
        $('#edit_course_type').val('single').trigger('change');
      }

      $('#editCourseModal').modal('show');
    },
    error:function(){
      alert('Failed to fetch course data');
    }
  });
});

// ===== Edit: submit =====
$('#editCourseForm').on('submit', function(e){
  e.preventDefault();
  let formData = new FormData(this);

  $.ajax({
    url:'edit_course.php',
    type:'POST',
    data: formData,
    processData:false,
    contentType:false,
    success:function(res){
      if(res.trim()==='success'){
        alert('Course updated!');
        location.reload();
      } else {
        alert('Error: '+res);
      }
    }
  });
});

// ===== View details =====
function viewCourseDetails(id){
  $.post('get_course_details.php', {id:id}, function(html){
    $('#courseDetailContent').html(html);
    new bootstrap.Modal(document.getElementById('courseDetailsModal')).show();
  }).fail(function(){
    $('#courseDetailContent').html("<div class='alert alert-danger'>Failed to load course details.</div>");
  });
}

// ===== Delete course =====
function deleteCourse(id){
  if(!confirm('Are you sure?')) return;

  $.post('delete_course.php', {id:id}, function(res){
    if(res.trim()==='success'){
      location.reload();
    } else {
      alert(res);
    }
  });
}
</script>
</body>
</html>