<?php
// POST action=smm_order&api_key=KEY&service_id=ID&link=URL&quantity=QTY
// Place an SMM order

$user_id    = $GLOBALS['api_user_id'];
$api_markup = $GLOBALS['api_markup'];

$service_id = (int)($_POST['service_id'] ?? $_GET['service_id'] ?? 0);
$link       = trim($_POST['link'] ?? $_GET['link'] ?? '');
$quantity   = (int)($_POST['quantity'] ?? $_GET['quantity'] ?? 0);

if (!$service_id || empty($link) || $quantity < 1) {
    api_response(['status' => 'error', 'message' => 'Missing service_id, link, or quantity.'], 400);
}

// Get service details
try {
    $svc_stmt = $pdo->prepare("SELECT * FROM smm_services WHERE id = :id AND status = 1 LIMIT 1");
    $svc_stmt->execute([':id' => $service_id]);
    $service = $svc_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

if (!$service) {
    api_response(['status' => 'error', 'message' => 'Service not found or inactive.'], 404);
}

if ($quantity < (int)$service['min_quantity'] || $quantity > (int)$service['max_quantity']) {
    api_response(['status' => 'error', 'message' => "Quantity must be between {$service['min_quantity']} and {$service['max_quantity']}."], 400);
}

// Calculate charge
$rate = (float)$service['our_rate'];
if ($api_markup > 0) {
    $rate = round($rate * (1 + $api_markup / 100), 2);
}
$charge = round(($rate * $quantity) / 1000, 2);

// Check balance
try {
    $bal_stmt = $pdo->prepare("SELECT main_balance FROM users WHERE id = :uid LIMIT 1");
    $bal_stmt->execute([':uid' => $user_id]);
    $balance = (float)$bal_stmt->fetchColumn();
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Balance check error.'], 500);
}

if ($balance < $charge) {
    api_response(['status' => 'error', 'message' => "Insufficient balance. Need ₦{$charge}, have ₦" . number_format($balance, 2)], 400);
}

// Place order with JAP provider
$jap_path = __DIR__ . '/../../include/JAP.php';
if (!file_exists($jap_path)) {
    api_response(['status' => 'error', 'message' => 'SMM provider not configured.'], 503);
}
require_once $jap_path;

$jap_key = $site_data['jap_api_key'] ?? '';
$jap_url = $site_data['jap_api_url'] ?? 'https://the-owlet.com/api/v2';

if (empty($jap_key)) {
    api_response(['status' => 'error', 'message' => 'SMM provider not configured.'], 503);
}

$jap = new JAP($jap_key, $jap_url);
$result = $jap->placeOrder($service['jap_service_id'], $link, $quantity);

if (!$result['success']) {
    api_response(['status' => 'error', 'message' => 'Provider error: ' . ($result['error'] ?? 'Order failed.')], 500);
}

$jap_order_id = $result['data']['order'] ?? 0;

// Deduct balance and save order
try {
    $pdo->beginTransaction();

    $pdo->prepare("UPDATE users SET main_balance = main_balance - :charge WHERE id = :uid")
        ->execute([':charge' => $charge, ':uid' => $user_id]);

    $pdo->prepare(
        "INSERT INTO smm_orders (user_id, smm_service_id, jap_service_id, jap_order_id, link, quantity, charge, status, created_at)
         VALUES (:uid, :sid, :jid, :joid, :link, :qty, :charge, 'Pending', NOW())"
    )->execute([
        ':uid'    => $user_id,
        ':sid'    => $service['id'],
        ':jid'    => $service['jap_service_id'],
        ':joid'   => $jap_order_id,
        ':link'   => $link,
        ':qty'    => $quantity,
        ':charge' => $charge,
    ]);

    $db_order_id = $pdo->lastInsertId();

    // Log transaction
    $ref = 'SMM_API_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));
    $pdo->prepare(
        "INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata, created_at)
         VALUES (:uid, :ref, 'balance', 'social_boost', :amount, 'NGN', 'successful', :meta, NOW())"
    )->execute([
        ':uid'    => $user_id,
        ':ref'    => $ref,
        ':amount' => $charge,
        ':meta'   => json_encode(['service' => $service['name'], 'quantity' => $quantity, 'via' => 'api']),
    ]);

    $pdo->commit();
} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    api_response(['status' => 'error', 'message' => 'Order saved but DB error: ' . $e->getMessage()], 500);
}

api_response([
    'status'   => 'success',
    'order_id' => (int)$db_order_id,
    'charge'   => number_format($charge, 2, '.', ''),
    'currency' => 'NGN',
    'message'  => 'Order placed successfully.',
]);
