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

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action']??'';
    if ($action==='toggle') {
        $id=(int)$_POST['id']; $v=(int)$_POST['verified'];
        $pdo->prepare("UPDATE users SET is_verified=? WHERE id=?")->execute([$v,$id]);
        jsonResponse(['success'=>true]);
    }
    if ($action==='disable') {
        $id=(int)$_POST['id']; $v=(int)$_POST['disabled'];
        $pdo->prepare("UPDATE users SET is_disabled=? WHERE id=?")->execute([$v,$id]);
        jsonResponse(['success'=>true]);
    }
    if ($action==='delete') {
        $pdo->prepare("DELETE FROM users WHERE id=?")->execute([(int)$_POST['id']]);
        jsonResponse(['success'=>true]);
    }
    if ($action==='save_note') {
        $id=(int)$_POST['id']; $note=sanitize($_POST['note']??'');
        try {
            $pdo->prepare("INSERT INTO admin_user_notes (user_id,note,created_at) VALUES (?,?,NOW()) ON DUPLICATE KEY UPDATE note=?, updated_at=NOW()")->execute([$id,$note,$note]);
        } catch(Exception $e) { /* table may not exist yet */ }
        jsonResponse(['success'=>true]);
    }
    if ($action==='warn') {
        $id=(int)$_POST['id']; $msg=sanitize($_POST['message']??'');
        if ($id && $msg) {
            try {
                $pdo->prepare("UPDATE user_warnings SET dismissed=1 WHERE user_id=? AND dismissed=0 AND expires_at>NOW()")->execute([$id]);
                $pdo->prepare("INSERT INTO user_warnings (user_id,message,issued_by,expires_at) VALUES (?,?,?,DATE_ADD(NOW(),INTERVAL 24 HOUR))")
                    ->execute([$id,$msg,$_SESSION['admin_id']]);
            } catch(Exception $e) { /* table may not exist yet — run migration SQL */ }
            try {
                $pdo->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")
                    ->execute([$id,'⚠️ Admin Warning',$msg]);
            } catch(Exception $e) {}
        }
        jsonResponse(['success'=>true]);
    }
    if ($action==='dismiss_warning') {
        $id=(int)$_POST['id'];
        try {
            $pdo->prepare("UPDATE user_warnings SET dismissed=1 WHERE user_id=? AND dismissed=0 AND expires_at>NOW()")->execute([$id]);
        } catch(Exception $e) {}
        jsonResponse(['success'=>true]);
    }
    if ($action==='unlock_abuse') {
        $id=(int)$_POST['id'];
        try {
            $pdo->prepare("UPDATE users SET abuse_locked_until=NULL, abuse_warned=0 WHERE id=?")->execute([$id]);
        } catch(Exception $e) { /* abuse columns not migrated yet — run database_abuse_lock.sql */ }
        jsonResponse(['success'=>true]);
    }
    if ($action==='direct_notify') {
        $id=(int)$_POST['id']; $msg=sanitize($_POST['message']??'');
        if ($id && $msg) {
            $pdo->prepare("INSERT INTO notifications (user_id, message, created_at) VALUES (?,?,NOW())")->execute([$id,$msg]);
        }
        jsonResponse(['success'=>true]);
    }
}

// CSV Export
if (isset($_GET['export']) && $_GET['export']==='csv') {
    $expQ = $pdo->query("SELECT u.name, u.email, u.created_at, COALESCE(SUM(ss.duration_minutes),0) as total_mins, u.last_login FROM users u LEFT JOIN study_sessions ss ON u.id=ss.user_id WHERE u.is_verified=1 GROUP BY u.id ORDER BY u.created_at DESC");
    $rows = $expQ->fetchAll();
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename="studytrack_users_'.date('Y-m-d').'.csv"');
    $out = fopen('php://output','w');
    fputcsv($out,['Name','Email','Join Date','Total Study Hours','Last Active']);
    foreach($rows as $r) {
        fputcsv($out,[$r['name'],$r['email'],date('Y-m-d',strtotime($r['created_at'])),round($r['total_mins']/60,1),$r['last_login']?date('Y-m-d',strtotime($r['last_login'])):'Never']);
    }
    fclose($out); exit;
}

$search  = sanitize($_GET['search']??'');
$filter  = $_GET['filter']??'all';

// Check if user_warnings table exists
$_warningsTableExists = false;
try {
    $pdo->query("SELECT 1 FROM user_warnings LIMIT 1");
    $_warningsTableExists = true;
} catch(Exception $e) { $_warningsTableExists = false; }

$_warnSubquery = $_warningsTableExists
    ? "(SELECT COUNT(*) FROM user_warnings uw WHERE uw.user_id=u.id AND uw.dismissed=0 AND uw.expires_at>NOW())"
    : "0";

// Check if abuse-lock columns exist yet
$_abuseColsExist = false;
try {
    $pdo->query("SELECT abuse_locked_until FROM users LIMIT 1");
    $_abuseColsExist = true;
} catch(Exception $e) { $_abuseColsExist = false; }

$_abuseSelect = $_abuseColsExist ? "u.abuse_locked_until, u.abuse_warned," : "NULL as abuse_locked_until, 0 as abuse_warned,";

$sql = "SELECT u.*, {$_abuseSelect} COUNT(DISTINCT ss.id) as sessions, COALESCE(SUM(ss.duration_minutes),0) as total_mins,
        {$_warnSubquery} as active_warnings
        FROM users u LEFT JOIN study_sessions ss ON u.id=ss.user_id";
$params = [];
$where = [];
if ($search) { $where[] = "(u.name LIKE ? OR u.email LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($filter === 'active')     $where[] = "(u.is_disabled IS NULL OR u.is_disabled=0)";
if ($filter === 'disabled')   $where[] = "u.is_disabled=1";
if ($filter === 'unverified') $where[] = "(u.is_verified IS NULL OR u.is_verified=0)";
if ($filter === 'inactive')   $where[] = "(u.last_login IS NULL OR u.last_login < NOW() - INTERVAL 7 DAY)";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " GROUP BY u.id ORDER BY u.created_at DESC";
$usersQ = $pdo->prepare($sql); $usersQ->execute($params); $users = $usersQ->fetchAll();

$allUsers = $pdo->query("SELECT id, is_verified, is_disabled FROM users")->fetchAll();
$cTotal    = count($allUsers);
$cDisabled = count(array_filter($allUsers, fn($u) => (int)($u['is_disabled']??0)===1));
$cUnverified = count(array_filter($allUsers, fn($u) => (int)($u['is_verified']??0)===0));
$cActive   = count(array_filter($allUsers, fn($u) => (int)($u['is_disabled']??0)===0));

// Load admin notes
$notesMap = [];
try {
    $notesQ = $pdo->query("SELECT user_id, note FROM admin_user_notes")->fetchAll();
    foreach($notesQ as $n) $notesMap[$n['user_id']] = $n['note'];
} catch(Exception $e) {}

require_once 'includes/header.php';
renderAdminHeader('Manage Users', 'users');
?>

<style>
.filter-tabs { display:flex; gap:4px; flex-wrap:wrap; margin-bottom:16px; }
.filter-tab { padding:6px 16px; border-radius:20px; font-size:13px; font-weight:500; border:1px solid var(--border); color:var(--text-muted); background:transparent; cursor:pointer; text-decoration:none; transition:all .15s; }
.filter-tab:hover, .filter-tab.active { background:var(--accent); border-color:var(--accent); color:#fff; }
.filter-tab .tab-count { display:inline-block; background:rgba(255,255,255,0.2); border-radius:10px; padding:1px 6px; font-size:11px; margin-left:4px; }
.filter-tab:not(.active) .tab-count { background:var(--border); color:var(--text-muted); }
.note-icon { font-size:14px; cursor:pointer; opacity:0.5; }
.note-icon.has-note { opacity:1; color:#f59e0b; }
</style>

<div class="stats-grid" style="margin-bottom:20px">
  <div class="stat-card"><div class="stat-icon" style="background:rgba(99,102,241,0.15)">👥</div><div class="stat-value"><?= $cTotal ?></div><div class="stat-label">Total Students</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(16,185,129,0.15)">✅</div><div class="stat-value"><?= $cTotal - $cUnverified ?></div><div class="stat-label">Verified</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(239,68,68,0.15)">🚫</div><div class="stat-value"><?= $cDisabled ?></div><div class="stat-label">Disabled</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(245,158,11,0.15)">⚠️</div><div class="stat-value"><?= $cUnverified ?></div><div class="stat-label">Unverified</div></div>
</div>

<div style="display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap;align-items:flex-end">
  <form method="GET" style="flex:1;min-width:200px;display:flex;gap:8px;align-items:center" id="searchForm">
    <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
    <input type="text" name="search" class="form-control" placeholder="Search by name or email…" value="<?= htmlspecialchars($search) ?>" style="flex:1">
    <button type="submit" class="btn btn-primary">Search</button>
    <?php if ($search): ?><a href="users.php?filter=<?= urlencode($filter) ?>" class="btn btn-secondary">Clear</a><?php endif; ?>
  </form>
  <a href="users.php?export=csv<?= $search ? '&search='.urlencode($search) : '' ?>&filter=<?= urlencode($filter) ?>" class="btn btn-secondary">⬇️ Export CSV</a>
</div>

<div class="filter-tabs">
  <?php
  $tabs = [
    ['key'=>'all','label'=>'All','count'=>$cTotal],
    ['key'=>'active','label'=>'Active','count'=>$cActive],
    ['key'=>'disabled','label'=>'Disabled','count'=>$cDisabled],
    ['key'=>'unverified','label'=>'Unverified','count'=>$cUnverified],
    ['key'=>'inactive','label'=>'Inactive 7d+','count'=>'?'],
  ];
  foreach ($tabs as $tab):
    $qs = $search ? '&search='.urlencode($search) : '';
  ?>
  <a href="users.php?filter=<?= $tab['key'] . $qs ?>" class="filter-tab <?= $filter===$tab['key']?'active':'' ?>">
    <?= $tab['label'] ?><span class="tab-count"><?= $tab['count'] ?></span>
  </a>
  <?php endforeach; ?>
</div>

<div class="card">
  <div class="card-header">
    <div class="card-title">👥 Students (<?= count($users) ?>)</div>
  </div>
  <?php if ($users): ?>
  <div class="table-wrapper"><table>
    <thead><tr><th>Student</th><th>Verified</th><th>Status</th><th>Sessions</th><th>Study Time</th><th>Joined</th><th>Note</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($users as $u):
      $dis = !empty($u['is_disabled']);
      $note = $notesMap[$u['id']] ?? '';
      $sysLocked = !empty($u['abuse_locked_until']) && strtotime($u['abuse_locked_until']) > time();
    ?>
    <tr style="<?= $dis?'opacity:0.6':'' ?>">
      <td>
        <div style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($u['name']) ?></div>
        <div style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($u['email']) ?></div>
      </td>
      <td><span class="badge <?= $u['is_verified']?'badge-green':'badge-yellow' ?>"><?= $u['is_verified']?'Verified':'Unverified' ?></span></td>
      <td>
        <?php if($dis): ?><span class="badge badge-red">Disabled</span><?php else: ?><span class="badge badge-cyan">Active</span><?php endif; ?>
        <?php if($sysLocked): ?><br><span class="badge badge-red" title="Locked until <?= date('M j, g:i A', strtotime($u['abuse_locked_until'])) ?>">🔒 System Locked</span><?php endif; ?>
      </td>
      <td><?= $u['sessions'] ?></td>
      <td><?= floor($u['total_mins']/60) ?>h <?= $u['total_mins']%60 ?>m</td>
      <td><?= date('M j, Y',strtotime($u['created_at'])) ?></td>
      <td>
        <span class="note-icon <?= $note?'has-note':'' ?>" onclick="openNote(<?= $u['id'] ?>,`<?= htmlspecialchars(addslashes($u['name'])) ?>`,`<?= htmlspecialchars(addslashes($note)) ?>`)" title="<?= $note ? htmlspecialchars($note) : 'Add admin note' ?>">📝</span>
      </td>
      <td>
        <div style="display:flex;gap:6px;flex-wrap:wrap">
          <a href="user-detail.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-primary">👁 View</a>
          <button class="btn btn-sm btn-secondary" onclick="openDM(<?= $u['id'] ?>,`<?= htmlspecialchars(addslashes($u['name'])) ?>`)">💬 Msg</button>
          <button class="btn btn-sm <?= $u['is_verified']?'btn-secondary':'' ?>" onclick="toggleVerify(<?= $u['id'] ?>,<?= $u['is_verified']?0:1 ?>)"><?= $u['is_verified']?'Unverify':'Verify' ?></button>
          <button class="btn btn-sm <?= $dis?'btn-secondary':'btn-danger' ?>" onclick="toggleDisable(<?= $u['id'] ?>,<?= $dis?0:1 ?>)"><?= $dis?'Enable':'Disable' ?></button>
          <button class="btn btn-sm <?= ($u['active_warnings']??0)>0 ? 'btn-warning' : 'btn-secondary' ?>" onclick="openWarn(<?= $u['id'] ?>,`<?= htmlspecialchars(addslashes($u['name'])) ?>`)">⚠️ Warn<?= ($u['active_warnings']??0)>0 ? ' ✓' : '' ?></button>
          <?php if(($u['active_warnings']??0)>0): ?>
          <button class="btn btn-sm btn-secondary" onclick="dismissWarn(<?= $u['id'] ?>,`<?= htmlspecialchars(addslashes($u['name'])) ?>`)">✕ Clear Warn</button>
          <?php endif; ?>
          <?php if($sysLocked): ?>
          <button class="btn btn-sm btn-warning" onclick="unlockAbuse(<?= $u['id'] ?>,`<?= htmlspecialchars(addslashes($u['name'])) ?>`)">🔓 Unlock</button>
          <?php endif; ?>
          <button class="btn btn-danger btn-sm" onclick="deleteUser(<?= $u['id'] ?>,`<?= htmlspecialchars($u['name'],ENT_QUOTES) ?>`)">🗑</button>
        </div>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>
  <?php else: ?>
  <div class="empty-state"><div class="empty-icon">👥</div><h3>No users found</h3></div>
  <?php endif; ?>
</div>

<!-- Warn Modal -->
<div class="modal-overlay" id="warnModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">⚠️ Issue Warning to <span id="warnUserName"></span></div>
      <button class="modal-close" onclick="closeModal('warnModal')">✕</button>
    </div>
    <p style="font-size:13px;color:var(--text-muted);margin:0 0 10px">This warning will appear as a banner on the user's screen for <strong>24 hours</strong>, then auto-expire. You can dismiss it early from this panel.</p>
    <textarea id="warnMessage" class="form-control" placeholder="Describe the warning reason (e.g. Inappropriate content uploaded…)" style="min-height:120px;width:100%;box-sizing:border-box;resize:vertical"></textarea>
    <div style="display:flex;gap:8px;margin-top:12px;justify-content:flex-end">
      <button class="btn btn-secondary" onclick="closeModal('warnModal')">Cancel</button>
      <button class="btn" style="background:#f59e0b;color:#000;font-weight:700" onclick="sendWarn()">⚠️ Issue Warning</button>
    </div>
  </div>
</div>

<!-- Direct Message Modal -->
<div class="modal-overlay" id="dmModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">💬 Send Notification to <span id="dmUserName"></span></div>
      <button class="modal-close" onclick="closeModal('dmModal')">✕</button>
    </div>
    <textarea id="dmMessage" class="form-control" placeholder="Write your message…" style="min-height:100px;width:100%;box-sizing:border-box;resize:vertical"></textarea>
    <div style="display:flex;gap:8px;margin-top:12px;justify-content:flex-end">
      <button class="btn btn-secondary" onclick="closeModal('dmModal')">Cancel</button>
      <button class="btn btn-primary" onclick="sendDM()">🔔 Send Notification</button>
    </div>
  </div>
</div>

<!-- Admin Note Modal -->
<div class="modal-overlay" id="noteModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">📝 Admin Note for <span id="noteUserName"></span></div>
      <button class="modal-close" onclick="closeModal('noteModal')">✕</button>
    </div>
    <p style="font-size:13px;color:var(--text-muted);margin:0 0 10px">Private note — never visible to the student.</p>
    <textarea id="noteContent" class="form-control" placeholder="e.g. Scholarship student, needs support…" style="min-height:100px;width:100%;box-sizing:border-box;resize:vertical"></textarea>
    <div style="display:flex;gap:8px;margin-top:12px;justify-content:flex-end">
      <button class="btn btn-secondary" onclick="closeModal('noteModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveNote()">💾 Save Note</button>
    </div>
  </div>
</div>

<script>
let dmUserId = 0, noteUserId = 0, warnUserId = 0;

function openModal(id) {
  document.getElementById(id).classList.add('active');
}
function closeModal(id) {
  document.getElementById(id).classList.remove('active');
}

function openDM(id, name) {
  dmUserId = id;
  document.getElementById('dmUserName').textContent = name;
  document.getElementById('dmMessage').value = '';
  openModal('dmModal');
}
function sendDM() {
  const msg = document.getElementById('dmMessage').value.trim();
  if (!msg) return alert('Please write a message.');
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'direct_notify', id:dmUserId, message:msg}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => {
    if (d.success) { closeModal('dmModal'); alert('Notification sent!'); }
  });
}

function openNote(id, name, note) {
  noteUserId = id;
  document.getElementById('noteUserName').textContent = name;
  document.getElementById('noteContent').value = note;
  openModal('noteModal');
}
function saveNote() {
  const note = document.getElementById('noteContent').value.trim();
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'save_note', id:noteUserId, note}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => {
    if (d.success) { closeModal('noteModal'); location.reload(); }
  });
}

function toggleVerify(id, v) {
  if (!confirm(v ? 'Verify this user?' : 'Unverify this user?')) return;
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'toggle', id, verified:v}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => { if (d.success) location.reload(); });
}
function toggleDisable(id, v) {
  if (!confirm(v ? 'Disable this user?' : 'Re-enable this user?')) return;
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'disable', id, disabled:v}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => { if (d.success) location.reload(); });
}
function deleteUser(id, name) {
  if (!confirm('Permanently delete ' + name + '? All data will be lost!')) return;
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'delete', id}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => { if (d.success) location.reload(); });
}

function openWarn(id, name) {
  warnUserId = id;
  document.getElementById('warnUserName').textContent = name;
  document.getElementById('warnMessage').value = '';
  openModal('warnModal');
}
function sendWarn() {
  const msg = document.getElementById('warnMessage').value.trim();
  if (!msg) return alert('Please write a warning message.');
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'warn', id:warnUserId, message:msg}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => {
    if (d.success) {
      closeModal('warnModal');
      alert('Warning issued! It will appear on the user\'s screen for 24 hours.');
      location.reload();
    }
  });
}
function dismissWarn(id, name) {
  if (!confirm('Remove the active warning for ' + name + '?')) return;
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'dismiss_warning', id:id}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => { if (d.success) location.reload(); });
}

function unlockAbuse(id, name) {
  if (!confirm('Remove the system lock for ' + name + '? They will be able to log study sessions again immediately.')) return;
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action:'unlock_abuse', id}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => { if (d.success) location.reload(); });
}

// Close modal when clicking backdrop
document.querySelectorAll('.modal-overlay').forEach(m => {
  m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); });
});
</script>

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