<?php
session_start();
require_once(__DIR__ . '/config/settings.php');
require_once(__DIR__ . '/config/coin_settings.php'); // Tu config de moneda administrativa

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

if (!isset($_SESSION['logged_in'])) { die(json_encode(['success' => false, 'message' => 'No autorizado'])); }

$orderID = $_POST['order_id'];
$coinsToAdd = (int)$_POST['coins'];
$account = $_SESSION['user_id'];

try {
    $dsn = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "sqlsrv:Server={$db_settings['host']};Database={$db_settings['name']}" : "dblib:host={$db_settings['host']};dbname={$db_settings['name']}";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    
    // 1. Aquí podrías añadir una validación con la API de PayPal para máxima seguridad
    
    // 2. Entregar las monedas usando la configuración del panel administrativo
    $table = $coin_config['coin_table'];
    $column = $coin_config['coin_column'];
    $idCol = $coin_config['coin_id_column'];

    $sql = "UPDATE $table SET $column = $column + :coins WHERE $idCol = :acc";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['coins' => $coinsToAdd, 'acc' => $account]);

    // 3. Opcional: Registrar la transacción en una tabla de logs
    $pdo->prepare("INSERT INTO Web_Donation_Logs (account, order_id, amount_coins, date) VALUES (?, ?, ?, GETDATE())")
        ->execute([$account, $orderID, $coinsToAdd]);

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}