<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/UsageMeter.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/BillingEngine.php'; // AI_GUARD
require_once __DIR__ . '/../../engine/Logger.php';

// KERNEL: trace + optional auth
$_k = Kernel::handle(['auth' => 'optional']);
$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $_GET['action'] ?? (($_SERVER['REQUEST_METHOD'] === 'GET') ? 'list' : 'add');
if (isset($b['action'])) $action = $b['action'];
// الزوار يمكنهم تصفح السوق، الإضافة تحتاج تسجيل دخول
$guest = ['id'=>0,'subscription_tier'=>'free','neighborhood_id'=>0,'user_type'=>'user'];
$u = $action === 'list' ? (current_user() ?: $guest) : require_auth();

// ── قائمة المنتجات ────────────────────────────────────────────
if ($action === 'list') {
    $hood         = (int)($u['neighborhood_id'] ?? 0);
    $cat          = $_GET['cat'] ?? '';
    $allowed_cats = ['food','handmade','services','used','education','fresh'];
    // FIX BUG 10: أضف alias صحيح i. لجميع الأعمدة
    $where  = 'i.status = "active" AND (i.expires_at IS NULL OR i.expires_at > NOW())';
    $params = [];
    if ($hood) { $where .= ' AND i.neighborhood_id = ?'; $params[] = $hood; }
    if ($cat && in_array($cat, $allowed_cats)) { $where .= ' AND i.category = ?'; $params[] = $cat; }
    $st = db()->prepare(
        "SELECT i.*, u.name AS seller_name, u.user_type AS seller_type, u.provider_verified AS seller_verified
         FROM marketplace_items i
         JOIN users u ON u.id = i.seller_id
         WHERE $where ORDER BY i.created_at DESC LIMIT 60"
    );
    $st->execute($params);
    json_response(['success' => true, 'items' => $st->fetchAll()]);
}

// ── إضافة منتج ────────────────────────────────────────────────
if ($action === 'add') {
    if (!check_rate_limit('market_add_' . $u['id'], 10, 3600))
        json_response(['error' => 'rate_limit'], 429);

    $cnt = db()->prepare('SELECT COUNT(*) FROM marketplace_items WHERE seller_id = ? AND status = "active"');
    $cnt->execute([$u['id']]);
    $limit = $u['subscription_tier'] === 'paid' ? 50 : FREE_MARKET_ITEMS;
    if ((int)$cnt->fetchColumn() >= $limit)
        json_response(['error' => 'limit_reached', 'message' => "الحد الأقصى $limit إعلان"], 403);

    $title = mb_substr(trim($b['title'] ?? ''), 0, 300);
    $cat   = $b['category'] ?? 'used';
    if (!$title) json_response(['error' => 'title_required'], 400);
    if (!in_array($cat, ['food','handmade','services','used','education','fresh'])) $cat = 'used';

    // FIX BUG 2: استخدم validate_image_base64() المركزية مع EXIF stripping
    $image_url = null;
    if (!empty($b['image_base64'])) {
        $img_check = validate_and_compress_image_base64($b['image_base64'], MAX_UPLOAD_MB);
        if ($img_check['ok']) {
            $fname = uniqid('item_', true) . '.' . $img_check['ext'];
            if (!is_dir(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);
            file_put_contents(UPLOAD_DIR . $fname, $img_check['data']);
            $image_url = UPLOAD_URL . $fname;
        }
    }

    $desc = mb_substr(trim($b['description'] ?? ''), 0, 1000);
    if (!$desc) {
        $ctx = $image_url ? "صورة المنتج متاحة" : "لا توجد صورة";
    // 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' => 'market/items.php']);
        if ($_se_in['action'] === SafetyEngine::BLOCK) {
            Logger::warn('ai_input_blocked', ['endpoint' => 'market/items.php']);
            $desc = null;
        } elseif ($_se_in['action'] === SafetyEngine::WARN) {
            $desc = SafetyEngine::emergencyResponse();
        } else {
            $_um_mkt = UsageMeter::wrap((int)$u['id'], 'chat', 'market', fn() => AIClient::call("اكتب وصفاً تسويقياً قصيراً (جملتان) لمنتج من فئة $cat بعنوان: $title. $ctx", 'أنت مساعد سوق سوداني ودود. اكتب بالعربية.', 'auto', 100, 0.7, false), ['skip_debit' => true]);
            $desc = $_um_mkt['ok'] ? ($_um_mkt['result']['text'] ?? null) : null;

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

        if ($desc) Logger::aiUsage((int)$u['id'], 'market_ai_desc', ['service'=>'market:description']);
    }

    $price   = isset($b['price']) && $b['price'] !== '' ? (float)$b['price'] : null;
    $hood    = (int)($u['neighborhood_id'] ?? 0);
    $expires = date('Y-m-d H:i:s', time() + 30 * 86400);

    db()->prepare(
        'INSERT INTO marketplace_items
         (seller_id, neighborhood_id, category, title, description, price, price_negotiable, currency, image_url, whatsapp_number, expires_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
    )->execute([
        $u['id'], $hood ?: null, $cat, $title, $desc,
        $price, (int)($b['price_negotiable'] ?? 1),
        in_array($b['currency'] ?? '', ['SDG','USD']) ? $b['currency'] : 'SDG',
        $image_url, mb_substr($b['whatsapp'] ?? '', 0, 20), $expires,
    ]);
    $iid = (int)db()->lastInsertId();
    db()->prepare('UPDATE users SET points_trade = points_trade + 10 WHERE id = ?')->execute([$u['id']]);
    json_response(['success' => true, 'id' => $iid, 'description' => $desc, 'image_url' => $image_url]);
}

// ── اهتمام بمنتج ──────────────────────────────────────────────
if ($action === 'interest') {
    $id = (int)($b['item_id'] ?? 0);
    $st = db()->prepare('SELECT seller_id FROM marketplace_items WHERE id = ? LIMIT 1');
    $st->execute([$id]);
    $item = $st->fetch();
    if (!$item) json_response(['error' => 'not_found'], 404);
    db()->prepare('UPDATE marketplace_items SET interest_count = interest_count + 1 WHERE id = ?')->execute([$id]);
    $fcm = get_user_token($item['seller_id']);
    if ($fcm) send_push($fcm, '🛒 اهتمام بمنتجك!', 'شخص مهتم بمنتجك في السوق', ['tag' => 'market']);
    // إشعار داخلي
    save_notification($item['seller_id'], 'market_interest', 'اهتمام بمنتجك 🛒', 'شخص مهتم بأحد منتجاتك', ['item_id' => (string)$id]);
    json_response(['success' => true]);
}

// ── حذف منتج ──────────────────────────────────────────────────
if ($action === 'delete') {
    $id = (int)($b['id'] ?? 0);
    db()->prepare('UPDATE marketplace_items SET status = "removed" WHERE id = ? AND seller_id = ?')->execute([$id, $u['id']]);
    json_response(['success' => true,
        'trace_id' => Logger::traceId()]);
}

json_response(['error' => 'unknown_action'], 400);
