<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $buyer_id = Auth::check();
    $data = json_decode(file_get_contents("php://input"));
    
    if (!isset($data->service_id)) {
        throw new Exception("Missing service_id");
    }

    $service_id = (int)$data->service_id;

    $pdo->beginTransaction();

    // 1. Get Service Details & Lock
    $stmt = $pdo->prepare("SELECT * FROM services WHERE id = ? FOR UPDATE");
    $stmt->execute([$service_id]);
    $service = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$service || !$service['is_active']) {
        throw new Exception("Service not available");
    }

    $seller_id = $service['seller_id'];
    $price = $service['price'];

    if ($buyer_id == $seller_id) {
        throw new Exception("Cannot buy your own service");
    }

    // 2. Check Buyer Balance
    $stmt = $pdo->prepare("SELECT diamonds FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$buyer_id]);
    $buyer_balance = $stmt->fetchColumn();

    if ($buyer_balance < $price) {
        throw new Exception("Insufficient diamonds");
    }

    // 3. Process Transaction
    // Deduct from Buyer
    $stmt = $pdo->prepare("UPDATE users SET diamonds = diamonds - ? WHERE id = ?");
    $stmt->execute([$price, $buyer_id]);

    // Add to Seller (Platform could take a cut here, but let's do 100% for now)
    $stmt = $pdo->prepare("UPDATE users SET diamonds = diamonds + ? WHERE id = ?");
    $stmt->execute([$price, $seller_id]);

    // 4. Create Order Record
    $sql = "INSERT INTO orders (service_id, buyer_id, seller_id, amount, status) VALUES (?, ?, ?, ?, 'completed')";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$service_id, $buyer_id, $seller_id, $price]);
    $order_id = $pdo->lastInsertId();

    // 5. Log Transactions for history
    // Buyer Log
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, reference_id) VALUES (?, 'content_bought', ?, ?, ?)");
    $stmt->execute([$buyer_id, $price, "Bought service: " . $service['title'], $order_id]);

    // Seller Log
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, reference_id) VALUES (?, 'content_sold', ?, ?, ?)");
    $stmt->execute([$seller_id, $price, "Sold service: " . $service['title'], $order_id]);

    $pdo->commit();

    echo json_encode([
        'status' => 'success',
        'order_id' => $order_id,
        'message' => 'Purchase successful',
        'new_balance' => $buyer_balance - $price
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
