<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/SafetyEngine.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/UsageMeter.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$action = $_GET['action'] ?? 'list';
$b      = json_decode(file_get_contents('php://input'), true) ?? [];

if ($action === 'list') {
    $st = db()->prepare('SELECT c.*,u.name AS party_uname FROM contracts c LEFT JOIN users u ON u.id=c.party_user_id WHERE c.created_by=? OR c.party_user_id=? ORDER BY c.id DESC LIMIT 50');
    $st->execute([$u['id'],$u['id']]);
    json_response(['success'=>true,'contracts'=>$st->fetchAll()]);
}

if ($action === 'templates') {
    $tpls = db()->query('SELECT id,name,type,variables FROM contract_templates ORDER BY type')->fetchAll();
    json_response(['success'=>true,'templates'=>$tpls]);
}

if ($action === 'generate') {
    $tpl_id = (int)($b['template_id']??0);
    $vars   = $b['variables'] ?? [];
    $tpl = db()->prepare('SELECT * FROM contract_templates WHERE id=? LIMIT 1'); $tpl->execute([$tpl_id]);
    $template = $tpl->fetch();
    if (!$template) Kernel::fail('template_not_found', '', 404);
    // استبدال المتغيرات
    $body = $template['body_ar'];
    foreach ($vars as $key => $val) $body = str_replace("{{{$key}}}", htmlspecialchars($val), $body);
    // تحسين بـ AI
    // AI_GUARD: daily limit check
    $_ai_plan = $u['plan_key'] ?? 'free';
    $_ai_limit = BillingEngine::checkAILimit((int)$u['id'], $_ai_plan);
    if (!empty($_ai_limit['exceeded'])) {
        json_response(['error'=>'daily_limit_exceeded','message'=>"تجاوزت حد {$_ai_limit['limit']} استدعاء/يوم",'used'=>$_ai_limit['used'],'limit'=>$_ai_limit['limit']], 429);
    }
    unset($_ai_plan, $_ai_limit);
        // Safety: evaluate user input before AI call
    $_se_in = SafetyEngine::evaluateInput($q ?? '', ['endpoint' => 'contracts/index.php']);
    if ($_se_in['action'] === SafetyEngine::BLOCK) {
        Logger::warn('ai_input_blocked', ['endpoint' => 'contracts/index.php']);
        $ai_summary = null;
    } elseif ($_se_in['action'] === SafetyEngine::WARN) {
        $ai_summary = SafetyEngine::emergencyResponse();
    } else {
        $_um_con = UsageMeter::wrap((int)$u['id'], 'chat', 'legal', fn() => AIClient::call("لخّص هذا العقد في 3 نقاط مهمة:\n$body", 'أنت مستشار قانوني مختصر.', 'fast', 150, 0.3, false), ['skip_debit' => true]);
        $ai_summary = $_um_con['ok'] ? ($_um_con['result']['text'] ?? null) : null;
    if ($ai_summary) Logger::aiUsage((int)$u['id'], 'contracts_ai', ['service' => 'legal']);

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

    db()->prepare('INSERT INTO contracts (title,type,party_user_id,party_name,party_email,party_phone,content,ai_summary,template_id,variables,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?)')->execute([$b['title']??$template['name'],$template['type'],$b['party_user_id']??null,$b['party_name']??'',$b['party_email']??'',$b['party_phone']??'',$body,$ai_summary,$tpl_id,json_encode($vars,JSON_UNESCAPED_UNICODE),$u['id']]);
    $cid=(int)db()->lastInsertId();
    json_response(['success'=>true,'contract_id'=>$cid,'content'=>$body,'ai_summary'=>$ai_summary]);
}

if ($action === 'sign') {
    $cid = (int)($b['contract_id']??0);
    db()->prepare("UPDATE contracts SET status='signed',signed_at=NOW() WHERE id=?")->execute([$cid]);
    json_response(['success'=>true,'message'=>'تم توقيع العقد ✅']);
}

Kernel::fail('unknown_action', '', 400);
