<?php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

/* ------------------------------
   Actions
------------------------------ */

// Add course
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
  $name        = trim($_POST['name'] ?? '');
  $dur         = (int)($_POST['duration_months'] ?? 3);
  $fee_type_in = $_POST['fee_type'] ?? 'PER_COURSE';
  $fee_type    = ($fee_type_in === 'PER_MONTH') ? 'PER_MONTH' : 'PER_COURSE';
  $course_fee  = (int)($_POST['course_fee'] ?? 0);
  $monthly_fee = (int)($_POST['monthly_fee'] ?? 0);

  if ($name !== '') {
    $st = mysqli_prepare($conn, "INSERT INTO courses(name,duration_months,course_fee,fee_type,monthly_fee,is_active) VALUES (?,?,?,?,?,1)");
    if(!$st){ die("Prepare failed: " . mysqli_error($conn)); }
    mysqli_stmt_bind_param($st, "siisi", $name, $dur, $course_fee, $fee_type, $monthly_fee);
    if(!mysqli_stmt_execute($st)){ die("Execute failed: " . mysqli_stmt_error($st)); }
    mysqli_stmt_close($st);
  }
  header('Location: courses.php?msg='.urlencode('Course added'));
  exit;
}

// Update course (inline editor)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
  $id          = (int)($_POST['id'] ?? 0);
  $name        = trim($_POST['name'] ?? '');
  $dur         = (int)($_POST['duration_months'] ?? 3);
  $fee_type_in = $_POST['fee_type'] ?? 'PER_COURSE';
  $fee_type    = ($fee_type_in === 'PER_MONTH') ? 'PER_MONTH' : 'PER_COURSE';
  $course_fee  = (int)($_POST['course_fee'] ?? 0);
  $monthly_fee = (int)($_POST['monthly_fee'] ?? 0);

  if ($id > 0 && $name !== '') {
    $st = mysqli_prepare($conn, "UPDATE courses SET name=?, duration_months=?, course_fee=?, fee_type=?, monthly_fee=? WHERE id=?");
    if(!$st){ die("Prepare failed: " . mysqli_error($conn)); }
    mysqli_stmt_bind_param($st, "siisii", $name, $dur, $course_fee, $fee_type, $monthly_fee, $id);
    if(!mysqli_stmt_execute($st)){ die("Execute failed: " . mysqli_stmt_error($st)); }
    mysqli_stmt_close($st);
  }
  header('Location: courses.php?msg='.urlencode('Course updated'));
  exit;
}

// Toggle active/inactive
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action']) && $_POST['action'] === 'toggle') {
  $id   = (int)($_POST['id'] ?? 0);
  $next = (int)($_POST['next'] ?? 0);
  if ($id > 0) {
    $st = mysqli_prepare($conn, "UPDATE courses SET is_active=? WHERE id=?");
    mysqli_stmt_bind_param($st, "ii", $next, $id);
    mysqli_stmt_execute($st);
    mysqli_stmt_close($st);
  }
  header('Location: courses.php?msg='.urlencode('Status updated'));
  exit;
}

// Load courses
$courses = mysqli_query($conn, "SELECT id,name,duration_months,course_fee,fee_type,monthly_fee,is_active FROM courses ORDER BY name");

/* ------------------------------
   UI
------------------------------ */

admin_header('Courses');
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
?>
<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  Courses
  <span style="font-size:12px;font-weight:600;color:#2563eb;background:#dbeafe;border:1px solid #bfdbfe;border-radius:999px;padding:2px 8px">
    Manage offerings & fees
  </span>
</h2>

<?php if($msg): ?>
  <div class="card mt-3" style="background:#eff6ff;border-color:#bfdbfe;color:#1e40af">
    <?= h($msg) ?>
  </div>
<?php endif; ?>

<div class="grid mt-3">
  <!-- Add Course -->
  <div class="card col-6" style="position:relative;overflow:hidden">
    <div style="position:absolute;right:-20px;top:-20px;width:110px;height:110px;background:linear-gradient(135deg,#bfdbfe,#93c5fd);opacity:.25;border-radius:50%"></div>
    <h3 style="margin:0 0 12px;color:#2563eb">Add Course</h3>

    <form method="post" style="display:grid;gap:10px">
      <input type="hidden" name="action" value="add">

      <label>Name</label>
      <input name="name" placeholder="e.g. Web Development" required>

      <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
        <div style="grid-column:span 6">
          <label>Duration (months)</label>
          <input type="number" name="duration_months" value="3" min="1" step="1">
        </div>
        <div style="grid-column:span 6">
          <label>Fee Type</label>
          <select name="fee_type" id="feeTypeAdd">
            <option value="PER_COURSE">Per Course (one-time)</option>
            <option value="PER_MONTH">Per Month</option>
          </select>
        </div>
      </div>

      <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
        <div style="grid-column:span 6">
          <label>Course Fee (one-time)</label>
          <input type="number" name="course_fee" value="0" min="0" step="100" id="courseFeeAdd">
        </div>
        <div style="grid-column:span 6">
          <label>Monthly Fee (if per-month)</label>
          <input type="number" name="monthly_fee" value="0" min="0" step="100" id="monthlyFeeAdd">
        </div>
      </div>

      <button class="btn primary mt-2" style="width:max-content">Add Course</button>
      <div style="font-size:12px;color:#475569">Tip: Select fee type to enable relevant fee field.</div>
    </form>
  </div>

  <!-- All Courses -->
  <div class="card col-6">
    <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px">
      <h3 style="margin:0;color:#2563eb">All Courses</h3>
      <input id="courseSearch" placeholder="Search by name..." style="max-width:240px">
    </div>

    <div style="overflow:auto;border-radius:10px;border:1px solid var(--border)">
      <table id="coursesTable" style="min-width:860px">
        <thead>
          <tr>
            <th style="background:#f1f5f9">#</th>
            <th style="background:#f1f5f9;text-align:left">Name</th>
            <th style="background:#f1f5f9">Duration</th>
            <th style="background:#f1f5f9">Fee Model</th>
            <th style="background:#f1f5f9; text-align:right">Amount</th>
            <th style="background:#f1f5f9">Status</th>
            <th style="background:#f1f5f9;width:210px">Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php
        $hasRows = false;
        while($c = mysqli_fetch_assoc($courses)):
          $hasRows = true;
          $active = (int)$c['is_active'] === 1;
          $badge  = $active
            ? '<span style="background:#dcfce7;color:#166534;border:1px solid #86efac;padding:3px 8px;border-radius:999px;font-size:12px;font-weight:700">Active</span>'
            : '<span style="background:#fee2e2;color:#991b1b;border:1px solid #fecaca;padding:3px 8px;border-radius:999px;font-size:12px;font-weight:700">Inactive</span>';

          $model = ($c['fee_type']==='PER_MONTH') ? 'Per Month' : 'Per Course';
          $amount = ($c['fee_type']==='PER_MONTH')
                    ? number_format((int)$c['monthly_fee']).' /month'
                    : number_format((int)$c['course_fee']).' total';
        ?>
          <tr class="row" data-id="<?= (int)$c['id'] ?>">
            <td style="text-align:center"><?= $c['id'] ?></td>
            <td class="name" style="font-weight:600"><?= h($c['name']) ?></td>
            <td style="text-align:center"><?= (int)$c['duration_months'] ?> mo</td>
            <td style="text-align:center"><?= $model ?></td>
            <td style="text-align:right"><?= $amount ?></td>
            <td style="text-align:center"><?= $badge ?></td>
            <td style="text-align:center; white-space:nowrap">
              <button class="btn editBtn" data-id="<?= (int)$c['id'] ?>" style="padding:6px 10px;border-color:#bfdbfe">Edit</button>
              <form method="post" style="display:inline">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
                <input type="hidden" name="next" value="<?= $active ? 0 : 1 ?>">
                <button class="btn" style="padding:6px 10px;margin-left:6px" onclick="return confirm('Are you sure you want to <?= $active?'deactivate':'activate' ?> this course?')">
                  <?= $active ? 'Deactivate' : 'Activate' ?>
                </button>
              </form>
            </td>
          </tr>

          <!-- Inline editor (hidden by default) -->
          <tr class="editRow" id="edit-<?= (int)$c['id'] ?>" style="display:none;background:#f8fafc">
            <td colspan="7">
              <form method="post" style="display:grid;gap:10px">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">

                <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                  <div style="grid-column:span 5">
                    <label>Name</label>
                    <input name="name" value="<?= h($c['name']) ?>" required>
                  </div>
                  <div style="grid-column:span 2">
                    <label>Duration (months)</label>
                    <input type="number" name="duration_months" value="<?= (int)$c['duration_months'] ?>" min="1" step="1">
                  </div>
                  <div style="grid-column:span 3">
                    <label>Fee Type</label>
                    <select name="fee_type" class="feeTypeEdit">
                      <option value="PER_COURSE" <?= $c['fee_type']==='PER_COURSE'?'selected':'' ?>>Per Course</option>
                      <option value="PER_MONTH"  <?= $c['fee_type']==='PER_MONTH'?'selected':''  ?>>Per Month</option>
                    </select>
                  </div>
                  <div style="grid-column:span 2; display:flex;align-items:flex-end;justify-content:flex-end">
                    <button class="btn primary" style="height:38px">Save</button>
                  </div>
                </div>

                <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                  <div style="grid-column:span 6">
                    <label>Course Fee (one-time)</label>
                    <input type="number" name="course_fee" value="<?= (int)$c['course_fee'] ?>" min="0" step="100" class="courseFeeEdit">
                  </div>
                  <div style="grid-column:span 6">
                    <label>Monthly Fee (if per-month)</label>
                    <input type="number" name="monthly_fee" value="<?= (int)$c['monthly_fee'] ?>" min="0" step="100" class="monthlyFeeEdit">
                  </div>
                </div>
              </form>
            </td>
          </tr>
        <?php endwhile; ?>
        <?php if(!$hasRows): ?>
          <tr><td colspan="7" style="text-align:center;padding:24px;color:#64748b">No courses yet. Add your first course on the left.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div style="display:flex;justify-content:flex-end;font-size:12px;color:#64748b;margin-top:8px">
      Tip: Per-month shows “/month”, Per-course shows total amount.
    </div>
  </div>
</div>

<script>
// Search
const search = document.getElementById('courseSearch');
const rows = [...document.querySelectorAll('#coursesTable tbody tr.row')];
search.addEventListener('input', () => {
  const q = search.value.trim().toLowerCase();
  rows.forEach(r => {
    const name = r.querySelector('.name')?.textContent.toLowerCase() || '';
    r.style.display = name.includes(q) ? '' : 'none';
  });
});

// Add form fee toggles
const feeTypeAdd = document.getElementById('feeTypeAdd');
const courseFeeAdd = document.getElementById('courseFeeAdd');
const monthlyFeeAdd = document.getElementById('monthlyFeeAdd');
function updateAddFeeVisibility(){
  if (feeTypeAdd.value === 'PER_MONTH') {
    monthlyFeeAdd.disabled = false;
    courseFeeAdd.disabled = true;
    courseFeeAdd.value = courseFeeAdd.value || 0;
  } else {
    monthlyFeeAdd.disabled = true;
    courseFeeAdd.disabled = false;
    monthlyFeeAdd.value = monthlyFeeAdd.value || 0;
  }
}
feeTypeAdd.addEventListener('change', updateAddFeeVisibility);
updateAddFeeVisibility();

// Inline editor toggle
document.querySelectorAll('.editBtn').forEach(btn => {
  btn.addEventListener('click', () => {
    const id = btn.dataset.id;
    const row = document.getElementById('edit-'+id);
    // close others
    document.querySelectorAll('.editRow').forEach(r => { if(r!==row) r.style.display='none'; });
    row.style.display = (row.style.display === 'none' || row.style.display === '') ? 'table-row' : 'none';

    // set proper enabled/disabled on fee fields for this row
    const feeTypeSel = row.querySelector('.feeTypeEdit');
    const courseFee  = row.querySelector('.courseFeeEdit');
    const monthlyFee = row.querySelector('.monthlyFeeEdit');
    const sync = () => {
      if (feeTypeSel.value === 'PER_MONTH') {
        monthlyFee.disabled = false;
        courseFee.disabled = true;
      } else {
        monthlyFee.disabled = true;
        courseFee.disabled = false;
      }
    };
    feeTypeSel.addEventListener('change', sync);
    sync();
  });
});
</script>

<?php admin_footer(); ?>
