<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
if(!class_exists('PricingEngine'))require_once __DIR__.'/../engine/PricingEngine.php';
require_once __DIR__ . '/../../engine/Logger.php';
require_once __DIR__ . '/../../engine/AIClient.php';
require_once __DIR__ . '/../../engine/UsageMeter.php';

// KERNEL: trace + security
$_partner_ctx = Kernel::handle(['auth' => false, 'public' => true]);

$partner = require_partner();
Logger::setContext('partner_id', (int)$partner['id']);

// Rate limit: configurable per partner (default 10000/day)
$_push_limit = (int)PricingEngine::getSetting('partner_push_limit_day', 200); // push-specific limit (separate from generic)
if (!check_rate_limit('partner_push_' . $partner['id'], $_push_limit, 86400)) {
    Logger::warn('partner_push_rate_exceeded', ['partner_id' => $partner['id'], 'limit' => $_push_limit]);
    json_response(['error' => 'daily_limit_exceeded'], 429);
}
unset($_push_limit);

$b       = json_decode(file_get_contents('php://input'), true) ?? [];
$type    = $b['type'] ?? '';
$content = mb_substr(trim($b['content'] ?? ''), 0, 2000);
if (!$type || !$content) json_response(['error' => 'missing_fields'], 400);

// ── فحص المحتوى بالذكاء الاصطناعي قبل الإرسال الجماعي ────────
$mod_prompt = "أنت مشرف محتوى في منصة مجتمعية سودانية عائلية.\nهل هذا المحتوى مناسب للنشر؟ أجب بـ YES أو NO فقط.\nالمحتوى: $content";

// AI moderation: check content before mass push
// Note: moderation calls are budgeted at 5 tokens each
// Partner daily rate limit (200 pushes) implicitly limits AI calls
// Platform-level guard via getSetting:
$_push_ai_enabled = (int)PricingEngine::getSetting('enable_partner_ai_moderation', 1);
$_mod_prompt = "أنت مشرف محتوى في منصة مجتمعية سودانية عائلية.\nهل هذا المحتوى مناسب للنشر؟ أجب بـ YES أو NO فقط.\nالمحتوى: " . mb_substr($content, 0, 500);
$moderation = $_push_ai_enabled
    ? (($__mod = UsageMeter::wrap((int)($partner['user_id'] ?? 0), 'chat', 'platform', fn() => AIClient::call($_mod_prompt, 'أجب بـ YES أو NO فقط.', 'auto', 5, 0.0, false), ['skip_debit' => true])) && $__mod['ok'] ? ($__mod['result']['text'] ?? 'YES') : 'YES')
    : 'YES'; // skip moderation if feature flag disabled
unset($_mod_prompt);

if (stripos($moderation, 'NO') !== false) {
    error_log('[push/moderation] content rejected for partner_id=' . $partner['id'] . ' content_prefix=' . substr($content, 0, 60));
    json_response(['error' => 'content_rejected', 'message' => 'المحتوى لا يناسب المجتمع — يرجى المراجعة'], 422);
}

// ── إرسال الإشعارات ────────────────────────────────────────────
$sent = 0;

if ($type === 'lesson') {
    $track = $b['track'] ?? $partner['track'] ?? 'foundation';
    $st = db()->prepare('SELECT fcm_token FROM users WHERE learning_track = ? AND fcm_token IS NOT NULL LIMIT 500');
    $st->execute([$track]);
    $tokens = array_column($st->fetchAll(), 'fcm_token');
    foreach (array_slice($tokens, 0, 200) as $t)
        if (send_push($t, '📚 درس جديد من شريكنا', mb_substr($content, 0, 100), ['tag' => 'partner_lesson'])) $sent++;

} elseif ($type === 'health') {
    $tokens = array_column(
        db()->query('SELECT fcm_token FROM users WHERE fcm_token IS NOT NULL LIMIT 500')->fetchAll(),
        'fcm_token'
    );
    foreach (array_slice($tokens, 0, 200) as $t)
        if (send_push($t, '💊 معلومة صحية', mb_substr($content, 0, 100), ['tag' => 'partner_health'])) $sent++;

} elseif ($type === 'pulse') {
    $hood_id = (int)($b['neighborhood_id'] ?? 0);
    $tokens  = $hood_id ? get_hood_tokens($hood_id) : [];
    foreach (array_slice($tokens, 0, 200) as $t)
        if (send_push($t, '📢 إعلان من شريك موثوق', mb_substr($content, 0, 100), ['tag' => 'partner_pulse'])) $sent++;

} else {
    json_response(['error' => 'invalid_type', 'allowed' => ['lesson','health','pulse']], 400);
}

Logger::info('partner_push_sent', [
    'partner_id' => $partner['id'],
    'type'       => $type,
    'sent'       => $sent,
    'moderation' => 'approved',
]);

json_response(['success' => true, 'sent' => $sent, 'moderation' => 'approved', 'trace_id' => Logger::traceId()]);
