<?php
require_once __DIR__ . '/../includes/config.php';
define('PUSH_SEND_INCLUDED', true);
require_once __DIR__ . '/push-send.php';
requireLogin();

$userId = $_SESSION['user_id'];

// ── Auto-generate smart notifications based on user data ─────────────
function autoTriggerNotifications($pdo, $userId) {
    // Helper: create notification only if not already sent today
    function createNotif($pdo, $userId, $title, $message, $type) {
        $exists = $pdo->prepare("SELECT id FROM notifications WHERE user_id=? AND title=? AND created_at >= CURDATE()");
        $exists->execute([$userId, $title]);
        if ($exists->fetch()) return; // already sent today
        $pdo->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,?)")
            ->execute([$userId, $title, $message, $type]);

        // ── Also send as a Web Push to phone/browser ──────────────────
        try {
            notifyUser($pdo, $userId, [
                'title' => $title,
                'body'  => $message,
                'icon'  => 'https://studytrack.edurx.icu/studytrack/images/studytrack.png',
                'url'   => 'https://studytrack.edurx.icu/studytrack/notifications',
                'tag'   => 'auto-' . md5($title . $userId),
            ]);
        } catch (Throwable $e) { /* silently ignore push errors */ }
    }

    // 1. Streak at risk — no study today AND yesterday was studied
    $q = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=? AND date=CURDATE()");
    $q->execute([$userId]); $todaySessions = (int)$q->fetchColumn();

    $q2 = $pdo->prepare("SELECT COUNT(*) FROM study_streaks WHERE user_id=? AND date=DATE_SUB(CURDATE(),INTERVAL 1 DAY)");
    $q2->execute([$userId]); $hadYesterday = (int)$q2->fetchColumn();

    $curHour = (int)date('G'); // current hour (0-23)
    if ($todaySessions === 0 && $hadYesterday > 0 && $curHour >= 18) {
        // Get current streak count
        $sq = $pdo->prepare("SELECT COUNT(*) FROM study_streaks WHERE user_id=? AND date >= DATE_SUB(CURDATE(),INTERVAL 30 DAY)");
        $sq->execute([$userId]); $streakLen = (int)$sq->fetchColumn();
        createNotif($pdo, $userId, '🔥 Streak at Risk!',
            "You have a {$streakLen}-day streak! Log a study session today to keep it alive.",
            'warning');
    }

    // 2. Weekly target progress — notify if behind by midweek (Wed afternoon)
    $dow = (int)date('N'); // 1=Mon, 7=Sun
    if ($dow >= 3 && $dow <= 5) {
        try { $pdo->exec("ALTER TABLE subjects ADD COLUMN weekly_target_hours DECIMAL(4,1) DEFAULT 0"); } catch(PDOException $e){}
        $weekStart = date('Y-m-d', strtotime('monday this week'));
        $targets = $pdo->prepare("
            SELECT s.name, s.weekly_target_hours,
                   COALESCE(SUM(CASE WHEN ss.date >= ? THEN ss.duration_minutes ELSE 0 END),0) AS week_mins
            FROM subjects s
            LEFT JOIN study_sessions ss ON s.id=ss.subject_id
            WHERE s.user_id=? AND s.weekly_target_hours > 0
            GROUP BY s.id
        ");
        $targets->execute([$weekStart, $userId]);
        $behind = [];
        foreach ($targets->fetchAll() as $t) {
            $targetMins = $t['weekly_target_hours'] * 60;
            $pct = $targetMins > 0 ? ($t['week_mins'] / $targetMins) * 100 : 100;
            $daysLeft = 8 - $dow; // days left in week
            $expectedPct = (($dow - 1) / 7) * 100;
            if ($pct < $expectedPct * 0.6) { // more than 40% behind schedule
                $behind[] = $t['name'];
            }
        }
        if (!empty($behind)) {
            createNotif($pdo, $userId, '📅 Weekly Target Behind',
                'You\'re behind on: ' . implode(', ', array_slice($behind, 0, 3)) . '. Pick up the pace this week!',
                'warning');
        }
    }

    // 3. Milestone notifications — total study hours
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0)/60 FROM study_sessions WHERE user_id=?");
    $q->execute([$userId]); $totalHours = (int)$q->fetchColumn();
    $milestones = [10=>'10 Hours', 50=>'50 Hours', 100=>'100 Hours', 200=>'200 Hours', 500=>'500 Hours'];
    foreach ($milestones as $hrs => $label) {
        if ($totalHours >= $hrs) {
            $mTitle = "🎉 Milestone: $label Studied!";
            $mExists = $pdo->prepare("SELECT id FROM notifications WHERE user_id=? AND title=?");
            $mExists->execute([$userId, $mTitle]);
            if (!$mExists->fetch()) {
                $pdo->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,?)")
                    ->execute([$userId, $mTitle, "Amazing! You've studied a total of $label. Keep up the incredible work! 🚀", 'achievement']);
            }
        }
    }

    // 4. New mark added — show percentage feedback
    $q = $pdo->prepare("SELECT m.marks_obtained, m.total_marks, m.exam_name, s.name as sub_name
        FROM marks m JOIN subjects s ON m.subject_id=s.id
        WHERE m.user_id=? AND m.created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
        ORDER BY m.created_at DESC LIMIT 1");
    $q->execute([$userId]);
    $newMark = $q->fetch();
    if ($newMark) {
        $pct = round(($newMark['marks_obtained'] / $newMark['total_marks']) * 100, 1);
        $msg = $pct >= 75
            ? "🎉 Excellent! You scored {$pct}% in {$newMark['exam_name']} ({$newMark['sub_name']}). Outstanding performance!"
            : ($pct >= 55
                ? "✅ Good effort! You scored {$pct}% in {$newMark['exam_name']}. Keep practising!"
                : "📖 You scored {$pct}% in {$newMark['exam_name']}. Focus more on {$newMark['sub_name']} — you can do it!");
        createNotif($pdo, $userId, '📝 Result Recorded', $msg, $pct >= 75 ? 'success' : ($pct >= 55 ? 'info' : 'warning'));
    }

    // 5. Tasks due today
    $q = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=? AND due_date=CURDATE() AND status!='completed'");
    $q->execute([$userId]); $dueTasks = (int)$q->fetchColumn();
    if ($dueTasks > 0 && $curHour >= 8) {
        createNotif($pdo, $userId, '✅ Tasks Due Today',
            "You have {$dueTasks} task" . ($dueTasks > 1 ? 's' : '') . " due today. Don't forget to complete them!",
            'info');
    }

    // 6. Upcoming reminders (tasks due tomorrow)
    $q = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=? AND due_date=DATE_ADD(CURDATE(),INTERVAL 1 DAY) AND status!='completed'");
    $q->execute([$userId]); $tomorrowTasks = (int)$q->fetchColumn();
    if ($tomorrowTasks > 0 && $curHour >= 18) {
        createNotif($pdo, $userId, '⏰ Tasks Due Tomorrow',
            "{$tomorrowTasks} task" . ($tomorrowTasks > 1 ? 's' : '') . " due tomorrow. Prepare in advance!",
            'reminder');
    }

    // 7. Session logged confirmation — most recent session in last 2 mins
    $q = $pdo->prepare("SELECT ss.duration_minutes, s.name as sub_name
        FROM study_sessions ss JOIN subjects s ON ss.subject_id=s.id
        WHERE ss.user_id=? AND ss.created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
        ORDER BY ss.created_at DESC LIMIT 1");
    $q->execute([$userId]);
    $newSession = $q->fetch();
    if ($newSession) {
        $h = floor($newSession['duration_minutes'] / 60);
        $m = $newSession['duration_minutes'] % 60;
        $dur = ($h > 0 ? "{$h}h " : '') . "{$m}m";
        createNotif($pdo, $userId, '⏱️ Study Session Logged!',
            "Great work! {$dur} of {$newSession['sub_name']} added to your log.",
            'success');
    }
}

// Run auto-trigger on every poll (lightweight, deduped by date)
try {
    autoTriggerNotifications($pdo, $userId);
} catch (Exception $e) {
    // Silently fail — don't block notification loading
}

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

    if ($action === 'read') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND (user_id=? OR user_id IS NULL)")
            ->execute([$id, $userId]);
        jsonResponse(['success' => true]);
    }

    if ($action === 'read_all') {
        $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=? OR user_id IS NULL")
            ->execute([$userId]);
        jsonResponse(['success' => true]);
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM notifications WHERE id=? AND user_id=?")->execute([$id, $userId]);
        jsonResponse(['success' => true]);
    }

    jsonResponse(['success' => false, 'message' => 'Unknown action']);
}

// GET — return notifications list
$stmt = $pdo->prepare("
    SELECT * FROM notifications
    WHERE user_id=? OR user_id IS NULL
    ORDER BY is_read ASC, created_at DESC
    LIMIT 40
");
$stmt->execute([$userId]);
$notifications = $stmt->fetchAll();

$result = array_map(function($n) {
    $diff = time() - strtotime($n['created_at']);
    if ($diff < 60)        $ago = 'just now';
    elseif ($diff < 3600)  $ago = floor($diff/60).'m ago';
    elseif ($diff < 86400) $ago = floor($diff/3600).'h ago';
    else                   $ago = floor($diff/86400).'d ago';
    return [
        'id'       => (int)$n['id'],
        'title'    => $n['title'],
        'message'  => $n['message'],
        'type'     => $n['type'],
        'is_read'  => (bool)$n['is_read'],
        'time_ago' => $ago,
    ];
}, $notifications);

jsonResponse($result);