<?php
// This script listens for incoming notifications from PayMongo
require_once 'includes/db.php';
// For logging: file_put_contents('webhook_log.txt', file_get_contents('php://input') . "\n\n", FILE_APPEND);

$payload = json_decode(file_get_contents('php://input'), true);
$event_type = $payload['data']['attributes']['type'] ?? '';

// Check if this is a successful payment event
if ($event_type === 'checkout.session.payment.paid') {
    $session_data = $payload['data']['attributes']['data'];
    $user_id = $session_data['attributes']['metadata']['user_id'] ?? null;
    $line_item = $session_data['attributes']['line_items'][0] ?? null;
    
    if ($user_id && $line_item) {
        $amount_paid = floatval($line_item['amount']) / 100; // Convert back from centavos
        $payment_method = $line_item['source']['type'] ?? 'paymongo';
        $reference_num = $line_item['source']['id'] ?? 'N/A';
        
        $conn->begin_transaction();
        try {
            $conn->query("UPDATE users SET wallet_balance = wallet_balance + $amount_paid WHERE id = $user_id");
            $conn->query("INSERT INTO transactions (user_id, transaction_type, amount, payment_method, reference_number, status) VALUES ($user_id, 'Top-up', $amount_paid, '$payment_method', '$reference_num', 'Completed')");
            $conn->commit();
            http_response_code(200); // Send 'OK' back to PayMongo
        } catch (mysqli_sql_exception $e) {
            $conn->rollback();
            http_response_code(500);
        }
    }
}
exit();
?>
