<?php
require_once 'includes/db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'User not logged in.']);
    exit();
}
$user_id = $_SESSION['user_id'];

$data = json_decode(file_get_contents('php://input'), true);
$orderID = $data['orderID'] ?? null;
$amount = floatval($data['amount'] ?? 0);

if (!$orderID || $amount <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid data.']);
    exit();
}

// In a real application, you would make a cURL call here to PayPal's API
// to verify the $orderID and confirm the payment status and amount.
// For this simulation, we will assume the payment is valid if it reaches this script.

$conn->begin_transaction();
try {
    // 1. Add funds to user's wallet
    $stmt1 = $conn->prepare("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?");
    $stmt1->bind_param("di", $amount, $user_id);
    $stmt1->execute();

    // 2. Create a transaction record for auditing
    $stmt2 = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, payment_method, reference_number, status) VALUES (?, 'Top-up', ?, 'PayPal', ?, 'Completed')");
    $stmt2->bind_param("ids", $user_id, $amount, $orderID);
    $stmt2->execute();
    
    $conn->commit();
    echo json_encode(['success' => true, 'message' => 'Payment successful and wallet updated.']);
} catch (mysqli_sql_exception $e) {
    $conn->rollback();
    http_response_code(500);
    echo json_encode(['error' => 'Database error. Transaction rolled back.']);
}
?>
