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

header('Content-Type: application/json; charset=utf-8');

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['session_token']) || !isset($data['amount'])) {
        throw new Exception('Dados incompletos');
    }
    
    $sessionToken = trim($data['session_token']);
    $amount = floatval($data['amount']);
    
    if (empty($sessionToken)) {
        throw new Exception('Token de sessão vazio');
    }
    
    if ($amount <= 0) {
        throw new Exception('Valor inválido');
    }
    
    $db = Database::getInstance()->getConnection();
    
    // Verificar sessão
    $stmt = $db->prepare("SELECT user_id FROM sessions WHERE session_token = ? AND expires_at > NOW()");
    $stmt->execute([$sessionToken]);
    $session = $stmt->fetch();
    
    if (!$session) {
        throw new Exception('Sessão inválida ou expirada');
    }
    
    $userId = $session['user_id'];
    
    // Verificar se recebeu transaction_id do cliente
    $clientTransactionId = isset($data['transaction_id']) ? trim($data['transaction_id']) : null;
    
    // Se houver transaction_id, verificar se já existe
    if ($clientTransactionId) {
        $stmt = $db->prepare("SELECT id FROM transactions WHERE provider_transaction_id = ?");
        $stmt->execute([$clientTransactionId]);
        if ($stmt->fetch()) {
            throw new Exception('Esta transação já foi processada');
        }
    }
    
    // Adicionar saldo
    $stmt = $db->prepare("UPDATE users SET balance = balance + ?, total_deposited = total_deposited + ? WHERE id = ?");
    $stmt->execute([$amount, $amount, $userId]);
    
    // Buscar novo saldo
    $stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    // Registrar transação com ID único
    $transactionId = 'DEP_' . time() . '_' . $userId . '_' . bin2hex(random_bytes(4));
    $providerTxId = $clientTransactionId ?: ('CHECKOUT_' . time() . '_' . bin2hex(random_bytes(4)));
    
    $stmt = $db->prepare("
        INSERT INTO transactions 
        (user_id, transaction_id, type, amount, status, payment_method, provider_transaction_id, created_at) 
        VALUES (?, ?, 'deposit', ?, 'approved', 'Checkout', ?, NOW())
    ");
    $stmt->execute([$userId, $transactionId, $amount, $providerTxId]);
    
    // Log de auditoria
    $stmt = $db->prepare("INSERT INTO audit_logs (user_id, action, description, ip_address) VALUES (?, 'deposit_approved', ?, ?)");
    $stmt->execute([
        $userId,
        'Depósito de R$ ' . number_format($amount, 2, ',', '.') . ' aprovado via checkout',
        $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    echo json_encode([
        'success' => true,
        'new_balance' => floatval($user['balance']),
        'amount_added' => $amount
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    error_log("Erro PDO add_balance.php: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Erro no banco de dados: ' . $e->getMessage()
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    
    // Log do erro para debug
    error_log("Erro add_balance.php: " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error_detail' => $e->getMessage() // Para debug
    ]);
}
