<?php
/**
 * POST /api/corporate/analyze.php
 * CorporateAgent::analyze() — حساب التكاليف + ROI
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
$_kctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$_user = $_kctx['user']; $_userId = (int)$_user['id'];
require_once '../../engine/CorporateAgent.php';
require_once '../../engine/PricingEngine.php';

header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }

$b   = json_decode(file_get_contents('php://input'), true) ?? [];
$ref = preg_replace('/[^A-Z0-9\-]/', '', $b['ref'] ?? '');

try {
    $inqData = $ref
        ? db()->prepare("SELECT * FROM corporate_inquiries WHERE ref_no=? LIMIT 1")
               ->execute([$ref]) && ($row = db()->prepare("SELECT * FROM corporate_inquiries WHERE ref_no=? LIMIT 1")) && $row->execute([$ref]) ? $row->fetch() : null
        : $b;

    if (!$inqData && $b) $inqData = $b;
    if (!$inqData) { http_response_code(404); die(json_encode(['error'=>'not_found'])); }

    // Decode JSON fields if from DB
    foreach (['services_selected','tech_requirements','operating_states'] as $field) {
        if (isset($inqData[$field]) && is_string($inqData[$field])) {
            $inqData[$field] = json_decode($inqData[$field], true) ?? [];
        }
    }

    $result = CorporateAgent::analyze($inqData);

    // Save estimate to DB
    if ($ref) {
        try {
            db()->prepare("UPDATE corporate_inquiries SET estimated_cost_sdg=?, estimated_roi_pct=? WHERE ref_no=?")
               ->execute([$result['monthly_sdg'], $result['roi_percent'], $ref]);
        } catch (Throwable $ignored) {}
    }

    echo json_encode(['ok' => true, 'analysis' => $result], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    Logger::error('endpoint_error', ['error' => $e->getMessage()]);
    Kernel::fail('server_error', 'خطأ مؤقت — حاول مرة أخرى', 500);
}
