<?php
/**
 * سودانا v22 — Visitor Ask API
 * HARD RULE: Gateway is the ONLY path. NO AI fallback.
 */
require_once '../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php';  // BRIDGE: unified trace_id
Logger::traceId();                                // generate trace NOW — static, shared by all engines
header('X-Trace-Id: ' . Logger::traceId());       // surface to client for debugging
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

start_secure_session(); // path derived from SITE_URL

if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);

$b = json_decode(file_get_contents('php://input'), true) ?? [];
$q = mb_substr(trim($b['question'] ?? ''), 0, 500);
if (!$q) Kernel::fail('question_required', 'السؤال مطلوب', 400);

$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];

// ── IP Rate Limiting ─────────────────────────────────────────
$ipHash = hash('sha256', $_SERVER['REMOTE_ADDR'] ?? '');
$rlKey  = 'va_ip_' . $ipHash;
try {
    $rlSt = db()->prepare(
        "SELECT COUNT(*) FROM rate_limits WHERE limit_key=? AND window_start > DATE_SUB(NOW(), INTERVAL 1 MINUTE)"
    );
    $rlSt->execute([$rlKey]);
    if ((int)$rlSt->fetchColumn() > 30) {
        http_response_code(429);
        die(json_encode(['error'=>'rate_limit','message'=>'طلبات كثيرة جداً. انتظر دقيقة.']));
    }
    db()->prepare("INSERT INTO rate_limits (limit_key, window_start) VALUES (?, NOW())")
       ->execute([$rlKey]);
} catch (Throwable $rl_ignored) {}

// ── AI Daily Limit Enforcement ─────────────────────────────
if ($u && !empty($u['id'])) {
    if (!class_exists('BillingEngine'))
        require_once __DIR__ . '/../engine/BillingEngine.php';
    $va_plan  = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';
    $va_limit = BillingEngine::checkAILimit((int)$u['id'], $va_plan);
    if (!empty($va_limit['exceeded'])) {
        json_response([
            'error'    => 'daily_limit_exceeded',
            'message'  => "تجاوزت حد {$va_limit['limit']} سؤال/يوم",
            'used'     => $va_limit['used'],
            'limit'    => $va_limit['limit'],
            'cost_sdg' => $va_limit['cost_sdg'] ?? 500,
        ], 429);
    }
}


$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

// ── v22 Engine Load ────────────────────────────────────────────
// Gateway.php already loads all v22 engines via require_once chain:
// Gateway → QueueEngine → EventBus → DecisionEngine → PolicyEngine
//         → ControlEngine → TaskEngine → GrowthBrain
//         → AIOrchestrator → SupportEngines
require_once '../engine/Gateway.php';
require_once '../engine/AIClient.php';
AIClient::reset();

// ── Safety Gate ────────────────────────────────────────────────
if (!SystemHealthMonitor::isSystemHealthy()) {
    json_response([
        'success' => true,
        'answer'  => 'الخدمة مزدحمة مؤقتاً — حاول بعد دقيقة. 🙏',
        'source'  => 'safety_gate',
        'actions' => [],
    ]);
}

try {
    // ── بناء سياق المحادثة من Session ────────────────────────────
    if (!isset($_SESSION['conv_history'])) $_SESSION['conv_history'] = [];
    if (!isset($_SESSION['conv_session_key'])) {
        $_SESSION['conv_session_key'] = bin2hex(random_bytes(16));
    }

    // أضف سياق المستخدم للـ ieResult
    if ($u) {
        $u['conversation_history'] = array_slice($_SESSION['conv_history'], -6);
        // أقرب موعد قادم للمستخدم
        try {
            $nextBook = db()->prepare(
                "SELECT slot_time, service_type FROM bookings
                 WHERE user_id=? AND slot_time>NOW() AND status IN ('confirmed','pending')
                 ORDER BY slot_time ASC LIMIT 1"
            );
            $nextBook->execute([(int)($u['id']??0)]);
            $nb = $nextBook->fetch();
            if ($nb) {
                $u['upcoming_booking'] = $nb['service_type'] . ' — ' .
                    date('l d/m H:i', strtotime($nb['slot_time']));
            }
        } catch (Throwable $ignored) {}
    }

    $result = Gateway::handle([
        'question' => $q,
        'user'     => $u,
        'ip'       => $ip,
        'trace_id' => Logger::traceId(),  // BRIDGE: unified trace across Gateway + ai_usage
    ]);

    // ── حفظ في سجل المحادثة ────────────────────────────────────
    if (!empty($result['answer'])) {
        $_SESSION['conv_history'][] = ['role'=>'user',      'content'=>$q];
        $_SESSION['conv_history'][] = ['role'=>'assistant',  'content'=>mb_substr($result['answer'],0,300)];
        // احتفظ بآخر 20 رسالة فقط
        if (count($_SESSION['conv_history']) > 20) {
            $_SESSION['conv_history'] = array_slice($_SESSION['conv_history'], -20);
        }

        // حفظ في DB لو المستخدم مسجَّل
        if ($u && !empty($u['id'])) {
            try {
                $sessKey = $_SESSION['conv_session_key'];
                db()->prepare(
                    "INSERT INTO conversation_sessions
                     (user_id, session_key, messages, domain, msg_count)
                     VALUES (?, ?, ?, ?, 1)
                     ON DUPLICATE KEY UPDATE
                       messages=VALUES(messages),
                       msg_count=msg_count+1,
                       last_msg_at=NOW()"
                )->execute([
                    (int)$u['id'],
                    $sessKey,
                    json_encode($_SESSION['conv_history'], JSON_UNESCAPED_UNICODE),
                    $result['sector'] ?? 'general',
                ]);
            } catch (Throwable $ignored) {}

            // ScoringAgent: شغِّله كل 10 رسائل
            $msgCount = count($_SESSION['conv_history']);
            if ($msgCount % 10 === 0) {
                try {
                    require_once __DIR__ . '/../engine/ScoringAgent.php';
                    ScoringAgent::score((int)$u['id']);
                } catch (Throwable $ignored) {}
            }
        }
    }

    // ════════════════════════════════════════════════════════════
    // SUDANNA PAY / GOV / INVEST / MERCHANT / INTEGRATION / SUPPORT
    // Post-Gateway enrichment — adds action buttons + direct answers
    // ════════════════════════════════════════════════════════════
    // SUDANNA PAY — Direct Handler in visitor_ask
    // ════════════════════════════════════════════════════════════
    if ($u && in_array($result['sector'] ?? '', ['pay','gov','invest','merchant'])) {
        $sector = $result['sector'] ?? 'pay';
        $intent = $result['flow_type'] ?? '';
    
        // Balance direct answer
        if (in_array($intent, ['sdpay_balance','check_balance'])) {
            require_once __DIR__.'/../engine/SudannaPayEngine.php';
            $dash = SudannaPayEngine::getDashboard((int)$u['id']);
            $bal  = number_format($dash['available'] ?? 0, 0, '.', ',');
            $result['answer'] = "💰 رصيدك في Sudanna Pay: **{$bal} SDG**\n";
            $result['answer'] .= "واردات الشهر: " . number_format($dash['month_in'] ?? 0, 0, '.', ',') . " SDG\n";
            $result['answer'] .= "صادرات الشهر: " . number_format($dash['month_out'] ?? 0, 0, '.', ',') . " SDG";
            $result['action_button'] = ['label'=>'فتح Sudanna Pay','url'=>'/app/pay.php'];
        }
    
        // Zakat calculator
        if ($intent === 'sdpay_zakat' || strpos($q, 'زكاة') !== false) {
            require_once __DIR__.'/../engine/SudannaPayEngine.php';
            $dash = SudannaPayEngine::getDashboard((int)$u['id']);
            $zakat = round(($dash['balance'] ?? 0) * 0.025);
            if ($zakat > 0 && !isset($result['action_button'])) {
                $result['answer'] .= "\n\n💡 زكاة رصيدك التقديرية: **" . number_format($zakat, 0, '.', ',') . " SDG**";
                $result['action_button'] = ['label'=>'أدِّ زكاتك الآن','url'=>'/app/zakat.php'];
            }
        }
    
        // Add action buttons for Pay flows
        $payButtons = [
            'sdpay_transfer'          => ['label'=>'أرسل مال','url'=>'/app/pay-send.php'],
            'sdpay_receive'           => ['label'=>'استقبل مال','url'=>'/app/pay-receive.php'],
            'sdpay_bill_electricity'  => ['label'=>'ادفع الكهرباء','url'=>'/app/pay-bills.php?cat=electricity'],
            'sdpay_bill_water'        => ['label'=>'ادفع المياه','url'=>'/app/pay-bills.php?cat=water'],
            'sdpay_bill_telecom'      => ['label'=>'اشحن الخط','url'=>'/app/pay-bills.php?cat=telecom'],
            'sdpay_bills'             => ['label'=>'دفع الفواتير','url'=>'/app/pay-bills.php'],
            'sdpay_gov_passport'      => ['label'=>'دفع رسوم الجواز','url'=>'/app/pay-gov.php'],
            'sdpay_gov_services'      => ['label'=>'الخدمات الحكومية','url'=>'/app/pay-gov.php'],
            'sdpay_gov_tax'           => ['label'=>'دفع الضريبة','url'=>'/app/pay-gov.php'],
            'invest_projects'         => ['label'=>'استثمر الآن','url'=>'/app/invest/index.php'],
            'invest_mudarabah'        => ['label'=>'مشاريع مضاربة','url'=>'/app/invest/index.php'],
            'sdpay_rosca'             => ['label'=>'الصندوق الرقمي','url'=>'/app/rosca.php'],
            'sdpay_cashin'            => ['label'=>'ابحث عن وكيل','url'=>'/app/pay-agents.php'],
            'sdpay_cashout'           => ['label'=>'ابحث عن وكيل','url'=>'/app/pay-agents.php'],
            'sdpay_agent'             => ['label'=>'خريطة الوكلاء','url'=>'/app/pay-agents.php'],
            'sdpay_gift'              => ['label'=>'ابعث هدية','url'=>'/app/pay-gifts.php'],
            'merchant_pay'            => ['label'=>'ادفع للتاجر','url'=>'/app/pay.php'],
            'merchant_register'       => ['label'=>'سجّل متجرك','url'=>'/app/merchant-portal.php'],
        ];
        if (!isset($result['action_button']) && isset($payButtons[$intent])) {
            $result['action_button'] = $payButtons[$intent];
        }
        if (!isset($result['action_button'])) {
            $result['action_button'] = ['label'=>'فتح Sudanna Pay','url'=>'/app/pay.php'];
        }
    }
    // ════════════════════════════════════════════════════════════
    
    
    // Integration/Developer questions
    if (in_array($result['sector'] ?? '', ['integration','bank'])) {
        if (($result['flow_type'] ?? '') === 'developer_portal') {
            $result['action_button'] = ['label'=>'بوابة المطورين','url'=>'/app/developer.php'];
        } elseif (($result['flow_type'] ?? '') === 'bank_qa') {
            require_once __DIR__.'/../engine/BankAnswerEngine.php';
            $bankResult = BankAnswerEngine::answer($q, 'ar');
            if ($bankResult['matched'] ?? false) {
                $result['answer'] = $bankResult['answer'];
                $result['source'] = 'bank_qa';
            }
        }
    }
    
    
    // Support/Dispute intents
    if (in_array($result['flow_type'] ?? '', ['sdpay_support','sdpay_open_ticket','sdpay_failed','sdpay_dispute','sdpay_suspended'])) {
        if (!isset($result['action_button'])) {
            $result['action_button'] = ['label'=>'فتح تكت دعم','url'=>'/app/support.php'];
        }
    }


    $response = [
        'success'         => true,
        'answer'          => $result['answer'] ?? '',
        'source'          => $result['source'] ?? 'engine',
        'execution_id'    => $result['execution_id'] ?? ('va_' . uniqid('', true)),
        'execution_state' => $result['execution_state'] ?? 'SUCCESS',
        'trace_id'        => Logger::traceId(),  // BRIDGE: trace for debugging
    ];

    foreach (['actions','action_button','cross_links','data','flow','limit_reached','blocked_ai','medical_context','service'] as $key) {
        if (!empty($result[$key])) $response[$key] = $result[$key];
    }

    json_response($response);

} catch (Throwable $e) {
    error_log('[visitor_ask] Gateway error: ' . $e->getMessage());
    json_response([
        'success' => true,
        'answer'  => 'خدمتنا مؤقتاً غير متاحة — حاول بعد دقيقة. 🙏',
        'source'  => 'system_error',
        'actions' => [],
    ]);
}
