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

$userId = (int)($_GET['id'] ?? 0);
if ($userId <= 0) { header('Location: users.php'); exit; }

// ── Quick actions (AJAX) ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';
    if ($action === 'toggle_verify') {
        $v = (int)$_POST['value'];
        $pdo->prepare("UPDATE users SET is_verified=? WHERE id=?")->execute([$v, $userId]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'toggle_disable') {
        $v = (int)$_POST['value'];
        $pdo->prepare("UPDATE users SET is_disabled=? WHERE id=?")->execute([$v, $userId]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'send_notification') {
        $title = sanitize($_POST['title'] ?? '');
        $msg   = sanitize($_POST['message'] ?? '');
        if ($title && $msg) {
            $pdo->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")
                ->execute([$userId, $title, $msg]);
        }
        jsonResponse(['success'=>true]);
    }
    if ($action === 'warn') {
        $msg = sanitize($_POST['message'] ?? '');
        if ($msg) {
            try {
                $pdo->prepare("UPDATE user_warnings SET dismissed=1 WHERE user_id=? AND dismissed=0 AND expires_at>NOW()")->execute([$userId]);
                $pdo->prepare("INSERT INTO user_warnings (user_id,message,issued_by,expires_at) VALUES (?,?,?,DATE_ADD(NOW(),INTERVAL 24 HOUR))")
                    ->execute([$userId, $msg, $_SESSION['admin_id']]);
            } catch (Exception $e) {}
            try {
                $pdo->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")
                    ->execute([$userId, '⚠️ Admin Warning', $msg]);
            } catch (Exception $e) {}
        }
        jsonResponse(['success'=>true]);
    }
    if ($action === 'delete_session') {
        $sessionId = (int)($_POST['session_id'] ?? 0);
        if ($sessionId > 0) {
            $pdo->prepare("DELETE FROM study_sessions WHERE id=? AND user_id=?")->execute([$sessionId, $userId]);
        }
        jsonResponse(['success'=>true]);
    }
    if ($action === 'save_note') {
        $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([$userId, $note, $note]);
        } catch (Exception $e) {}
        jsonResponse(['success'=>true]);
    }
    jsonResponse(['success'=>false]);
}

// ── Fetch user ────────────────────────────────────────────────────────────────
$user = $pdo->prepare("SELECT * FROM users WHERE id=?")->execute([$userId]) ? null : null;
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) { header('Location: users.php'); exit; }

// ── Stats (single query batch) ────────────────────────────────────────────────
$totalMins    = (int)$pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?")->execute([$userId]) ? 0 : 0;
$q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?"); $q->execute([$userId]); $totalMins = (int)$q->fetchColumn();
$q = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=?"); $q->execute([$userId]); $sessionCount = (int)$q->fetchColumn();
$q = $pdo->prepare("SELECT COUNT(*) FROM subjects WHERE user_id=?"); $q->execute([$userId]); $subjectCount = (int)$q->fetchColumn();
$q = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=?"); $q->execute([$userId]); $taskTotal = (int)$q->fetchColumn();
$q = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=? AND status='completed'"); $q->execute([$userId]); $taskDone = (int)$q->fetchColumn();
$q = $pdo->prepare("SELECT COUNT(*) FROM marks WHERE user_id=?"); $q->execute([$userId]); $markCount = (int)$q->fetchColumn();

// Avg mark %
$avgMark = 0;
try {
    $q = $pdo->prepare("SELECT AVG(marks_obtained/total_marks*100) FROM marks WHERE user_id=?"); $q->execute([$userId]); $avgMark = round((float)$q->fetchColumn(), 1);
} catch (Exception $e) {}

// Achievements
$achieveCount = 0;
try {
    $q = $pdo->prepare("SELECT COUNT(*) FROM user_achievements WHERE user_id=?"); $q->execute([$userId]); $achieveCount = (int)$q->fetchColumn();
} catch (Exception $e) {}

// Study streak (consecutive days)
$streak = 0;
try {
    $days = $pdo->prepare("SELECT DISTINCT date FROM study_sessions WHERE user_id=? ORDER BY date DESC LIMIT 60"); $days->execute([$userId]);
    $dates = array_column($days->fetchAll(PDO::FETCH_ASSOC), 'date');
    if ($dates) {
        $streak = 1; $prev = $dates[0];
        for ($i = 1; $i < count($dates); $i++) {
            $diff = (strtotime($prev) - strtotime($dates[$i])) / 86400;
            if ($diff == 1) { $streak++; $prev = $dates[$i]; } else break;
        }
    }
} catch (Exception $e) {}

// ── Detailed data ─────────────────────────────────────────────────────────────
$q = $pdo->prepare("SELECT ss.*, sub.name as subject_name, sub.color FROM study_sessions ss LEFT JOIN subjects sub ON ss.subject_id=sub.id WHERE ss.user_id=? ORDER BY ss.date DESC LIMIT 15"); $q->execute([$userId]); $sessions = $q->fetchAll(PDO::FETCH_ASSOC);
$q = $pdo->prepare("SELECT t.*, sub.name as subject_name FROM tasks t LEFT JOIN subjects sub ON t.subject_id=sub.id WHERE t.user_id=? ORDER BY t.created_at DESC LIMIT 10"); $q->execute([$userId]); $tasks = $q->fetchAll(PDO::FETCH_ASSOC);
$q = $pdo->prepare("SELECT m.*, sub.name as subject_name FROM marks m LEFT JOIN subjects sub ON m.subject_id=sub.id WHERE m.user_id=? ORDER BY m.exam_date DESC LIMIT 10"); $q->execute([$userId]); $marks = $q->fetchAll(PDO::FETCH_ASSOC);
$q = $pdo->prepare("SELECT s.*, (SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND subject_id=s.id) as mins FROM subjects s WHERE s.user_id=? ORDER BY mins DESC"); $q->execute([$userId, $userId]); $subjects = $q->fetchAll(PDO::FETCH_ASSOC);

// Study per day (last 14 days)
$activityDays = [];
for ($i = 13; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND date=?"); $q->execute([$userId,$d]);
    $activityDays[] = ['date'=>date('M j', strtotime($d)), 'mins'=>(int)$q->fetchColumn()];
}

// Admin note
$adminNote = '';
try {
    $q = $pdo->prepare("SELECT note FROM admin_user_notes WHERE user_id=?"); $q->execute([$userId]); $r = $q->fetch(); $adminNote = $r['note'] ?? '';
} catch (Exception $e) {}

// Active warning
$activeWarning = null;
try {
    $q = $pdo->prepare("SELECT * FROM user_warnings WHERE user_id=? AND dismissed=0 AND expires_at>NOW() ORDER BY id DESC LIMIT 1"); $q->execute([$userId]); $activeWarning = $q->fetch();
} catch (Exception $e) {}

$taskPct   = $taskTotal > 0 ? round($taskDone / $taskTotal * 100) : 0;
$avatarSrc = !empty($user['avatar']) ? '../' . $user['avatar'] : null;
$initials  = strtoupper(substr($user['name'], 0, 1)) . (strpos($user['name'],' ')!==false ? strtoupper(substr(strrchr($user['name'],' '),1,1)) : '');

require_once 'includes/header.php';
renderAdminHeader('User Profile', 'users');
?>

<style>
.profile-hero { display:flex; align-items:center; gap:20px; margin-bottom:24px; flex-wrap:wrap; }
.avatar-circle { width:72px; height:72px; border-radius:50%; background:linear-gradient(135deg,#6366f1,#8b5cf6); display:flex; align-items:center; justify-content:center; font-size:26px; font-weight:700; color:#fff; flex-shrink:0; }
.avatar-circle img { width:72px; height:72px; border-radius:50%; object-fit:cover; }
.profile-name { font-size:22px; font-weight:700; color:var(--text-primary); margin:0 0 2px; }
.profile-email { font-size:14px; color:var(--text-muted); margin:0 0 8px; }
.profile-badges { display:flex; gap:6px; flex-wrap:wrap; }

.quick-actions { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:24px; }

.tab-bar { display:flex; gap:2px; border-bottom:1px solid var(--border); margin-bottom:20px; overflow-x:auto; }
.tab-btn { padding:10px 18px; font-size:13px; font-weight:500; color:var(--text-muted); border:none; background:transparent; cursor:pointer; border-bottom:2px solid transparent; transition:all .15s; white-space:nowrap; }
.tab-btn.active { color:var(--accent); border-bottom-color:var(--accent); }
.tab-pane { display:none; }
.tab-pane.active { display:block; }

.mini-bar-wrap { display:flex; flex-direction:column; gap:10px; }
.mini-bar { display:flex; align-items:center; gap:10px; }
.mini-bar-label { font-size:13px; color:var(--text-secondary); min-width:110px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.mini-bar-track { flex:1; height:8px; background:var(--bg-secondary,rgba(99,102,241,0.08)); border-radius:4px; overflow:hidden; }
.mini-bar-fill { height:100%; border-radius:4px; background:var(--accent); }
.mini-bar-val { font-size:12px; color:var(--text-muted); min-width:36px; text-align:right; }

.activity-chart { display:flex; align-items:flex-end; gap:4px; height:60px; }
.activity-bar-col { flex:1; display:flex; flex-direction:column; align-items:center; gap:3px; }
.activity-bar-fill { width:100%; border-radius:3px 3px 0 0; background:var(--accent); opacity:.8; min-height:2px; }
.activity-bar-label { font-size:9px; color:var(--text-muted); }

.warning-banner { background:rgba(245,158,11,0.1); border:1px solid rgba(245,158,11,0.3); border-radius:10px; padding:12px 16px; margin-bottom:16px; display:flex; align-items:center; gap:10px; }

.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,0.6); z-index:999999; display:none; align-items:center; justify-content:center; }
.modal-overlay.active { display:flex; }
.modal { background:var(--surface); border:1px solid var(--border); border-radius:16px; padding:28px; width:420px; max-width:95vw; }
.modal-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; }
.modal-title { font-size:16px; font-weight:700; }
.modal-close { background:none; border:none; color:var(--text-muted); font-size:18px; cursor:pointer; }
</style>

<!-- Back nav -->
<div style="margin-bottom:16px">
  <a href="users.php" class="btn btn-secondary btn-sm">← Back to Users</a>
</div>

<!-- Profile hero -->
<div class="profile-hero">
  <div class="avatar-circle">
    <?php if ($avatarSrc): ?>
      <img src="<?= htmlspecialchars($avatarSrc) ?>" alt="">
    <?php else: ?>
      <?= htmlspecialchars($initials) ?>
    <?php endif; ?>
  </div>
  <div style="flex:1;min-width:0">
    <div class="profile-name"><?= htmlspecialchars($user['name']) ?></div>
    <div class="profile-email"><?= htmlspecialchars($user['email']) ?></div>
    <div class="profile-badges">
      <?php if ($user['is_verified'] ?? 0): ?>
        <span class="badge badge-green">✅ Verified</span>
      <?php else: ?>
        <span class="badge badge-yellow">⚠️ Unverified</span>
      <?php endif; ?>
      <?php if (!empty($user['is_disabled'])): ?>
        <span class="badge badge-red">🚫 Disabled</span>
      <?php else: ?>
        <span class="badge badge-cyan">🟢 Active</span>
      <?php endif; ?>
      <?php if ($activeWarning): ?>
        <span class="badge badge-yellow">⚠️ Warning Active</span>
      <?php endif; ?>
      <span class="badge badge-purple">ID #<?= $userId ?></span>
    </div>
  </div>
  <div style="text-align:right;font-size:12px;color:var(--text-muted)">
    Joined <?= date('M j, Y', strtotime($user['created_at'])) ?><br>
    <?php if (!empty($user['last_login'])): ?>
    Last seen <?= date('M j', strtotime($user['last_login'])) ?>
    <?php else: ?>
    Never logged in
    <?php endif; ?>
  </div>
</div>

<!-- Active warning banner -->
<?php if ($activeWarning): ?>
<div class="warning-banner">
  <span style="font-size:20px">⚠️</span>
  <div>
    <div style="font-size:13px;font-weight:600;color:#f59e0b">Active Warning</div>
    <div style="font-size:13px;color:var(--text-secondary)"><?= htmlspecialchars($activeWarning['message']) ?> — expires <?= date('M j, H:i', strtotime($activeWarning['expires_at'])) ?></div>
  </div>
</div>
<?php endif; ?>

<!-- Quick actions -->
<div class="quick-actions">
  <?php $isVerified = (int)($user['is_verified'] ?? 0); $isDisabled = (int)(!empty($user['is_disabled'])); ?>
  <button class="btn btn-sm <?= $isVerified ? 'btn-secondary' : 'btn-primary' ?>" onclick="quickAction('toggle_verify', <?= $isVerified ? 0 : 1 ?>, '<?= $isVerified ? 'Unverify' : 'Verify' ?> this user?')">
    <?= $isVerified ? '🔄 Unverify' : '✅ Verify' ?>
  </button>
  <button class="btn btn-sm <?= $isDisabled ? 'btn-secondary' : 'btn-danger' ?>" onclick="quickAction('toggle_disable', <?= $isDisabled ? 0 : 1 ?>, '<?= $isDisabled ? 'Re-enable' : 'Disable' ?> this user?')">
    <?= $isDisabled ? '✅ Enable' : '🚫 Disable' ?>
  </button>
  <button class="btn btn-sm btn-secondary" onclick="openModal('notifModal')">💬 Send Notification</button>
  <button class="btn btn-sm btn-secondary" style="color:#f59e0b;border-color:#f59e0b" onclick="openModal('warnModal')">⚠️ Issue Warning</button>
  <button class="btn btn-sm btn-secondary" onclick="openModal('noteModal')">📝 Admin Note</button>
  <a href="users.php?action=delete&confirm=<?= $userId ?>" class="btn btn-sm btn-danger" onclick="return confirm('Permanently delete this user?')">🗑 Delete</a>
</div>

<!-- Stats row -->
<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"><?= floor($totalMins/60) ?>h <?= $totalMins%60 ?>m</div><div class="stat-label">Total Study</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(6,182,212,0.15)">📚</div><div class="stat-value"><?= $sessionCount ?></div><div class="stat-label">Sessions</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(16,185,129,0.15)">🔥</div><div class="stat-value"><?= $streak ?>d</div><div class="stat-label">Current Streak</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(245,158,11,0.15)">✅</div><div class="stat-value"><?= $taskDone ?>/<?= $taskTotal ?></div><div class="stat-label">Tasks Done</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(139,92,246,0.15)">📊</div><div class="stat-value"><?= $avgMark ?>%</div><div class="stat-label">Avg Mark</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(239,68,68,0.15)">🏆</div><div class="stat-value"><?= $achieveCount ?></div><div class="stat-label">Achievements</div></div>
</div>

<!-- Tabs -->
<div class="card">
  <div class="tab-bar">
    <button class="tab-btn active" onclick="switchTab('overview', this)">📊 Overview</button>
    <button class="tab-btn" onclick="switchTab('sessions', this)">⏱️ Sessions</button>
    <button class="tab-btn" onclick="switchTab('tasks', this)">✅ Tasks</button>
    <button class="tab-btn" onclick="switchTab('marks', this)">📝 Marks</button>
    <button class="tab-btn" onclick="switchTab('subjects', this)">📚 Subjects</button>
    <button class="tab-btn" onclick="switchTab('account', this)">⚙️ Account</button>
  </div>
  <div style="padding:4px 0 8px">

    <!-- OVERVIEW TAB -->
    <div class="tab-pane active" id="tab-overview">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;flex-wrap:wrap">
        <!-- Activity chart -->
        <div>
          <div style="font-size:13px;font-weight:600;color:var(--text-primary);margin-bottom:12px">📅 Study Activity — Last 14 Days</div>
          <?php $maxMins = max(array_column($activityDays,'mins') ?: [1]); ?>
          <div class="activity-chart">
            <?php foreach ($activityDays as $d): $h = $maxMins > 0 ? max(4, round($d['mins']/$maxMins*56)) : 4; ?>
            <div class="activity-bar-col">
              <div class="activity-bar-fill" style="height:<?= $h ?>px" title="<?= $d['mins'] ?> mins"></div>
              <div class="activity-bar-label"><?= date('j', strtotime(str_replace(' ', ' ', $d['date']))) ?></div>
            </div>
            <?php endforeach; ?>
          </div>
          <div style="font-size:11px;color:var(--text-muted);margin-top:6px">Daily study minutes</div>
        </div>
        <!-- Subject breakdown -->
        <div>
          <div style="font-size:13px;font-weight:600;color:var(--text-primary);margin-bottom:12px">📚 Time by Subject</div>
          <?php if ($subjects): $maxSubMins = max(array_column($subjects,'mins') ?: [1]); ?>
          <div class="mini-bar-wrap">
            <?php foreach (array_slice($subjects,0,6) as $s): $pct = $maxSubMins > 0 ? ($s['mins']/$maxSubMins*100) : 0; ?>
            <div class="mini-bar">
              <div class="mini-bar-label"><?= htmlspecialchars($s['name']) ?></div>
              <div class="mini-bar-track"><div class="mini-bar-fill" style="width:<?= $pct ?>%;background:<?= htmlspecialchars($s['color'] ?? '#6366f1') ?>"></div></div>
              <div class="mini-bar-val"><?= floor($s['mins']/60) ?>h</div>
            </div>
            <?php endforeach; ?>
          </div>
          <?php else: ?><div style="color:var(--text-muted);font-size:13px">No subjects yet</div><?php endif; ?>
        </div>
      </div>
      <!-- Task progress -->
      <div style="margin-top:20px">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
          <span style="font-size:13px;font-weight:600">Task Completion</span>
          <span style="font-size:13px;color:var(--text-muted)"><?= $taskDone ?> / <?= $taskTotal ?> (<?= $taskPct ?>%)</span>
        </div>
        <div style="height:10px;background:var(--border);border-radius:5px;overflow:hidden">
          <div style="height:100%;width:<?= $taskPct ?>%;background:linear-gradient(90deg,#10b981,#6366f1);border-radius:5px;transition:width .6s"></div>
        </div>
      </div>
    </div>

    <!-- SESSIONS TAB -->
    <div class="tab-pane" id="tab-sessions">
      <?php if ($sessions): ?>
      <div class="table-wrapper"><table>
        <thead><tr><th>Date</th><th>Subject</th><th>Duration</th><th>Notes</th><th></th></tr></thead>
        <tbody id="sessionsTbody">
        <?php foreach ($sessions as $s): ?>
        <tr id="session-row-<?= $s['id'] ?>">
          <td style="font-size:13px"><?= date('M j, Y', strtotime($s['date'])) ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:6px">
              <div style="width:10px;height:10px;border-radius:50%;background:<?= htmlspecialchars($s['color'] ?? '#6366f1') ?>"></div>
              <span style="font-size:13px"><?= htmlspecialchars($s['subject_name'] ?? '—') ?></span>
            </div>
          </td>
          <td><span class="badge badge-cyan"><?= floor($s['duration_minutes']/60) ?>h <?= $s['duration_minutes']%60 ?>m</span></td>
          <td style="font-size:12px;color:var(--text-muted);max-width:200px"><?= htmlspecialchars(mb_substr($s['notes'] ?? '',0,60)) ?><?= mb_strlen($s['notes'] ?? '')>60?'…':'' ?></td>
          <td style="text-align:right">
            <button class="btn btn-sm" style="background:rgba(239,68,68,0.12);color:#ef4444;font-weight:600" onclick="deleteSession(<?= $s['id'] ?>)" title="Delete session">🗑️</button>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
      <?php else: ?><div class="empty-state" id="sessionsEmptyState"><div class="empty-icon">⏱️</div><h3>No study sessions yet</h3></div><?php endif; ?>
    </div>

    <!-- TASKS TAB -->
    <div class="tab-pane" id="tab-tasks">
      <?php if ($tasks): ?>
      <div class="table-wrapper"><table>
        <thead><tr><th>Task</th><th>Subject</th><th>Priority</th><th>Status</th><th>Due</th></tr></thead>
        <tbody>
        <?php foreach ($tasks as $t):
          $priColor = ['high'=>'badge-red','medium'=>'badge-yellow','low'=>'badge-green'][$t['priority']] ?? 'badge-yellow';
          $stColor  = ['completed'=>'badge-green','in_progress'=>'badge-cyan','pending'=>'badge-yellow'][$t['status']] ?? 'badge-yellow';
        ?>
        <tr>
          <td style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($t['title']) ?></td>
          <td style="font-size:13px;color:var(--text-muted)"><?= htmlspecialchars($t['subject_name'] ?? '—') ?></td>
          <td><span class="badge <?= $priColor ?>"><?= ucfirst($t['priority']) ?></span></td>
          <td><span class="badge <?= $stColor ?>"><?= str_replace('_',' ',ucfirst($t['status'])) ?></span></td>
          <td style="font-size:12px;color:var(--text-muted)"><?= $t['due_date'] ? date('M j',strtotime($t['due_date'])) : '—' ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
      <?php else: ?><div class="empty-state"><div class="empty-icon">✅</div><h3>No tasks yet</h3></div><?php endif; ?>
    </div>

    <!-- MARKS TAB -->
    <div class="tab-pane" id="tab-marks">
      <?php if ($marks): ?>
      <div class="table-wrapper"><table>
        <thead><tr><th>Exam</th><th>Subject</th><th>Score</th><th>Date</th></tr></thead>
        <tbody>
        <?php foreach ($marks as $m):
          $pct = $m['total_marks'] > 0 ? round($m['marks_obtained'] / $m['total_marks'] * 100, 1) : 0;
          $pctColor = $pct >= 75 ? '#10b981' : ($pct >= 50 ? '#f59e0b' : '#ef4444');
        ?>
        <tr>
          <td style="font-weight:500"><?= htmlspecialchars($m['exam_name']) ?></td>
          <td style="font-size:13px;color:var(--text-muted)"><?= htmlspecialchars($m['subject_name'] ?? '—') ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:8px">
              <span style="font-weight:600;color:<?= $pctColor ?>"><?= $pct ?>%</span>
              <span style="font-size:12px;color:var(--text-muted)"><?= $m['marks_obtained'] ?>/<?= $m['total_marks'] ?></span>
            </div>
          </td>
          <td style="font-size:12px;color:var(--text-muted)"><?= date('M j, Y', strtotime($m['exam_date'])) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
      <?php else: ?><div class="empty-state"><div class="empty-icon">📝</div><h3>No marks recorded</h3></div><?php endif; ?>
    </div>

    <!-- SUBJECTS TAB -->
    <div class="tab-pane" id="tab-subjects">
      <?php if ($subjects): ?>
      <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;padding:4px 0">
        <?php foreach ($subjects as $s): ?>
        <div style="border:1px solid var(--border);border-radius:12px;padding:14px;border-left:4px solid <?= htmlspecialchars($s['color'] ?? '#6366f1') ?>">
          <div style="font-weight:600;font-size:14px;margin-bottom:4px"><?= htmlspecialchars($s['name']) ?></div>
          <div style="font-size:13px;color:var(--text-muted)"><?= floor($s['mins']/60) ?>h <?= $s['mins']%60 ?>m studied</div>
          <?php if (!empty($s['target_marks'])): ?>
          <div style="font-size:12px;color:var(--text-muted);margin-top:2px">Target: <?= $s['target_marks'] ?>%</div>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      </div>
      <?php else: ?><div class="empty-state"><div class="empty-icon">📚</div><h3>No subjects added</h3></div><?php endif; ?>
    </div>

    <!-- ACCOUNT TAB -->
    <div class="tab-pane" id="tab-account">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
        <div>
          <div style="font-size:13px;font-weight:600;margin-bottom:12px;color:var(--text-primary)">Account Info</div>
          <table style="width:100%;font-size:13px;border-collapse:collapse">
            <?php $rows = [
              ['User ID', '#'.$user['id']],
              ['Email', $user['email']],
              ['Verified', ($user['is_verified']??0) ? '✅ Yes' : '❌ No'],
              ['Status', !empty($user['is_disabled']) ? '🚫 Disabled' : '🟢 Active'],
              ['Study Goal', ($user['study_goal_minutes']??120).' mins/day'],
              ['Joined', date('M j, Y', strtotime($user['created_at']))],
              ['Last Login', !empty($user['last_login']) ? date('M j, Y H:i', strtotime($user['last_login'])) : 'Never'],
            ]; foreach ($rows as [$k,$v]): ?>
            <tr style="border-bottom:1px solid var(--border)">
              <td style="padding:8px 0;color:var(--text-muted);width:40%"><?= $k ?></td>
              <td style="padding:8px 0;font-weight:500"><?= htmlspecialchars($v) ?></td>
            </tr>
            <?php endforeach; ?>
          </table>
        </div>
        <div>
          <div style="font-size:13px;font-weight:600;margin-bottom:12px;color:var(--text-primary)">📝 Admin Note</div>
          <textarea id="adminNoteText" class="form-control" rows="5" placeholder="Private note — never visible to the student…" style="margin-bottom:10px"><?= htmlspecialchars($adminNote) ?></textarea>
          <button class="btn btn-primary btn-sm" onclick="saveNote()">💾 Save Note</button>
          <div id="noteMsg" style="font-size:12px;color:#10b981;margin-top:8px;display:none">✓ Saved</div>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- Notify Modal -->
<div class="modal-overlay" id="notifModal">
  <div class="modal">
    <div class="modal-header"><div class="modal-title">💬 Send Notification</div><button class="modal-close" onclick="closeModal('notifModal')">✕</button></div>
    <div class="form-group"><label class="form-label">Title</label><input type="text" id="notifTitle" class="form-control" placeholder="Notification title"></div>
    <div class="form-group"><label class="form-label">Message</label><textarea id="notifMsg2" class="form-control" rows="3" placeholder="Message…"></textarea></div>
    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
      <button class="btn btn-secondary" onclick="closeModal('notifModal')">Cancel</button>
      <button class="btn btn-primary" onclick="sendNotif()">🔔 Send</button>
    </div>
  </div>
</div>

<!-- Warn Modal -->
<div class="modal-overlay" id="warnModal">
  <div class="modal">
    <div class="modal-header"><div class="modal-title">⚠️ Issue Warning</div><button class="modal-close" onclick="closeModal('warnModal')">✕</button></div>
    <p style="font-size:13px;color:var(--text-muted);margin:0 0 12px">Appears as a banner on the user's screen for 24 hours.</p>
    <textarea id="warnMsg" class="form-control" rows="3" placeholder="Warning reason…"></textarea>
    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
      <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>

<!-- Note Modal (same page inline, but kept for consistency) -->
<div class="modal-overlay" id="noteModal">
  <div class="modal">
    <div class="modal-header"><div class="modal-title">📝 Admin Note</div><button class="modal-close" onclick="closeModal('noteModal')">✕</button></div>
    <p style="font-size:13px;color:var(--text-muted);margin:0 0 12px">Private note — never visible to the student.</p>
    <textarea id="noteModalText" class="form-control" rows="4" placeholder="e.g. Scholarship student, needs support…"><?= htmlspecialchars($adminNote) ?></textarea>
    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
      <button class="btn btn-secondary" onclick="closeModal('noteModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveNoteModal()">💾 Save Note</button>
    </div>
  </div>
</div>

<script>
function openModal(id)  { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }
document.querySelectorAll('.modal-overlay').forEach(m => m.addEventListener('click', e => { if(e.target===m) m.classList.remove('active'); }));

function switchTab(name, btn) {
  document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.getElementById('tab-'+name).classList.add('active');
  btn.classList.add('active');
}

function post(data) {
  return fetch(window.location.href, {
    method:'POST', headers:{'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'},
    body: new URLSearchParams(data)
  }).then(r=>r.json());
}

function quickAction(action, value, msg) {
  if (!confirm(msg)) return;
  post({action, value}).then(d => { if(d.success) location.reload(); });
}

function sendNotif() {
  const title = document.getElementById('notifTitle').value.trim();
  const msg   = document.getElementById('notifMsg2').value.trim();
  if (!title || !msg) return alert('Title and message required.');
  post({action:'send_notification', title, message:msg}).then(d => {
    if(d.success) { closeModal('notifModal'); alert('Notification sent!'); }
  });
}

function sendWarn() {
  const msg = document.getElementById('warnMsg').value.trim();
  if (!msg) return alert('Please write a warning message.');
  post({action:'warn', message:msg}).then(d => {
    if(d.success) { closeModal('warnModal'); alert('Warning issued!'); location.reload(); }
  });
}

function deleteSession(sessionId) {
  if (!confirm('Delete this study session? This cannot be undone.')) return;
  post({action:'delete_session', session_id: sessionId}).then(d => {
    if (d.success) {
      const row = document.getElementById('session-row-' + sessionId);
      if (row) row.remove();
      const tbody = document.getElementById('sessionsTbody');
      if (tbody && tbody.children.length === 0) location.reload();
    } else {
      alert('Failed to delete session.');
    }
  });
}

function saveNote() {
  const note = document.getElementById('adminNoteText').value.trim();
  post({action:'save_note', note}).then(d => {
    if(d.success) { const m=document.getElementById('noteMsg'); m.style.display='block'; setTimeout(()=>m.style.display='none',2000); }
  });
}
function saveNoteModal() {
  const note = document.getElementById('noteModalText').value.trim();
  document.getElementById('adminNoteText').value = note;
  post({action:'save_note', note}).then(d => { if(d.success) { closeModal('noteModal'); } });
}
</script>

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