<?php
// POST action=giftcard_buy&api_key=KEY&product_id=ID&quantity=1
// Purchase a gift card

$user_id    = $GLOBALS['api_user_id'];
$api_markup = $GLOBALS['api_markup'];
$product_id = (int)($_POST['product_id'] ?? $_GET['product_id'] ?? 0);
$quantity   = max(1, (int)($_POST['quantity'] ?? $_GET['quantity'] ?? 1));

if (!$product_id) {
    api_response(['status' => 'error', 'message' => 'Missing product_id.'], 400);
}

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

if (!$product) {
    api_response(['status' => 'error', 'message' => 'Product not found or unavailable.'], 404);
}

$price = (float)$product['price'];
if ($api_markup > 0) $price = round($price * (1 + $api_markup / 100), 2);
$total = $price * $quantity;

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

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

// Place order via Reloadly or internal handler
// For now we deduct and record - the fulfillment depends on your gift card provider setup
try {
    $pdo->beginTransaction();

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

    $ref = 'GC_API_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));
    $pdo->prepare(
        "INSERT INTO giftcard_orders (user_id, product_id, product_name, quantity, unit_price, total_amount, status, order_ref, created_at)
         VALUES (:uid, :pid, :name, :qty, :up, :total, 'processing', :ref, NOW())"
    )->execute([
        ':uid'   => $user_id,
        ':pid'   => $product_id,
        ':name'  => $product['product_name'],
        ':qty'   => $quantity,
        ':up'    => $price,
        ':total' => $total,
        ':ref'   => $ref,
    ]);

    $order_id = $pdo->lastInsertId();

    $pdo->prepare(
        "INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata, created_at)
         VALUES (:uid, :ref, 'balance', 'giftcard', :amount, 'NGN', 'successful', :meta, NOW())"
    )->execute([
        ':uid'    => $user_id,
        ':ref'    => $ref,
        ':amount' => $total,
        ':meta'   => json_encode(['product' => $product['product_name'], 'qty' => $quantity, 'via' => 'api']),
    ]);

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

api_response([
    'status'   => 'success',
    'order_id' => (int)$order_id,
    'product'  => $product['product_name'],
    'quantity' => $quantity,
    'total'    => number_format($total, 2, '.', ''),
    'message'  => 'Gift card order placed. Processing...',
]);
