<?php
// ==========================================================
// ARQUIVO: process_payment.php
// ATUALIZAÇÃO: Usa points_name e mostra erros detalhados do MP
// ==========================================================

ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

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

try {
    session_start();

    // --- 1. CONFIGURAÇÃO E CONEXÃO ---
    if (file_exists('vendor/autoload.php')) require 'vendor/autoload.php';
    elseif (file_exists('../vendor/autoload.php')) require '../vendor/autoload.php';
    else throw new Exception("Vendor (SDK) não encontrado.");

    if (file_exists('includes/conexao.php')) require 'includes/conexao.php';
    elseif (file_exists('../includes/conexao.php')) require '../includes/conexao.php';
    else throw new Exception("Conexão com banco não encontrada.");

    // Busca Token e o Nome da Moeda
    $stmt = $pdo->query("SELECT access_token, points_name FROM mp_config WHERE id = 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$config || empty($config['access_token'])) {
        throw new Exception("Token do Mercado Pago não configurado no banco.");
    }

    \MercadoPago\SDK::setAccessToken(trim($config['access_token']));

    // --- 2. RECEBE OS DADOS ---
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (empty($data)) throw new Exception("Sem dados recebidos.");

    // Sanitização
    $amount = (float)($data['amount'] ?? 0);
    $email = filter_var($data['email'], FILTER_VALIDATE_EMAIL);
    $docNumber = preg_replace('/[^0-9]/', '', $data['documentNumber'] ?? ''); 
    $accountId = (int)($data['accountId'] ?? 0);
    $pointsAmount = (int)($data['pointsAmount'] ?? 0);
    $method = $data['paymentMethod'] ?? 'pix'; 
    $firstName = $data['payerFirstName'] ?? 'Visitante';
    
    // Nome do Produto (Usa o points_name do banco ou padrão)
    $currencyName = $config['points_name'] ?? 'Pontos';
    $description = "$currencyName - Acc: $accountId";

    // Validações
    if (!$email) throw new Exception("E-mail inválido.");
    if ($amount < 1) throw new Exception("Valor mínimo R$ 1,00.");
    if ($accountId <= 0) throw new Exception("Conta não identificada.");

    // --- 3. PROCESSAMENTO ---

    // === CASO 1: PIX ===
    if ($method === 'pix') {
        if (empty($docNumber)) throw new Exception("CPF é obrigatório para PIX.");

        $payment = new \MercadoPago\Payment();
        $payment->transaction_amount = $amount;
        $payment->description = $description;
        $payment->payment_method_id = "pix";
        $payment->external_reference = (string)$accountId;
        $payment->metadata = [
            "account_id" => $accountId,
            "points_amount" => $pointsAmount
        ];
        $payment->payer = [
            "email" => $email,
            "first_name" => $firstName,
            "identification" => ["type" => "CPF", "number" => $docNumber]
        ];

        $payment->save();

        if ($payment->error) {
            $err = $payment->error->message ?? "Erro desconhecido";
            throw new Exception("Erro MP (Pix): $err");
        }

        if (isset($payment->point_of_interaction->transaction_data)) {
            $qr = $payment->point_of_interaction->transaction_data;
            echo json_encode([
                'status' => 'success',
                'action' => 'pix',
                'id' => $payment->id,
                'qr_code' => $qr->qr_code,
                'qr_code_base64' => $qr->qr_code_base64
            ]);
        } else {
            throw new Exception("PIX criado, mas sem QR Code.");
        }

    } 
    // === CASO 2: CARTÃO (LINK / PREFERENCE) ===
    elseif ($method === 'card') {
        
        $preference = new \MercadoPago\Preference();
        
        $item = new \MercadoPago\Item();
        $item->title = $description;
        $item->quantity = 1;
        $item->unit_price = $amount;
        $item->currency_id = "BRL";
        
        $preference->items = [$item];
        $preference->external_reference = (string)$accountId;
        $preference->metadata = [
            "account_id" => $accountId,
            "points_amount" => $pointsAmount
        ];

        $payer = new \MercadoPago\Payer();
        $payer->email = $email;
        $preference->payer = $payer;

        // URLs de retorno
        $base_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
        $path = dirname($_SERVER['PHP_SELF']); 
        // Ajusta path para evitar barras duplicadas ou faltantes
        $path = rtrim($path, '/');
        
        $preference->back_urls = [
            "success" => $base_url . $path . "/donate.php?status=success",
            "failure" => $base_url . $path . "/donate.php?status=failure",
            "pending" => $base_url . $path . "/donate.php?status=pending"
        ];
        $preference->auto_return = "approved";

        $preference->save(); // Tenta criar o link

        // *** DEBUGA O ERRO AQUI ***
        if ($preference->error) {
             // Pega o erro real do objeto Mercado Pago para mostrar na tela
             $msgErro = "Erro MP: ";
             if(isset($preference->error->message)) {
                 $msgErro .= $preference->error->message;
             }
             if(isset($preference->error->causes) && is_array($preference->error->causes)) {
                 foreach($preference->error->causes as $cause) {
                     $msgErro .= " | " . ($cause->description ?? $cause->code);
                 }
             }
             throw new Exception($msgErro);
        }

        echo json_encode([
            'status' => 'success',
            'action' => 'redirect',
            'url' => $preference->init_point // Link de pagamento
        ]);
    } else {
        throw new Exception("Método desconhecido.");
    }

} catch (Exception $e) {
    http_response_code(400); 
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>