<?php declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../../includes/auth.php';
require_role(['super_admin','branch_admin']);
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/layout_top.php';
require_once __DIR__ . '/../../includes/scope.php';

$action = $_POST['action'] ?? '';
$msg = '';

function dt_from_input(?string $s): ?string {
  if (!$s) return null;
  $ts = strtotime($s);
  if ($ts === false) return null;
  return date('Y-m-d H:i:s', $ts);
}

if ($action === 'create') {
  $scope_type = (string)($_POST['scope_type'] ?? 'system');
  $scope_id   = (int)($_POST['scope_id'] ?? 0);
  $title      = trim((string)($_POST['title'] ?? ''));
  $body       = trim((string)($_POST['body'] ?? ''));
  $publish_at = dt_from_input($_POST['publish_at'] ?? '');
  $expire_at  = dt_from_input($_POST['expire_at'] ?? '');
  $pinned     = isset($_POST['pinned']) ? 1 : 0;
  $created_by = (int)($_SESSION['user_id'] ?? 0);

  if ($title === '' || $body === '') {
    $msg = '<div class="alert alert-danger py-2">Title and body are required.</div>';
  } else {
    $stmt = $mysqli->prepare('INSERT INTO lms_announcements (scope_type, scope_id, title, body, publish_at, expire_at, pinned, created_by) VALUES (?,?,?,?,?,?,?,?)');
    $sid = ($scope_type === 'system') ? null : $scope_id;
    $stmt->bind_param('sisssiii', $scope_type, $sid, $title, $body, $publish_at, $expire_at, $pinned, $created_by);
    $stmt->execute();
    $msg = '<div class="alert alert-success py-2">Announcement created.</div>';
  }
}
if ($action === 'pin' || $action === 'unpin') {
  $id = (int)($_POST['id'] ?? 0);
  if ($id > 0) {
    $p = ($action === 'pin') ? 1 : 0;
    $stmt = $mysqli->prepare('UPDATE lms_announcements SET pinned=? WHERE id=?');
    $stmt->bind_param('ii', $p, $id);
    $stmt->execute();
    $msg = '<div class="alert alert-success py-2">Announcement '.($p ? 'pinned' : 'unpinned').'.</div>';
  }
}
if ($action === 'delete') {
  $id = (int)($_POST['id'] ?? 0);
  if ($id > 0) {
    $stmt = $mysqli->prepare('DELETE FROM lms_announcements WHERE id=?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $msg = '<div class="alert alert-warning py-2">Announcement deleted.</div>';
  }
}

$courses = elms_all_courses($mysqli);
$course_id = (int)($_GET['course_id'] ?? 0);
$batches = $course_id ? elms_batches_for_course($mysqli, $course_id) : [];

$rows = [];
try {
  $res = $mysqli->query("SELECT id, scope_type, scope_id, title, publish_at, expire_at, pinned, created_at
                         FROM lms_announcements
                         ORDER BY pinned DESC, publish_at DESC, id DESC
                         LIMIT 50");
  $rows = $res->fetch_all(MYSQLI_ASSOC);
} catch (Throwable $e) { $rows = []; }
?>
<h1 class="h4 mb-3">Announcements</h1>
<?= $msg ?>
<div class="card mb-4 border-0 shadow-sm"><div class="card-body">
  <h2 class="h6">Create Announcement</h2>
  <form method="post" class="row g-2">
    <input type="hidden" name="action" value="create">
    <div class="col-12 col-md-2">
      <label class="form-label">Scope</label>
      <select name="scope_type" class="form-select" id="scope_select" onchange="toggleScope();">
        <option value="system">System</option>
        <option value="course">Course</option>
        <option value="batch">Batch</option>
      </select>
    </div>
    <div class="col-12 col-md-3" id="course_wrap" style="display:none;">
      <label class="form-label">Course</label>
      <select name="scope_course" class="form-select" onchange="location.href='?course_id='+this.value;">
        <option value="">Select course…</option>
        <?php foreach ($courses as $cid => $ctitle): ?>
        <option value="<?= (int)$cid ?>" <?= $cid===$course_id?'selected':'' ?>><?= esc($ctitle) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-12 col-md-3" id="batch_wrap" style="display:none;">
      <label class="form-label">Batch</label>
      <select name="scope_id" class="form-select">
        <option value="">Select batch…</option>
        <?php foreach ($batches as $bid => $bcode): ?>
        <option value="<?= (int)$bid ?>"><?= esc($bcode) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-12"><label class="form-label">Title</label><input name="title" class="form-control" required></div>
    <div class="col-12"><label class="form-label">Body</label><textarea name="body" class="form-control" rows="4" required></textarea></div>
    <div class="col-6 col-md-3"><label class="form-label">Publish at</label><input type="datetime-local" name="publish_at" class="form-control"></div>
    <div class="col-6 col-md-3"><label class="form-label">Expire at</label><input type="datetime-local" name="expire_at" class="form-control"></div>
    <div class="col-12 col-md-2 form-check mt-4"><input class="form-check-input" type="checkbox" name="pinned" id="pin"><label class="form-check-label" for="pin">Pin</label></div>
    <div class="col-12 col-md-2 mt-4"><button class="btn btn-success">Create</button></div>
  </form>
  <script>
    function toggleScope(){const sel=document.getElementById('scope_select').value;
      document.getElementById('course_wrap').style.display=(sel==='course'||sel==='batch')?'':'none';
      document.getElementById('batch_wrap').style.display=(sel==='batch')?'':'none';}
    toggleScope();
  </script>
</div></div>

<div class="card border-0 shadow-sm"><div class="card-body">
  <h2 class="h6 mb-3">Recent</h2>
  <div class="table-responsive">
    <table class="table table-hover align-middle">
      <thead><tr><th>#</th><th>Scope</th><th>Title</th><th>Publish</th><th>Expire</th><th>Pinned</th><th></th></tr></thead>
      <tbody>
        <?php if (!$rows): ?><tr><td colspan="7" class="text-center text-muted">No announcements yet.</td></tr>
        <?php else: foreach ($rows as $r): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= esc($r['scope_type']) ?><?= $r['scope_id'] ? ' #'.(int)$r['scope_id'] : '' ?></td>
            <td><?= esc($r['title']) ?></td>
            <td><?= esc($r['publish_at'] ?? '') ?></td>
            <td><?= esc($r['expire_at'] ?? '') ?></td>
            <td><?= ((int)$r['pinned'] ? 'Yes' : 'No') ?></td>
            <td class="text-end">
              <form method="post" class="d-inline">
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <input type="hidden" name="action" value="<?= ((int)$r['pinned'] ? 'unpin' : 'pin') ?>">
                <button class="btn btn-sm btn-outline-secondary"><?= ((int)$r['pinned'] ? 'Unpin' : 'Pin') ?></button>
              </form>
              <form method="post" class="d-inline" onsubmit="return confirm('Delete announcement?')">
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <input type="hidden" name="action" value="delete">
                <button class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div></div>

<?php require_once __DIR__ . '/../../includes/layout_bottom.php'; ?>
