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


$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];
Logger::traceId();
Logger::setContext('user_id', (int)$u['id'] ?? 0);

if (!in_array($u['user_type'] ?? 'user', ['teacher','academic']))
    Kernel::respond(['error' => 'teachers_only', 'message' => 'هذه الميزة للمعلمين الموثّقين فقط'], 403);

$b = json_decode(file_get_contents('php://input'), true) ?? [];
$track  = in_array($b['track'] ?? '', ['foundation','growth','leadership']) ? $b['track'] : 'foundation';
$title  = mb_substr(trim($b['title'] ?? ''), 0, 300);
$content= mb_substr(trim($b['content'] ?? ''), 0, 10000);
if (!$title || !$content) Kernel::respond(['error' => 'missing_fields'], 400);

$quiz_q   = mb_substr(trim($b['quiz_question'] ?? ''), 0, 500);
$quiz_ans = strtoupper(trim($b['quiz_answer'] ?? ''));
$opts     = array_filter(array_map('trim', (array)($b['quiz_options'] ?? [])));

// Gemini يُقيِّم جودة الدرس قبل إرساله للمراجعة
$ai_score    = 0;
$ai_feedback = '';
try {
    // 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($content ?? '', ['endpoint' => 'academy/submit.php']);
    if ($_se_in['action'] === SafetyEngine::BLOCK) {
        Logger::warn('ai_input_blocked', ['endpoint' => 'academy/submit.php']);
        $eval = null;
    } elseif ($_se_in['action'] === SafetyEngine::WARN) {
        $eval = SafetyEngine::emergencyResponse();
    } else {
        $_um_sub = UsageMeter::wrap((int)$u['id'], 'chat', 'education', fn() => AIClient::call("قيّم هذا الدرس التعليمي من 0 إلى 100 واذكر ملاحظة تحسين واحدة. الدرس: {$title}\n\n{$content}", "أنت مقيّم محتوى تعليمي. أجب بـ JSON: {\"score\": 85, \"feedback\": \"ملاحظة\"}", 'auto', 150, 0.3, false), ['skip_debit' => true]);
        $eval = $_um_sub['ok'] ? ($_um_sub['result']['text'] ?? null) : null;

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

    $ev = json_decode(preg_replace('/^```json\s*|\s*```$/', '', trim($eval)), true);
    $ai_score    = max(0, min(100, (int)($ev['score'] ?? 50)));
    $ai_feedback = $ev['feedback'] ?? '';
} catch (Throwable $ignored) {}

db()->prepare(
    'INSERT INTO lesson_submissions (user_id, track, title, content, quiz_question, quiz_options, quiz_answer, ai_score, ai_feedback)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
)->execute([$u['id'], $track, $title, $content,
    $quiz_q ?: null, $opts ? json_encode(array_values($opts), JSON_UNESCAPED_UNICODE) : null,
    $quiz_ans ?: null, $ai_score, $ai_feedback]);

$sub_id = (int)db()->lastInsertId();
save_notification($u['id'], 'lesson_submitted', '📚 تم استلام درسك', "درسك «{$title}» قيد مراجعة فريق سودانا. سيُنشر بعد الموافقة.");
_log_ai('lesson_submit', $u['id']);

Kernel::respond(['success' => true, 'submission_id' => $sub_id, 'ai_score' => $ai_score, 'ai_feedback' => $ai_feedback,
    'message' => 'تم إرسال درسك للمراجعة ✅ سيُنشر بعد الموافقة عليه.']);
