<?php
require_once 'config.php';
if (function_exists('getSetting') && getSetting('sales_enabled','1') !== '1') {
    echo json_encode(['ok'=>false,'error'=>'فروش موقتاً متوقف است. لطفاً چند ساعت دیگر دوباره تلاش کنید.'], JSON_UNESCAPED_UNICODE);
    exit;
}
require_once '_vpn_helpers.php';
require_once 'discount_engine.php';
require_once 'plan_price_helper.php';
header('Content-Type: application/json; charset=utf-8');

function gemaccMiniappBlockedGuard(PDO $pdo, int $userId): void {
    $st = $pdo->prepare("SELECT is_blocked, blocked_reason FROM users WHERE id=? LIMIT 1");
    $st->execute([$userId]);
    $u = $st->fetch(PDO::FETCH_ASSOC);
    if ($u && (int)($u['is_blocked'] ?? 0) === 1) {
        echo json_encode(['ok'=>false,'error'=>'حساب شما داخل ربات مسدود شده است. برای بررسی با پشتیبانی تماس بگیرید.'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['ok'=>false,'error'=>'POST required'], JSON_UNESCAPED_UNICODE);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$userId = (int)($input['user_id'] ?? 0);
$planId = (int)($input['plan_id'] ?? 0);
$discountCode = gemacc_normalize_discount_code($input['discount_code'] ?? '');
$requestId = trim((string)($input['request_id'] ?? ''));

if (!$userId || !$planId) {
    echo json_encode(['ok'=>false,'error'=>'user_id and plan_id required'], JSON_UNESCAPED_UNICODE);
    exit;
}
gemaccMiniappBlockedGuard($pdo, $userId);

try {
    $dupe = gemacc_idempotency_begin($pdo, $userId, $requestId, 'wallet_order');
    if ($dupe) {
        $cached = json_decode((string)($dupe['response_json'] ?? ''), true);
        if (is_array($cached) && !empty($cached)) {
            echo json_encode($cached, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            exit;
        }
        echo json_encode(['ok'=>false,'error'=>'این درخواست قبلاً در حال پردازش است. چند ثانیه دیگر تاریخچه سفارش‌ها را بررسی کنید.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $pdo->beginTransaction();

    $st = $pdo->prepare("SELECT p.*, pc.service_type AS category_service_type, pc.traffic_type AS category_traffic_type, pc.traffic_limit_gb AS category_traffic_limit_gb, pc.months AS category_months FROM plans p LEFT JOIN plan_categories pc ON pc.id=p.category_id WHERE p.id=? AND p.is_active=1 FOR UPDATE");
    $st->execute([$planId]);
    $plan = $st->fetch(PDO::FETCH_ASSOC);
    if (!$plan) throw new RuntimeException('پلن یافت نشد');

    $originalPrice = gemacc_plan_effective_sale_price($plan);
    $discount = ['valid'=>false,'discount_amount'=>0,'final_price'=>$originalPrice];
    if ($discountCode !== '') {
        $discount = gemacc_discount_preview($pdo, $userId, $discountCode, $originalPrice, $planId, 'wallet');
        if (empty($discount['valid'])) throw new RuntimeException($discount['message'] ?? 'کد تخفیف نامعتبر است');
    }
    $finalPrice = max(0, (int)($discount['final_price'] ?? $originalPrice));

    $st = $pdo->prepare("SELECT balance FROM users WHERE id=? FOR UPDATE");
    $st->execute([$userId]);
    $balance = (int)$st->fetchColumn();
    if ($balance < $finalPrice) throw new RuntimeException('موجودی کیف پول کافی نیست');

    $st = $pdo->prepare("UPDATE users SET balance=balance-? WHERE id=? AND balance>=?");
    $st->execute([$finalPrice, $userId, $finalPrice]);
    if (!$st->rowCount()) throw new RuntimeException('موجودی کافی نیست');

    $desc = 'خرید ' . ($plan['title'] ?? 'سرویس');
    if (!empty($discount['valid']) && (int)$discount['discount_amount'] > 0) $desc .= ' با کد تخفیف ' . $discountCode;
    $st = $pdo->prepare("INSERT INTO wallet_transactions(user_id,amount,type,status,payment_method,description) VALUES(?,?,'PURCHASE','COMPLETED','wallet',?)");
    $st->execute([$userId, $finalPrice, $desc]);

    $requestedSeats = max(1, (int)($plan['seats'] ?? $plan['user_count'] ?? 1));
    $trafficType = $plan['traffic_type'] ?: ($plan['category_traffic_type'] ?? 'unlimited');
    $trafficLimitGb = $trafficType === 'limited' ? ($plan['traffic_limit_gb'] ?? $plan['category_traffic_limit_gb'] ?? null) : null;
    $rawSvc = strtolower((string)($plan['protocol'] ?? $plan['category_service_type'] ?? 'openvpn_l2tp')); $serviceType = in_array($rawSvc, ['windscribe','expressvpn','v2ray'], true) ? $rawSvc : 'openvpn_l2tp';
    $st = $pdo->prepare("INSERT INTO orders(user_id,plan_id,category_id,plan_code,plan_title,service_type,duration,months,requested_seats,traffic_type,traffic_limit_gb,price,purchase_price,payment_method,payment_status,delivery_status,status,receipt_text) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,'WALLET','paid','pending','PENDING',?)");
    $receiptMeta = json_encode(['request_id'=>$requestId,'original_price'=>$originalPrice,'discount_code'=>$discountCode,'discount_amount'=>(int)($discount['discount_amount'] ?? 0),'final_price'=>$finalPrice], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $st->execute([$userId,$planId,$plan['category_id'] ?? null,$plan['code'] ?? null,$plan['title'] ?? 'OpenVPN | L2TP',$serviceType,$plan['duration'],(int)($plan['months'] ?? $plan['category_months'] ?? 1),$requestedSeats,$trafficType,$trafficLimitGb,$finalPrice,gemacc_plan_effective_purchase_price($plan),$receiptMeta]);
    $orderId = (int)$pdo->lastInsertId();

    gemacc_discount_apply($pdo, $discount, $userId, $orderId);

    $order = ['id'=>$orderId,'user_id'=>$userId,'plan_id'=>$planId,'category_id'=>$plan['category_id'] ?? null,'duration'=>$plan['duration'],'requested_seats'=>$requestedSeats,'required_accounts'=>$requestedSeats,'service_type'=>$serviceType,'traffic_type'=>$trafficType,'traffic_limit_gb'=>$trafficLimitGb];
    $creds = vpnAllocateCredentials($pdo, $order, $requestedSeats);
    if (!$creds) vpnQueueOrderWithCount($pdo, $order, $requestedSeats);

    $response = [
        'ok'=>true,
        'message'=>$creds ? 'خرید موفق و '.count($creds).' سرویس اختصاصی ارسال شد' : 'خرید موفق؛ موجودی این دسته کافی نیست و سفارش در صف قرار گرفت',
        'order_id'=>$orderId,
        'queued'=>!$creds,
        'original_price'=>$originalPrice,
        'discount_amount'=>(int)($discount['discount_amount'] ?? 0),
        'final_price'=>$finalPrice,
    ];
    gemacc_idempotency_finish($pdo, $userId, $requestId, 'wallet_order', $orderId, $response);
    $pdo->commit();

    if ($creds) {
        $notification = vpnNotifyDeliveryBatch($userId, $creds, $plan, $orderId, $pdo);
        $response['notification'] = $notification;
        if (empty($notification['telegram_sent'])) $response['message'] = 'خرید موفق و سرویس ثبت شد، اما ارسال پیام تلگرام ناموفق بود؛ از فیلترشکن من قابل مشاهده است';
    }
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch(Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $response = ['ok'=>false,'error'=>'خطا: '.$e->getMessage()];
    if ($requestId !== '') {
        try { gemacc_idempotency_finish($pdo, $userId, $requestId, 'wallet_order', null, $response); } catch (Throwable $ignored) {}
    }
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
}
