<?php
require_once 'config.php';

// Este endpoint recebe notificações automáticas da SeedPay quando o status de um pagamento muda

// Log do webhook para debug
$webhookData = file_get_contents('php://input');
error_log("SeedPay Webhook received: " . $webhookData);

try {
    $data = json_decode($webhookData, true);
    
    if (!$data) {
        throw new Exception('Invalid webhook data');
    }
    
    // Extrair informações do webhook
    $providerTransactionId = $data['transaction_id'] ?? $data['id'] ?? null;
    $status = $data['status'] ?? null;
    $amount = isset($data['amount']) ? floatval($data['amount']) : null;
    
    if (!$providerTransactionId || !$status) {
        throw new Exception('Missing required fields');
    }
    
    $db = Database::getInstance()->getConnection();
    
    // Buscar transação no banco
    $stmt = $db->prepare("
        SELECT id, user_id, amount, status as current_status
        FROM transactions 
        WHERE provider_transaction_id = ?
    ");
    $stmt->execute([$providerTransactionId]);
    $transaction = $stmt->fetch();
    
    if (!$transaction) {
        error_log("Transaction not found for provider_transaction_id: " . $providerTransactionId);
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Transaction not found']);
        exit;
    }
    
    // Se já foi processada, ignorar
    if ($transaction['current_status'] === 'approved') {
        echo json_encode(['success' => true, 'message' => 'Already processed']);
        exit;
    }
    
    // Processar baseado no status
    if ($status === 'approved' || $status === 'paid') {
        // Atualizar transação
        $stmt = $db->prepare("UPDATE transactions SET status = 'approved', approved_at = NOW() WHERE id = ?");
        $stmt->execute([$transaction['id']]);
        
        // Creditar saldo
        $depositAmount = $transaction['amount'];
        $userId = $transaction['user_id'];
        
        $stmt = $db->prepare("UPDATE users SET balance = balance + ?, total_deposited = total_deposited + ? WHERE id = ?");
        $stmt->execute([$depositAmount, $depositAmount, $userId]);
        
        // Log de auditoria
        $stmt = $db->prepare("INSERT INTO audit_logs (user_id, action, description, ip_address) VALUES (?, 'deposit_approved_webhook', ?, ?)");
        $stmt->execute([
            $userId,
            'Depósito de R$ ' . number_format($depositAmount, 2, ',', '.') . ' aprovado via webhook',
            $_SERVER['REMOTE_ADDR'] ?? 'webhook'
        ]);
        
        error_log("Payment approved for transaction: " . $providerTransactionId);
        
    } elseif ($status === 'rejected' || $status === 'cancelled') {
        // Atualizar status da transação
        $newStatus = $status === 'rejected' ? 'rejected' : 'cancelled';
        $stmt = $db->prepare("UPDATE transactions SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $transaction['id']]);
        
        error_log("Payment " . $newStatus . " for transaction: " . $providerTransactionId);
    }
    
    echo json_encode(['success' => true, 'message' => 'Webhook processed']);
    
} catch (Exception $e) {
    error_log("Webhook error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
