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

// Mock Webhook endpoint to simulate success from Stripe/PayPal
// In a real app, verify signature!

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

try {
    $data = json_decode(file_get_contents("php://input"));
    
    // Simulate: { "event": "payment_success", "user_id": 1, "amount_diamonds": 500 }
    
    if (isset($data->event) && $data->event === 'payment_success' && isset($data->user_id) && isset($data->amount_diamonds)) {
        
        $user_id = (int)$data->user_id;
        $amount = (int)$data->amount_diamonds;
        
        // Add Gems
        $stmt = $pdo->prepare("UPDATE users SET diamonds = diamonds + ? WHERE id = ?");
        $stmt->execute([$amount, $user_id]);
        
        // Log
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'purchase', ?, 'Top-up via Gateway')");
        $stmt->execute([$user_id, $amount]);
        
        echo json_encode(['status' => 'processed']);
    } else {
        echo json_encode(['status' => 'ignored']);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
