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

$dateFrom = date('Y-m-d', strtotime('monday this week'));
$dateTo   = date('Y-m-d', strtotime('sunday this week'));
$weeklyGoalMins = 35 * 60; // 35 hrs default

// ── AJAX: Send report to one or all users ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    // Helper: build stats for one user and send
    function sendReportForUser($pdo, $userId, $dateFrom, $dateTo, $weeklyGoalMins): array {
        $q = $pdo->prepare("SELECT id, name, email FROM users WHERE id=?");
        $q->execute([$userId]); $user = $q->fetch();
        if (!$user || empty($user['email'])) return ['ok'=>false,'reason'=>'No email'];

        // Total mins & sessions
        $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND date BETWEEN ? AND ?");
        $q->execute([$userId,$dateFrom,$dateTo]); $totalMins = (int)$q->fetchColumn();

        $q = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=? AND date BETWEEN ? AND ?");
        $q->execute([$userId,$dateFrom,$dateTo]); $sessions = (int)$q->fetchColumn();

        // Subject breakdown
        $q = $pdo->prepare("SELECT s.name, SUM(ss.duration_minutes) as mins FROM study_sessions ss JOIN subjects s ON ss.subject_id=s.id WHERE ss.user_id=? AND ss.date BETWEEN ? AND ? GROUP BY ss.subject_id ORDER BY mins DESC");
        $q->execute([$userId,$dateFrom,$dateTo]); $subStats = $q->fetchAll();

        // Streak (last 30 days)
        $q = $pdo->prepare("SELECT COUNT(*) FROM (SELECT DISTINCT date FROM study_sessions WHERE user_id=? AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)) t");
        $q->execute([$userId]); $streakDays = (int)$q->fetchColumn();

        $topSubject = !empty($subStats) ? $subStats[0]['name'] : 'N/A';
        $goalPct    = $weeklyGoalMins > 0 ? min(100, round($totalMins / $weeklyGoalMins * 100)) : 0;
        $subjects   = array_map(fn($s) => ['name'=>$s['name'],'hours'=>round($s['mins']/60,1)], $subStats);

        $sent = sendWeeklyReport($user['email'], $user['name'], [
            'total_hours'    => round($totalMins / 60, 1),
            'total_sessions' => $sessions,
            'top_subject'    => $topSubject,
            'streak_days'    => $streakDays,
            'goal_percent'   => $goalPct,
            'subjects'       => $subjects,
        ]);

        return ['ok' => $sent, 'name' => $user['name'], 'email' => $user['email']];
    }

    // Send to single user
    if ($action === 'send_one') {
        $uid = (int)($_POST['user_id'] ?? 0);
        if (!$uid) jsonResponse(['success'=>false,'message'=>'Invalid user.']);
        $result = sendReportForUser($pdo, $uid, $dateFrom, $dateTo, $weeklyGoalMins);
        if ($result['ok']) {
            jsonResponse(['success'=>true,'message'=>'Report sent to ' . ($result['name'] ?? 'user') . '.']);
        } else {
            jsonResponse(['success'=>false,'message'=>'Failed to send to ' . ($result['name'] ?? 'user') . ': ' . ($result['reason'] ?? 'SMTP error')]);
        }
    }

    // Send to ALL verified active users
    if ($action === 'send_all') {
        $users = $pdo->query("SELECT id FROM users WHERE is_verified=1 AND (is_disabled IS NULL OR is_disabled=0)")->fetchAll();
        $sent = 0; $failed = 0;
        foreach ($users as $u) {
            $r = sendReportForUser($pdo, $u['id'], $dateFrom, $dateTo, $weeklyGoalMins);
            $r['ok'] ? $sent++ : $failed++;
        }
        jsonResponse(['success'=>true,'message'=>"Done! Sent: $sent | Failed: $failed"]);
    }
}

// ── Load user list with this week's stats ────────────────────────────────────
$search = sanitize($_GET['search'] ?? '');
$sql = "SELECT u.id, u.name, u.email, u.is_verified, u.is_disabled,
               COALESCE(SUM(ss.duration_minutes),0) as week_mins,
               COUNT(ss.id) as week_sessions
        FROM users u
        LEFT JOIN study_sessions ss ON ss.user_id=u.id AND ss.date BETWEEN ? AND ?
        WHERE u.is_verified=1 AND (u.is_disabled IS NULL OR u.is_disabled=0)";
$params = [$dateFrom, $dateTo];
if ($search) { $sql .= " AND (u.name LIKE ? OR u.email LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
$sql .= " GROUP BY u.id ORDER BY week_mins DESC";
$usersQ = $pdo->prepare($sql); $usersQ->execute($params); $users = $usersQ->fetchAll();

require_once 'includes/header.php';
renderAdminHeader('Weekly Reports', 'weekly-reports');
?>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px;flex-wrap:wrap">
  <div>
    <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">📊 Weekly Reports</div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:3px">
      Week of <?= date('d M', strtotime($dateFrom)) ?> – <?= date('d M Y', strtotime($dateTo)) ?>
    </div>
  </div>
  <button class="btn btn-primary" onclick="sendAll()" id="sendAllBtn">
    📨 Send to All Users
  </button>
</div>

<!-- Toast notification -->
<div id="toast" style="display:none;position:fixed;top:20px;right:20px;z-index:9999;background:#1e293b;border:1px solid rgba(99,102,241,0.4);border-radius:12px;padding:14px 20px;color:#f8fafc;font-size:14px;max-width:340px;box-shadow:0 8px 32px rgba(0,0,0,0.4)"></div>

<!-- Search -->
<form method="GET" style="display:flex;gap:8px;margin-bottom:20px">
  <input type="text" name="search" class="form-control" placeholder="Search by name or email..." value="<?= htmlspecialchars($search) ?>" style="max-width:320px">
  <button type="submit" class="btn btn-primary">Search</button>
  <?php if ($search): ?><a href="weekly-reports.php" class="btn btn-secondary">Clear</a><?php endif; ?>
</form>

<!-- Stats summary -->
<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"><?= count($users) ?></div>
    <div class="stat-label">Active Students</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(16,185,129,0.15)">⏱️</div>
    <div class="stat-value"><?= round(array_sum(array_column($users,'week_mins')) / 60, 1) ?>h</div>
    <div class="stat-label">Total Study This Week</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(245,158,11,0.15)">📚</div>
    <div class="stat-value"><?= array_sum(array_column($users,'week_sessions')) ?></div>
    <div class="stat-label">Total Sessions</div>
  </div>
</div>

<!-- User table -->
<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>This Week</th>
        <th>Sessions</th>
        <th>Goal</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
    <?php foreach ($users as $u):
      $hrs     = round($u['week_mins'] / 60, 1);
      $goalPct = min(100, round($u['week_mins'] / $weeklyGoalMins * 100));
      $barColor = $goalPct >= 80 ? '#10b981' : ($goalPct >= 50 ? '#f59e0b' : '#ef4444');
    ?>
    <tr>
      <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 style="font-weight:700;color:var(--text-primary)"><?= $hrs ?>h</span>
      </td>
      <td><?= $u['week_sessions'] ?></td>
      <td>
        <div style="display:flex;align-items:center;gap:8px;min-width:120px">
          <div style="flex:1;background:rgba(255,255,255,0.06);border-radius:4px;height:6px;overflow:hidden">
            <div style="background:<?= $barColor ?>;width:<?= $goalPct ?>%;height:100%;border-radius:4px"></div>
          </div>
          <span style="font-size:12px;color:var(--text-muted);white-space:nowrap"><?= $goalPct ?>%</span>
        </div>
      </td>
      <td>
        <button class="btn btn-sm btn-primary" onclick="sendOne(<?= $u['id'] ?>, '<?= htmlspecialchars($u['name'], ENT_QUOTES) ?>')">
          📧 Send
        </button>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>
  <?php else: ?>
  <div class="empty-state"><div class="empty-icon">📊</div><h3>No active students found</h3></div>
  <?php endif; ?>
</div>

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

function showToast(msg, ok = true) {
  const t = document.getElementById('toast');
  t.style.display = 'block';
  t.style.borderColor = ok ? 'rgba(16,185,129,0.4)' : 'rgba(239,68,68,0.4)';
  t.innerHTML = (ok ? '✅ ' : '❌ ') + msg;
  clearTimeout(t._tid);
  t._tid = setTimeout(() => t.style.display = 'none', 4000);
}

function sendOne(userId, name) {
  if (!confirm('Send weekly report to ' + name + '?')) return;
  post({action: 'send_one', user_id: userId}).then(d => showToast(d.message, d.success));
}

function sendAll() {
  const btn = document.getElementById('sendAllBtn');
  if (!confirm('Send weekly report to ALL ' + <?= count($users) ?> + ' active students?')) return;
  btn.disabled = true;
  btn.textContent = '⏳ Sending...';
  post({action: 'send_all'}).then(d => {
    showToast(d.message, d.success);
    btn.disabled = false;
    btn.textContent = '📨 Send to All Users';
  });
}
</script>

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