<?php
require_once '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['transaction_id'])) {
        throw new Exception('Dados incompletos');
    }
    
    $sessionToken = $data['session_token'];
    $transactionId = $data['transaction_id'];
    
    $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'];
    
    // Buscar transação
    $stmt = $db->prepare("
        SELECT id, provider_transaction_id, amount, status 
        FROM transactions 
        WHERE transaction_id = ? AND user_id = ?
    ");
    $stmt->execute([$transactionId, $userId]);
    $transaction = $stmt->fetch();
    
    if (!$transaction) {
        throw new Exception('Transação não encontrada');
    }
    
    // Se já foi aprovada, retornar sucesso
    if ($transaction['status'] === 'approved') {
        echo json_encode([
            'success' => true,
            'status' => 'approved',
            'message' => 'Pagamento já foi aprovado'
        ]);
        exit;
    }
    
    // Verificar status na SeedPay
    $providerTransactionId = $transaction['provider_transaction_id'];
    
    if ($providerTransactionId) {
        $authString = SEEDPAY_PUBLIC_KEY . ':' . SEEDPAY_SECRET_KEY;
        $authToken = base64_encode($authString);
        
        $ch = curl_init(SEEDPAY_API_URL . '/' . $providerTransactionId);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . $authToken
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode === 200) {
            $seedpayResponse = json_decode($response, true);
            
            if ($seedpayResponse && isset($seedpayResponse['status'])) {
                $paymentStatus = $seedpayResponse['status'];
                
                // Se aprovado, creditar saldo
                if ($paymentStatus === 'approved' || $paymentStatus === 'paid') {
                    // Atualizar transação
                    $stmt = $db->prepare("UPDATE transactions SET status = 'approved', approved_at = NOW() WHERE id = ?");
                    $stmt->execute([$transaction['id']]);
                    
                    // Creditar saldo
                    $amount = $transaction['amount'];
                    $stmt = $db->prepare("UPDATE users SET balance = balance + ?, total_deposited = total_deposited + ? WHERE id = ?");
                    $stmt->execute([$amount, $amount, $userId]);
                    
                    // 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',
                        $_SERVER['REMOTE_ADDR'] ?? 'unknown'
                    ]);
                    
                    // Buscar saldo atualizado
                    $stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
                    $stmt->execute([$userId]);
                    $user = $stmt->fetch();
                    
                    echo json_encode([
                        'success' => true,
                        'status' => 'approved',
                        'message' => 'Pagamento aprovado! Saldo creditado.',
                        'new_balance' => floatval($user['balance'])
                    ]);
                    exit;
                }
            }
        }
    }
    
    // Se chegou aqui, ainda está pendente
    echo json_encode([
        'success' => true,
        'status' => 'pending',
        'message' => 'Aguardando pagamento...'
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
