<?php
require_once '../includes/config.php';
requireAdmin();

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'send') {
        $title   = sanitize($_POST['title'] ?? '');
        $message = sanitize($_POST['message'] ?? '');
        $type    = in_array($_POST['type'] ?? '', ['info','warning','success','danger']) ? $_POST['type'] : 'info';
        $theme   = in_array($_POST['theme'] ?? '', ['default','celebration','urgent','reminder','achievement','system']) ? $_POST['theme'] : 'default';
        $target  = $_POST['target'] ?? 'all';

        if (!$title || !$message) {
            jsonResponse(['success'=>false,'message'=>'Title and message are required.']);
        }

        // Prepend theme emoji prefix to title if not default
        $themePrefix = [
            'celebration' => '🎉 ',
            'urgent'      => '🚨 ',
            'reminder'    => '⏰ ',
            'achievement' => '🏆 ',
            'system'      => '⚙️ ',
            'default'     => '',
        ];
        $finalTitle = ($themePrefix[$theme] ?? '') . $title;

        if ($target === 'all') {
            $stmt = $db->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (NULL,?,?,?)");
            $stmt->bind_param("sss", $finalTitle, $message, $type);
            $stmt->execute();
            jsonResponse(['success'=>true,'message'=>'Notification broadcast to all users!']);
        } else {
            $userId = (int)$target;
            $stmt   = $db->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (?,?,?,?)");
            $stmt->bind_param("isss", $userId, $finalTitle, $message, $type);
            $stmt->execute();
            jsonResponse(['success'=>true,'message'=>'Notification sent to user!']);
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("DELETE FROM notifications WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        jsonResponse(['success'=>true]);
    }

    if ($action === 'delete_all') {
        $db->query("DELETE FROM notifications WHERE created_at < NOW() - INTERVAL 30 DAY");
        jsonResponse(['success'=>true,'message'=>'Old notifications cleared.']);
    }
}

$notifications = $db->query("
    SELECT n.*, u.name as user_name
    FROM notifications n
    LEFT JOIN users u ON n.user_id = u.id
    ORDER BY n.created_at DESC
    LIMIT 100
")->fetch_all(MYSQLI_ASSOC);

$users = $db->query("SELECT id, name, email FROM users WHERE is_verified=1 ORDER BY name")->fetch_all(MYSQLI_ASSOC);

// Stats
$totalSent    = (int)$db->query("SELECT COUNT(*) FROM notifications")->fetch_row()[0];
$broadcastCnt = (int)$db->query("SELECT COUNT(*) FROM notifications WHERE user_id IS NULL")->fetch_row()[0];
$todayCnt     = (int)$db->query("SELECT COUNT(*) FROM notifications WHERE DATE(created_at)=CURDATE()")->fetch_row()[0];
$unreadCnt    = 0;
try { $unreadCnt = (int)$db->query("SELECT COUNT(*) FROM notifications WHERE is_read=0")->fetch_row()[0]; } catch(Exception $e) {}

require_once 'includes/header.php';
renderAdminHeader('Notifications', 'notifications');
?>

<style>
.theme-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(130px,1fr)); gap:10px; margin-top:8px; }
.theme-btn  { border:1px solid var(--border); border-radius:10px; padding:10px 12px; cursor:pointer; text-align:center; transition:all .15s; background:transparent; color:var(--text-primary); font-size:13px; }
.theme-btn:hover  { border-color:var(--accent); background:rgba(99,102,241,0.06); }
.theme-btn.active { border-color:var(--accent); background:rgba(99,102,241,0.1); color:var(--accent); font-weight:600; }
.theme-btn .t-icon { font-size:22px; display:block; margin-bottom:4px; }
.theme-btn .t-label { display:block; font-size:12px; }

.preview-box { border:1px solid var(--border); border-radius:12px; padding:14px 16px; display:flex; align-items:flex-start; gap:12px; transition:all .2s; }
.preview-box.theme-info        { border-left:4px solid #6366f1; background:rgba(99,102,241,0.06); }
.preview-box.theme-success     { border-left:4px solid #10b981; background:rgba(16,185,129,0.06); }
.preview-box.theme-warning     { border-left:4px solid #f59e0b; background:rgba(245,158,11,0.06); }
.preview-box.theme-danger      { border-left:4px solid #ef4444; background:rgba(239,68,68,0.06); }
.preview-icon { font-size:22px; flex-shrink:0; line-height:1; }
.preview-title { font-size:14px; font-weight:600; color:var(--text-primary); margin:0 0 3px; }
.preview-msg   { font-size:13px; color:var(--text-secondary); margin:0; line-height:1.5; }

.char-count { font-size:12px; color:var(--text-muted); text-align:right; margin-top:4px; }
.char-count.over { color:#ef4444; }

.notif-row-info    { border-left:3px solid #6366f1; }
.notif-row-success { border-left:3px solid #10b981; }
.notif-row-warning { border-left:3px solid #f59e0b; }
.notif-row-danger  { border-left:3px solid #ef4444; }
</style>

<!-- Stats -->
<div class="stats-grid" style="margin-bottom:24px">
  <div class="stat-card"><div class="stat-icon" style="background:rgba(99,102,241,0.15)">🔔</div><div class="stat-value"><?= number_format($totalSent) ?></div><div class="stat-label">Total Sent</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(6,182,212,0.15)">📢</div><div class="stat-value"><?= $broadcastCnt ?></div><div class="stat-label">Broadcasts</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(16,185,129,0.15)">📅</div><div class="stat-value"><?= $todayCnt ?></div><div class="stat-label">Sent Today</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(245,158,11,0.15)">👁</div><div class="stat-value"><?= $unreadCnt ?></div><div class="stat-label">Unread</div></div>
</div>

<!-- Compose -->
<div class="card" style="margin-bottom:24px">
  <div class="card-header"><div class="card-title">🔔 Compose Notification</div></div>
  <div style="padding:24px">
    <div id="notifMsg" style="display:none" class="alert"></div>

    <!-- Theme picker -->
    <div class="form-group">
      <label class="form-label">Theme</label>
      <div class="theme-grid" id="themeGrid">
        <button type="button" class="theme-btn active" data-theme="default" data-icon="🔔" data-type="info">
          <span class="t-icon">🔔</span><span class="t-label">Default</span>
        </button>
        <button type="button" class="theme-btn" data-theme="celebration" data-icon="🎉" data-type="success">
          <span class="t-icon">🎉</span><span class="t-label">Celebration</span>
        </button>
        <button type="button" class="theme-btn" data-theme="urgent" data-icon="🚨" data-type="danger">
          <span class="t-icon">🚨</span><span class="t-label">Urgent</span>
        </button>
        <button type="button" class="theme-btn" data-theme="reminder" data-icon="⏰" data-type="warning">
          <span class="t-icon">⏰</span><span class="t-label">Reminder</span>
        </button>
        <button type="button" class="theme-btn" data-theme="achievement" data-icon="🏆" data-type="success">
          <span class="t-icon">🏆</span><span class="t-label">Achievement</span>
        </button>
        <button type="button" class="theme-btn" data-theme="system" data-icon="⚙️" data-type="info">
          <span class="t-icon">⚙️</span><span class="t-label">System</span>
        </button>
      </div>
      <input type="hidden" id="selectedTheme" value="default">
      <input type="hidden" id="selectedType"  value="info">
    </div>

    <form id="notifForm">
      <input type="hidden" name="theme" id="themeInput" value="default">
      <input type="hidden" name="type"  id="typeInput"  value="info">

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px">
        <div class="form-group" style="margin:0">
          <label class="form-label">Title *</label>
          <input type="text" id="titleInput" name="title" class="form-control" placeholder="Notification title" maxlength="100" required>
          <div class="char-count" id="titleCount">0 / 100</div>
        </div>
        <div class="form-group" style="margin:0">
          <label class="form-label">Send To *</label>
          <select name="target" class="form-control">
            <option value="all">📢 All Users (Broadcast)</option>
            <?php foreach ($users as $u): ?>
            <option value="<?= $u['id'] ?>">👤 <?= htmlspecialchars($u['name']) ?> (<?= htmlspecialchars($u['email']) ?>)</option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="form-group" style="margin-bottom:16px">
        <label class="form-label">Message *</label>
        <textarea id="msgInput" name="message" class="form-control" rows="3" placeholder="Write your notification message..." maxlength="300" required></textarea>
        <div class="char-count" id="msgCount">0 / 300</div>
      </div>

      <!-- Live Preview -->
      <div class="form-group" style="margin-bottom:20px">
        <label class="form-label">Preview</label>
        <div class="preview-box theme-info" id="previewBox">
          <div class="preview-icon" id="previewIcon">🔔</div>
          <div>
            <p class="preview-title" id="previewTitle">Notification title</p>
            <p class="preview-msg"   id="previewMsg">Your message will appear here…</p>
          </div>
        </div>
      </div>

      <div style="display:flex;gap:10px;align-items:center">
        <button type="submit" id="sendBtn" class="btn btn-primary">🔔 Send Notification</button>
        <button type="button" class="btn btn-secondary" onclick="document.getElementById('notifForm').reset();updatePreview();">Clear</button>
      </div>
    </form>
  </div>
</div>

<!-- History -->
<div class="card">
  <div class="card-header">
    <div class="card-title">📋 Recent Notifications (<?= count($notifications) ?>)</div>
    <?php if(count($notifications)>0): ?>
    <button class="btn btn-secondary btn-sm" onclick="clearOld()" style="color:#ef4444">🗑 Clear Old (30d+)</button>
    <?php endif; ?>
  </div>
  <?php if (empty($notifications)): ?>
  <div class="empty-state"><div class="empty-icon">🔔</div><h3>No notifications sent yet</h3><p>Send your first notification above.</p></div>
  <?php else: ?>
  <div class="table-wrapper">
    <table>
      <thead>
        <tr><th>Theme / Title</th><th>Message</th><th>Type</th><th>Sent To</th><th>Date</th><th></th></tr>
      </thead>
      <tbody>
      <?php foreach ($notifications as $n):
        $typeClass = 'notif-row-' . ($n['type'] ?? 'info');
        $badges = ['info'=>'badge-purple','success'=>'badge-green','warning'=>'badge-yellow','danger'=>'badge-red'];
        $typeIcons = ['info'=>'ℹ️','success'=>'✅','warning'=>'⚠️','danger'=>'🚨'];
      ?>
      <tr class="<?= $typeClass ?>">
        <td>
          <div style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($n['title']) ?></div>
        </td>
        <td style="max-width:220px;color:var(--text-secondary);font-size:13px">
          <?= htmlspecialchars(mb_substr($n['message'],0,80)) . (mb_strlen($n['message'])>80?'…':'') ?>
        </td>
        <td><span class="badge <?= $badges[$n['type']] ?? 'badge-purple' ?>"><?= ($typeIcons[$n['type']] ?? 'ℹ️') . ' ' . ucfirst($n['type'] ?? 'info') ?></span></td>
        <td>
          <?= $n['user_name']
            ? '<div style="font-size:13px">'.htmlspecialchars($n['user_name']).'</div>'
            : '<span class="badge badge-cyan">📢 All Users</span>' ?>
        </td>
        <td style="font-size:12px;color:var(--text-muted);white-space:nowrap"><?= date('M j, Y', strtotime($n['created_at'])) ?><br><?= date('H:i', strtotime($n['created_at'])) ?></td>
        <td><button class="btn btn-danger btn-sm" onclick="deleteNotif(<?= $n['id'] ?>)">🗑</button></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<script>
const themeData = {
  default:     { icon:'🔔', type:'info',    previewClass:'theme-info' },
  celebration: { icon:'🎉', type:'success', previewClass:'theme-success' },
  urgent:      { icon:'🚨', type:'danger',  previewClass:'theme-danger' },
  reminder:    { icon:'⏰', type:'warning', previewClass:'theme-warning' },
  achievement: { icon:'🏆', type:'success', previewClass:'theme-success' },
  system:      { icon:'⚙️', type:'info',    previewClass:'theme-info' },
};

let currentTheme = 'default';

document.querySelectorAll('.theme-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.theme-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    currentTheme = btn.dataset.theme;
    document.getElementById('themeInput').value = currentTheme;
    document.getElementById('typeInput').value  = themeData[currentTheme].type;
    updatePreview();
  });
});

function updatePreview() {
  const td    = themeData[currentTheme];
  const title = document.getElementById('titleInput').value.trim() || 'Notification title';
  const msg   = document.getElementById('msgInput').value.trim()   || 'Your message will appear here…';
  const prefix = { celebration:'🎉 ', urgent:'🚨 ', reminder:'⏰ ', achievement:'🏆 ', system:'⚙️ ', default:'' };

  document.getElementById('previewIcon').textContent  = td.icon;
  document.getElementById('previewTitle').textContent = (prefix[currentTheme] || '') + title;
  document.getElementById('previewMsg').textContent   = msg;

  const box = document.getElementById('previewBox');
  box.className = 'preview-box ' + td.previewClass;
}

function charCount(inputId, countId, max) {
  const el  = document.getElementById(inputId);
  const cnt = document.getElementById(countId);
  el.addEventListener('input', () => {
    const len = el.value.length;
    cnt.textContent = len + ' / ' + max;
    cnt.classList.toggle('over', len > max * 0.9);
    updatePreview();
  });
}
charCount('titleInput','titleCount',100);
charCount('msgInput','msgCount',300);

const form    = document.getElementById('notifForm');
const msgBox  = document.getElementById('notifMsg');
const sendBtn = document.getElementById('sendBtn');

function showMsg(msg, type) {
  msgBox.className = 'alert alert-' + type;
  msgBox.innerHTML = (type==='error'?'⚠️ ':'✅ ') + msg;
  msgBox.style.display = 'flex';
}

form.addEventListener('submit', async e => {
  e.preventDefault();
  sendBtn.disabled = true;
  sendBtn.innerHTML = '<span class="spinner"></span> Sending…';
  msgBox.style.display = 'none';

  const fd = new FormData(form);
  fd.append('action','send');

  try {
    const res  = await fetch(window.location.href, {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    const data = await res.json();
    if (data.success) {
      showMsg(data.message, 'success');
      form.reset();
      document.querySelectorAll('.theme-btn').forEach(b=>b.classList.remove('active'));
      document.querySelector('[data-theme="default"]').classList.add('active');
      currentTheme='default';
      document.getElementById('themeInput').value='default';
      document.getElementById('typeInput').value='info';
      updatePreview();
      setTimeout(() => location.reload(), 1400);
    } else {
      showMsg(data.message || 'Error sending notification.', 'error');
    }
  } catch(err) {
    showMsg('Connection error. Please try again.', 'error');
  }
  sendBtn.disabled = false;
  sendBtn.innerHTML = '🔔 Send Notification';
});

async function deleteNotif(id) {
  if (!confirm('Delete this notification?')) return;
  const fd = new FormData();
  fd.append('action','delete'); fd.append('id',id);
  const res  = await fetch(window.location.href,{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
  const data = await res.json();
  if (data.success) location.reload();
}

async function clearOld() {
  if (!confirm('Delete all notifications older than 30 days?')) return;
  const fd = new FormData();
  fd.append('action','delete_all');
  const res  = await fetch(window.location.href,{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
  const data = await res.json();
  if (data.success) location.reload();
}

updatePreview();
</script>

<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
