<?php
/**
 * GET /api/user/context.php
 * سياق المستخدم الكامل للمساعد الشخصي
 * v23.1: يقرأ الحدود من PricingEngine ديناميكياً + أرقام الاستخدام الحقيقية
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/Logger.php';
require_once __DIR__.'/../../engine/PricingEngine.php';
require_once __DIR__.'/../../engine/UsageMeter.php';

$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];
if (!$u) { http_response_code(401); die(json_encode(['error'=>'unauthorized'])); }

$uid     = (int)$u['id'];
$planKey = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';

// ── حدود الباقة من PricingEngine ───────────────────────────────
$pricing = PricingEngine::getAll();
$planData = $pricing['plans'][$planKey] ?? $pricing['plans']['free'];

// ── إحصائيات الاستخدام الحقيقية ─────────────────────────────────
$usage = UsageMeter::getUserSummary($uid, 30);

$ctx = [
    'user' => [
        'id'         => $uid,
        'name'       => $u['name'] ?? '',
        'first_name' => explode(' ', trim($u['name'] ?? 'مستخدم'))[0],
        'plan'       => $planKey,
        'plan_label' => ['free'=>'مجاني','plus'=>'Plus','pro'=>'Pro','corp'=>'شركات'][$planKey] ?? $planKey,
        'points'     => (int)($u['achievement_points'] ?? 0),
        'avatar'     => mb_substr($u['name'] ?? 'م', 0, 1),
    ],
    'limits' => [
        'ai_daily'        => (int)($planData['ai_day'] ?? 20),
        'bookings_daily'  => (int)($planData['bookings_day'] ?? 2),
        'doc_credit_sdg'  => (int)($planData['doc_credit_sdg'] ?? 0),
        'plan_price_sdg'  => (int)($planData['sdg'] ?? 0),
    ],
    'usage' => [
        'ai_today'         => $usage['ai_today'],
        'tokens_30d'       => $usage['tokens_period'],
        'spent_30d_sdg'    => $usage['spent_sdg'],
        'ai_pct_used'      => $planData['ai_day'] > 0
                              ? min(100, round(($usage['ai_today'] / $planData['ai_day']) * 100))
                              : 0,
    ],
    'wallet'        => ['balance' => 0, 'credit_remaining' => 0, 'credit_pct' => 100],
    'upcoming'      => [],
    'recent'        => [],
    'notifications' => ['unread' => 0, 'items' => []],
    'stats'         => ['ai_today' => $usage['ai_today'], 'bookings_total' => 0, 'docs_issued' => 0],
    'last_conversation' => null,
    'nudge'         => null,
    'alerts'        => [],
];

try {
    // Wallet balance
    $w = db()->prepare("SELECT balance_sdg AS balance FROM wallet WHERE user_id=? LIMIT 1");
    $w->execute([$uid]);
    $ctx['wallet']['balance'] = (int)($w->fetchColumn() ?? 0);

    // Subscription credit
    $cr = db()->prepare(
        "SELECT remaining_sdg, monthly_credit FROM subscription_credits
         WHERE user_id=? AND period_month=MONTH(NOW()) AND period_year=YEAR(NOW()) LIMIT 1"
    );
    $cr->execute([$uid]);
    $crRow = $cr->fetch();
    if ($crRow) {
        $ctx['wallet']['credit_remaining'] = (int)$crRow['remaining_sdg'];
        $monthly = (int)$crRow['monthly_credit'];
        $ctx['wallet']['credit_pct'] = $monthly > 0
            ? round(($crRow['remaining_sdg'] / $monthly) * 100)
            : 100;
    }

    // ── تنبيهات تلقائية ───────────────────────────────────────────
    $aiPct = $ctx['usage']['ai_pct_used'];
    $warnPct = (int)PricingEngine::getSetting('ai_warn_threshold_pct', 80);
    if ($aiPct >= 100) {
        $ctx['alerts'][] = ['type'=>'limit_exceeded', 'severity'=>'critical',
            'message'=>'تجاوزت حدك اليومي من الأسئلة. كل سؤال إضافي = ' .
                      number_format(PricingEngine::getSetting('ai_overage_charge_sdg', 500)) . ' SDG'];
    } elseif ($aiPct >= $warnPct) {
        $ctx['alerts'][] = ['type'=>'limit_warn', 'severity'=>'warning',
            'message'=>"استخدمت $aiPct% من حدك اليومي ({$ctx['usage']['ai_today']}/{$ctx['limits']['ai_daily']})"];
    }

    $creditPct = $ctx['wallet']['credit_pct'];
    $lowPct = (int)PricingEngine::getSetting('credit_low_threshold_pct', 20);
    $critPct = (int)PricingEngine::getSetting('credit_critical_threshold_pct', 5);
    if ($crRow) {
        if ($creditPct <= $critPct) {
            $ctx['alerts'][] = ['type'=>'credit_critical', 'severity'=>'critical',
                'message'=>'رصيد الوثائق الشهري شبه نافد ('.number_format($ctx['wallet']['credit_remaining']).' SDG)'];
        } elseif ($creditPct <= $lowPct) {
            $ctx['alerts'][] = ['type'=>'credit_low', 'severity'=>'warning',
                'message'=>"رصيد الوثائق منخفض ($creditPct% متبقي)"];
        }
    }

    // Upcoming bookings
    $uq = db()->prepare(
        "SELECT b.id, b.slot_time, b.service_type,
                COALESCE(p.name,'مزود الخدمة') as provider_name
         FROM bookings b LEFT JOIN users p ON b.provider_id=p.id
         WHERE b.user_id=? AND b.slot_time>NOW() AND b.status IN ('confirmed','pending')
         ORDER BY b.slot_time ASC LIMIT 3"
    );
    $uq->execute([$uid]);
    $ctx['upcoming'] = $uq->fetchAll();

    // Recent activity
    $rc = db()->prepare(
        "SELECT sector, LEFT(question,60) as question, created_at
         FROM execution_log WHERE user_id=? ORDER BY created_at DESC LIMIT 5"
    );
    $rc->execute([$uid]);
    $ctx['recent'] = $rc->fetchAll();

    // Notifications
    $nt = db()->prepare(
        "SELECT id, type, title, body, created_at FROM notifications
         WHERE user_id=? AND is_read=0 ORDER BY created_at DESC LIMIT 5"
    );
    $nt->execute([$uid]);
    $ntItems = $nt->fetchAll();
    $ctx['notifications'] = ['unread' => count($ntItems), 'items' => $ntItems];

    // Total bookings
    $bk = db()->prepare("SELECT COUNT(*) FROM bookings WHERE user_id=?");
    $bk->execute([$uid]);
    $ctx['stats']['bookings_total'] = (int)$bk->fetchColumn();

    // Total documents issued (from ai_usage where event_type=document)
    try {
        $dc = db()->prepare("SELECT COUNT(*) FROM ai_usage WHERE user_id=? AND event_type='document'");
        $dc->execute([$uid]);
        $ctx['stats']['docs_issued'] = (int)$dc->fetchColumn();
    } catch (Throwable $ignored) {}

    // Last conversation
    try {
        $lc = db()->prepare(
            "SELECT domain, msg_count, last_msg_at FROM conversation_sessions
             WHERE user_id=? ORDER BY last_msg_at DESC LIMIT 1"
        );
        $lc->execute([$uid]);
        $ctx['last_conversation'] = $lc->fetch() ?: null;
    } catch (Throwable $ignored) {}

    // Provider potential nudge
    try {
        $nd = db()->prepare(
            "SELECT detected_domain, confidence_score, stage, nudge_response
             FROM provider_potential WHERE user_id=? LIMIT 1"
        );
        $nd->execute([$uid]);
        $ndRow = $nd->fetch();
        if ($ndRow && (float)$ndRow['confidence_score'] >= 0.6
            && $ndRow['nudge_response'] !== 'negative') {
            $ctx['nudge'] = $ndRow;
        }
    } catch (Throwable $ignored) {}

} catch (Throwable $e) {
    error_log("[user/context] " . $e->getMessage());
}

echo json_encode($ctx, JSON_UNESCAPED_UNICODE);
