<?php
/**
 * POST /api/corporate/proposal.php
 * يُولِّد دراسة الشركة بالـ AI
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/SafetyEngine.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once __DIR__ . '/../../engine/UsageMeter.php';
require_once '../../engine/TemplateEngine.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }

// AUTH GATE: corporate proposals require authenticated user
$ctx = Kernel::handle(['auth' => true]);
$_corp_user   = $ctx['user'];
$_corp_uid  = (int)$_corp_user['id'];
$_corp_plan = $_corp_user['plan_key'] ?? 'free';

// AI LIMIT GUARD: corporate proposals are expensive (3000 tokens)
if (!class_exists('BillingEngine')) require_once __DIR__ . '/../../engine/BillingEngine.php';
$_corp_limit = BillingEngine::checkAILimit($_corp_uid, $_corp_plan);
if (!empty($_corp_limit['exceeded'])) {
    http_response_code(429);
    die(json_encode([
        'error'   => 'daily_limit_exceeded',
        'message' => "تجاوزت حد {$_corp_limit['limit']} استدعاء/يوم",
        'used'    => $_corp_limit['used'],
        'limit'   => $_corp_limit['limit'],
    ], JSON_UNESCAPED_UNICODE));
}
unset($_corp_limit, $_corp_plan);

$b   = json_decode(file_get_contents('php://input'), true) ?? [];
$ref = preg_replace('/[^A-Z0-9\-]/', '', $b['ref'] ?? '');
if (!$ref) { http_response_code(400); die(json_encode(['error'=>'ref_required'])); }

try {
    $st = db()->prepare("SELECT * FROM corporate_inquiries WHERE ref_no=? LIMIT 1");
    $st->execute([$ref]);
    $inq = $st->fetch();
    if (!$inq) { http_response_code(404); die(json_encode(['error'=>'inquiry_not_found'])); }

    // Decode JSON fields
    foreach (['services_selected','tech_requirements','operating_states'] as $f) {
        $inq[$f] = json_decode($inq[$f]??'[]', true) ?: [];
    }

    $analysis = CorporateAgent::analyze($inq);
    $prompt   = CorporateAgent::generateProposalPrompt($inq, $analysis);
    $system   = 'أنت مستشار أعمال مؤسسي متخصص. أكتب عروض احترافية ومُقنعة باللغة العربية الفصحى. استخدم أرقاماً وإحصائيات لدعم توصياتك.';

    $t0 = microtime(true);
        // Safety: evaluate user input before AI call
    $_se_in = SafetyEngine::evaluateInput($q ?? '', ['endpoint' => 'corporate/proposal.php']);
    if ($_se_in['action'] === SafetyEngine::BLOCK) {
        Logger::warn('ai_input_blocked', ['endpoint' => 'corporate/proposal.php']);
        $content = null;
    } elseif ($_se_in['action'] === SafetyEngine::WARN) {
        $content = SafetyEngine::emergencyResponse();
    } else {
        $_um_corp = UsageMeter::wrap((int)$_corp_uid, 'chat', 'business', fn() => AIClient::call($prompt, $system, 'auto', 3000, 0.3, false), ['skip_debit' => true]);
        $content = $_um_corp['ok'] ? ($_um_corp['result']['text'] ?? null) : null;

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

    if (!$content) $content = ask_gemini($prompt, $system, [], 3000, 0.5);
    if (!$content) $content = ask_openai($prompt, $system, 3000, 0.5);
    $ms = (int)((microtime(true) - $t0) * 1000);

    if (!$content) {
        http_response_code(500);
        die(json_encode(['error'=>'generation_failed','message'=>'تعذّر توليد العرض — حاول مرة أخرى']));
    }

    // Format as HTML
    $proposalHtml = "<div dir='rtl' style='font-family:Cairo,sans-serif;line-height:1.8;color:#1e293b'>"
        . "<h1 style='color:#073328;border-bottom:2px solid #00d97e;padding-bottom:10px'>"
        . "عرض حلول الشركات — {$inq['org_name']}</h1>"
        . "<p style='color:#64748b;font-size:.85rem'>رقم المرجع: {$ref} | التاريخ: " . date('d/m/Y') . "</p>"
        . "<hr style='border-color:#e2e8f0;margin:16px 0'>"
        . nl2br(htmlspecialchars($content))
        . "</div>";

    // Save proposal
    $proposalRef = 'PRO-' . strtoupper(substr(md5($ref . time()), 0, 8));
    db()->prepare(
        "INSERT INTO corporate_proposals
         (inquiry_id, ref_no, executive_summary_ar, services_breakdown,
          monthly_cost_usd, monthly_cost_sdg, year1_total_sdg,
          roi_percent, breakeven_months, full_proposal_html, ai_model_used, generation_ms, status)
         VALUES (?,?,?,?,?,?,?,?,?,?,'claude',?,'draft')
         ON DUPLICATE KEY UPDATE full_proposal_html=VALUES(full_proposal_html)"
    )->execute([
        $inq['id'], $proposalRef,
        mb_substr($content, 0, 1000),
        json_encode($analysis['breakdown'] ?? []),
        $analysis['monthly_usd'],
        $analysis['monthly_sdg'],
        $analysis['year1_sdg'],
        $analysis['roi_percent'],
        $analysis['breakeven_months'],
        $proposalHtml,
        $ms,
    ]);

    db()->prepare("UPDATE corporate_inquiries SET status='proposal_ready' WHERE ref_no=?")->execute([$ref]);
    Logger::aiUsage($_corp_uid, 'corporate_proposal', [
        'ref_no'  => $ref,
        'model'   => 'claude→gemini→openai',
        'cost_sdg'=> 0, // corporate billing handled separately
        'ms'      => $ms,
    ]);

    echo json_encode([
        'ok'           => true,
        'proposal_ref' => $proposalRef,
        'preview'      => mb_substr($content, 0, 500) . '...',
        'analysis'     => $analysis,
        'generation_ms'=> $ms,
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    Logger::error('corporate_proposal_failed', ['user_id' => $_corp_uid ?? 0, 'error' => $e->getMessage()]);
    http_response_code(500);
    echo json_encode(['error' => 'generation_failed', 'message' => 'تعذّر توليد العرض — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
