<?php declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../includes/auth.php';
ec_require_login();
require_once __DIR__ . '/../includes/sms.php';              // for birthday SMS toggle (optional)
require_once __DIR__ . '/../includes/notifications.php';    // NEW
date_default_timezone_set('Asia/Colombo');

$db  = ecn_db();
$uid = (int)($_SESSION['user']['id'] ?? $_SESSION['id'] ?? 0);

/* ---- Kill-switch for callers that don't want any items (e.g., add payment) ---- */
if (isset($_GET['mute']) && $_GET['mute'] === '1') {
  echo json_encode(['items' => []]);
  exit;
}

/* ---- helpers ---- */
function db_has(mysqli $db, string $tbl): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
  if (!$st) return false;
  $st->bind_param('s',$tbl); $st->execute(); $st->store_result();
  $ok = $st->num_rows>0; $st->free_result(); $st->close(); return $ok;
}
function col_exists(mysqli $db, string $tbl, string $col): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
  if (!$st) return false;
  $st->bind_param('ss',$tbl,$col); $st->execute(); $st->store_result();
  $ok = $st->num_rows>0; $st->free_result(); $st->close(); return $ok;
}

/* ---- Optional app_settings + birthday log tables ---- */
@$db->query("CREATE TABLE IF NOT EXISTS app_settings (
  k VARCHAR(64) PRIMARY KEY,
  v VARCHAR(255) NOT NULL,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

@$db->query("CREATE TABLE IF NOT EXISTS birthday_sms_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  student_id INT NOT NULL,
  ymd DATE NOT NULL,
  sent_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  status ENUM('sent','failed') NOT NULL,
  error TEXT NULL,
  UNIQUE KEY uniq_sid_ymd (student_id, ymd)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

function setting_get(mysqli $db, string $key, string $default='0'): string {
  $st = $db->prepare("SELECT v FROM app_settings WHERE k=?");
  if (!$st) return $default;
  $st->bind_param('s',$key); $st->execute(); $st->bind_result($v);
  $out = $st->fetch() ? (string)$v : $default; $st->close(); return $out;
}

/* ---- API: mark-all-read / mark-one-read ---- */
if (($_GET['action'] ?? '') === 'read_all') {
  if ($uid > 0) { noti_mark_all_read($db, $uid); }
  echo json_encode(['ok'=>1]); exit;
}
if (($_GET['action'] ?? '') === 'read' && isset($_GET['id'])) {
  $nid = (int)preg_replace('/^\D+/', '', (string)$_GET['id']); // accepts "noti-123"
  if ($nid > 0 && $uid > 0) { noti_mark_read($db, $nid, $uid); }
  echo json_encode(['ok'=>1]); exit;
}

/* ---- Build items ---- */
$items = [];

/* A) Birthday window (kept) */
try {
  $windowDays = max(0, min(365, (int)($_GET['days'] ?? 7)));
  $BIRTHDAY_SMS_ENABLED = (bool)(sms_cfg()['birthday_sms_enabled'] ?? false);

  if ($db && db_has($db, 'studentss') && col_exists($db,'studentss','dob')) {
    $phoneCols = [];
    foreach (['phone','contact_no','mobile','contact_number','telephone','tel','phone_no'] as $cand) {
      if (col_exists($db, 'studentss', $cand)) $phoneCols[] = $cand;
    }
    $selPhones = '';
    foreach ($phoneCols as $c) $selPhones .= ", {$c} AS {$c}";

    $sql = "SELECT id, full_name AS s_name, dob{$selPhones}
            FROM studentss
            WHERE dob IS NOT NULL AND dob <> '0000-00-00'";
    if ($rs = $db->query($sql)) {
      $today = new DateTime('today');
      while ($row = $rs->fetch_assoc()) {
        $sid   = (int)$row['id'];
        $name  = trim((string)$row['s_name']) ?: 'Student';
        $dobS  = (string)$row['dob'];
        try { $dob = new DateTime($dobS); } catch (Throwable $e) { continue; }

        $md = $dob->format('m-d');
        $yr = (int)$today->format('Y');
        try { $next = new DateTime("{$yr}-{$md}"); }
        catch (Throwable $e) { if ($md==='02-29') $next = new DateTime("{$yr}-02-28"); else continue; }
        if ($next < $today) $next->modify('+1 year');

        $days = (int)$today->diff($next)->days;
        if ($days > $windowDays) continue;

        $turning = $dob->diff($next)->y;
        $ageTxt  = $turning > 0 ? " (turns {$turning})" : '';
        $dateLbl = $next->format('D, d M');
        $nid     = "bday-{$sid}-".$next->format('Ymd');

        $items[] = [
          'id'    => $nid,
          'title' => $days === 0 ? '🎂 Birthday today' : '🎂 Upcoming birthday',
          'body'  => $days === 0 ? "{$name}{$ageTxt}" : "{$name}{$ageTxt} — in {$days} day".($days===1?'':'s')." (on {$dateLbl})",
          'time'  => $days === 0 ? 'today' : "in {$days}d",
          'read'  => false,
        ];

        // Auto SMS only on birthday
        if ($days === 0 && $BIRTHDAY_SMS_ENABLED) {
          $ymd = $today->format('Y-m-d');
          $st = $db->prepare("SELECT 1 FROM birthday_sms_log WHERE student_id=? AND ymd=? LIMIT 1");
          if ($st) {
            $st->bind_param('is',$sid,$ymd);
            $st->execute(); $exists = (bool)$st->get_result()->fetch_row(); $st->close();
            if (!$exists) {
              $phone = '';
              foreach ($phoneCols as $c) { if (!empty($row[$c])) { $phone = trim((string)$row[$c]); if ($phone) break; } }
              if ($phone) {
                $msg = "Happy Birthday, {$name}! 🎉 – Eden Campus";
                $err = null; $ok  = sms_send($phone, $msg, $err);
                $st2 = $db->prepare("INSERT INTO birthday_sms_log(student_id, ymd, status, error) VALUES (?,?,?,?)");
                $status = $ok ? 'sent' : 'failed'; $errTxt = $ok ? null : (string)$err;
                $st2 && $st2->bind_param('isss',$sid,$ymd,$status,$errTxt) && $st2->execute(); $st2 && $st2->close();
              }
            }
          }
        }
      }
      $rs->close();
    }
  }
} catch (Throwable $e) {
  $items[] = ['id'=>'err-'.time(),'title'=>'⚠️ Notifications error','body'=>'Birthday fetch failed. ('.$e->getMessage().')','time'=>date('H:i'),'read'=>false];
}

/* B) Approval/role notifications (NEW) */
if ($uid > 0) {
  try {
    $roleItems = noti_fetch_for_user($db, $uid, 30, false);
    $items = array_merge($roleItems, $items); // show role items first
  } catch (Throwable $e) {
    // ignore
  }
}

echo json_encode(['items' => $items], JSON_UNESCAPED_UNICODE);
