<?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'), true);
    
    if (empty($data['service_id'])) {
        throw new Exception("Service ID required");
    }

    $service_id = (int)$data['service_id'];

    $pdo->beginTransaction();

    // Get Service Info
    $stmt = $pdo->prepare("SELECT * FROM mk_services WHERE id = ?");
    $stmt->execute([$service_id]);
    $service = $stmt->fetch();

    if (!$service) throw new Exception("Service not found");

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

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

    // Check Balance
    $stmt = $pdo->prepare("SELECT diamonds FROM users WHERE id = ?");
    $stmt->execute([$buyer_id]);
    $buyer = $stmt->fetch();

    if ($buyer['diamonds'] < $price) {
        throw new Exception("Insufficient diamonds");
    }

    // Get Economy Settings
    $stmt_cfg = $pdo->prepare("SELECT setting_key, setting_value FROM site_config WHERE setting_key IN ('sales_fee_percent', 'marketplace_category_fees')");
    $stmt_cfg->execute();
    $configs = $stmt_cfg->fetchAll(PDO::FETCH_KEY_PAIR);

    $general_fee = (float)($configs['sales_fee_percent'] ?? 10);
    $category_fees = json_decode($configs['marketplace_category_fees'] ?? '{}', true);
    
    // Determine specific fee
    $fee_percent = $general_fee;
    if (isset($category_fees[$service['category']])) {
        $fee_percent = (float)$category_fees[$service['category']];
    }

    $fee = $price * ($fee_percent / 100);
    $seller_net = $price - $fee;

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

    // Add to Seller (with fee deducted)
    $stmt = $pdo->prepare("UPDATE users SET diamonds = diamonds + ? WHERE id = ?");
    $stmt->execute([$seller_net, $seller_id]);

    // Log Transaction (simplified)
    // You might want a transactions table here

    $pdo->commit();

    echo json_encode([
        'status' => 'success',
        'success' => true,
        'message' => 'Service purchased successfully'
    ]);

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