<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/UsageMeter.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/BillingEngine.php'; // AI_GUARD
require_once __DIR__ . '/../../engine/Logger.php';

// KERNEL: trace + optional auth
$_k = Kernel::handle(['auth' => 'optional']);
$action = $_GET['action'] ?? 'list';
// الزوار يمكنهم رؤية قائمة الدروس، لكن الإكمال يحتاج تسجيل دخول
$u = in_array($action, ['list','detail']) ? (current_user() ?: ['id'=>0,'subscription_tier'=>'free','learning_track'=>'foundation','points_learn'=>0,'user_type'=>'user','rank_title'=>'طالب جديد']) : require_auth();

// ── قائمة الدروس ──────────────────────────────────────────────
if ($action === 'list') {
    $track = $u['learning_track'] ?: 'foundation';
    $st = db()->prepare('SELECT l.id, l.title, l.order_index, l.is_premium, l.track, up.completed_at FROM lessons l LEFT JOIN user_progress up ON up.lesson_id = l.id AND up.user_id = ? WHERE l.track = ? ORDER BY l.order_index');
    $st->execute([$u['id'], $track]);
    $lessons = $st->fetchAll();

    $done_st = db()->prepare('SELECT COUNT(*) FROM user_progress WHERE user_id = ? AND completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)');
    $done_st->execute([$u['id']]);
    $weekly_count = (int)$done_st->fetchColumn();

    Kernel::respond([
        'success'      => true,
        'lessons'      => $lessons,
        'track'        => $track,
        'weekly_done'  => $weekly_count,
        'weekly_limit' => $u['subscription_tier'] === 'paid' ? 999 : FREE_LESSONS_PER_WEEK,
    ]);
}

// ── تفاصيل درس ────────────────────────────────────────────────
if ($action === 'detail') {
    $id = (int)($_GET['id'] ?? 0);
    $st = db()->prepare('SELECT * FROM lessons WHERE id = ? LIMIT 1');
    $st->execute([$id]);
    $lesson = $st->fetch();
    if (!$lesson) Kernel::respond(['error' => 'not_found'], 404);
    if ($lesson['is_premium'] && $u['subscription_tier'] !== 'paid')
        Kernel::respond(['error' => 'premium_required', 'message' => 'هذا الدرس للمشتركين المدفوعين فقط'], 403);
    unset($lesson['quiz_answer']);
    Kernel::respond(['success' => true, 'lesson' => $lesson]);
}

// ── إكمال درس ─────────────────────────────────────────────────
if ($action === 'complete') {
    $b   = json_decode(file_get_contents('php://input'), true) ?? [];
    $id  = (int)($b['lesson_id'] ?? 0);
    $ans = strtoupper(trim($b['answer'] ?? ''));

    $st = db()->prepare('SELECT * FROM lessons WHERE id = ? LIMIT 1');
    $st->execute([$id]);
    $lesson = $st->fetch();
    if (!$lesson) Kernel::respond(['error' => 'not_found'], 404);

    // فحص الحد الأسبوعي
    $weekly = db()->prepare('SELECT COUNT(*) FROM user_progress WHERE user_id = ? AND completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)');
    $weekly->execute([$u['id']]);
    if ($u['subscription_tier'] !== 'paid' && (int)$weekly->fetchColumn() >= FREE_LESSONS_PER_WEEK)
        Kernel::respond(['error' => 'weekly_limit', 'message' => 'وصلت لحد الأسبوع المجاني — أبشر بدرسين أسبوعياً!'], 403);

    $correct = $lesson['quiz_answer'] && $ans === strtoupper($lesson['quiz_answer']);
    $points  = $correct ? 10 : 5;

    // FIX BUG 3: تحقق من الإكمال المسبق قبل منح النقاط
    $already = db()->prepare('SELECT id FROM user_progress WHERE user_id = ? AND lesson_id = ? LIMIT 1');
    $already->execute([$u['id'], $id]);
    $already_done = (bool)$already->fetchColumn();

    if (!$already_done) {
        db()->prepare('INSERT INTO user_progress (user_id, lesson_id, quiz_correct) VALUES (?, ?, ?)')->execute([$u['id'], $id, (int)$correct]);
        db()->prepare('UPDATE users SET points_learn = points_learn + ? WHERE id = ?')->execute([$points, $u['id']]);
    } else {
        // الدرس مكتمل مسبقاً — أعد العرض بدون نقاط إضافية
        $points = 0;
    }

    // حساب الرتبة الجديدة
    $pts_st = db()->prepare('SELECT points_learn, rank_title FROM users WHERE id = ?');
    $pts_st->execute([$u['id']]);
    $pts_row  = $pts_st->fetch();
    $pts      = (int)$pts_row['points_learn'];
    $old_rank = $pts_row['rank_title'];

    $ranks = ['طالب جديد' => 0, 'متعلم نشيط' => 50, 'مبدع سوداني' => 150, 'خبير الحي' => 300, 'قائد المجتمع' => 500, 'حامل المعرفة' => 800];
    $new_rank = $old_rank;
    foreach ($ranks as $title => $min) { if ($pts >= $min) $new_rank = $title; }

    $rank_upgraded = $new_rank !== $old_rank;
    if ($rank_upgraded) {
        db()->prepare('UPDATE users SET rank_title = ? WHERE id = ?')->execute([$new_rank, $u['id']]);
        $fcm = get_user_token((int)$u['id']);
        if ($fcm) send_push($fcm, '🎓 ترقّي جديد!', "تهانينا! أصبحت الآن «$new_rank» 🎉", ['tag' => 'rank']);
    }

    // نصيحة AI عند الإجابة الصحيحة
    $ai_note = '';
    if ($correct && $lesson['title']) {
    // AI_GUARD: daily limit check
    $_ai_plan = $u['plan_key'] ?? 'free';
    $_ai_limit = BillingEngine::checkAILimit((int)$u['id'], $_ai_plan);
    if (!empty($_ai_limit['exceeded'])) {
        Kernel::respond(['error'=>'daily_limit_exceeded','message'=>"تجاوزت حد {$_ai_limit['limit']} استدعاء/يوم",'used'=>$_ai_limit['used'],'limit'=>$_ai_limit['limit']], 429);
    }
    unset($_ai_plan, $_ai_limit);
                // Safety: evaluate user input before AI call
        $_se_in = SafetyEngine::evaluateInput($q ?? '', ['endpoint' => 'academy/lessons.php']);
        if ($_se_in['action'] === SafetyEngine::BLOCK) {
            Logger::warn('ai_input_blocked', ['endpoint' => 'academy/lessons.php']);
            $ai_note = null;
        } elseif ($_se_in['action'] === SafetyEngine::WARN) {
            $ai_note = SafetyEngine::emergencyResponse();
        } else {
            $_um_les = UsageMeter::wrap((int)$u['id'], 'chat', 'education', fn() => AIClient::call("اذكر نصيحة عملية واحدة يستطيع الطالب السوداني تطبيقها فوراً من درس: {$lesson['title']}", 'أنت مدرب تعليمي في منصة سودانا. اجعل نصيحتك عملية وقابلة للتطبيق فوراً.', 'auto', 80, 0.7, false), ['skip_debit' => true]);
            $ai_note = $_um_les['ok'] ? ($_um_les['result']['text'] ?? null) : null;

            // Safety: evaluate AI output
            if ($ai_note) {
                $_se_out = SafetyEngine::evaluateOutput($ai_note, 'medical');
                if ($_se_out['action'] === SafetyEngine::WARN && !empty($_se_out['replace'])) {
                    $ai_note = $_se_out['replace'];
                } elseif ($_se_out['action'] === SafetyEngine::BLOCK) {
                    $ai_note = null;
                }
            }
        }

        Logger::aiUsage((int)$u['id'], 'academy_lesson_note', ['service'=>'academy:note']);
    }

    Kernel::respond([
        'success'       => true,
        'correct'       => $correct,
        'points_earned' => $points,
        'total_points'  => $pts,
        'rank_upgraded' => $rank_upgraded,
        'new_rank'      => $new_rank,
        'ai_note'       => $ai_note,
    ]);
}

Kernel::respond(['error' => 'unknown_action'], 400);
