<?php
// ==========================================================
// ARQUIVO: notification.php
// OBJETIVO: Entrega automática (Funciona para Pix e Cartão)
// ==========================================================

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

http_response_code(200); // OK imediato para o MP

try {
    if (file_exists('vendor/autoload.php')) require 'vendor/autoload.php';
    elseif (file_exists('../vendor/autoload.php')) require '../vendor/autoload.php';
    
    if (file_exists('includes/conexao.php')) require 'includes/conexao.php';
    elseif (file_exists('../includes/conexao.php')) require '../includes/conexao.php';

    // Config
    $stmtConfig = $pdo->query("SELECT access_token, points_per_real FROM mp_config WHERE id = 1");
    $configMP = $stmtConfig->fetch(PDO::FETCH_ASSOC);

    if (!$configMP || empty($configMP['access_token'])) exit;

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

    // Captura ID
    $payment_id = $_GET['data_id'] ?? $_GET['id'] ?? null;
    $topic = $_GET['topic'] ?? $_GET['type'] ?? null;

    if (!$payment_id) {
        $input = json_decode(file_get_contents('php://input'), true);
        $payment_id = $input['data']['id'] ?? null;
        $topic = $input['type'] ?? null;
    }

    if (!$payment_id || $topic !== 'payment') exit;

    // Busca Pagamento
    $payment = \MercadoPago\Payment::find_by_id($payment_id);

    if ($payment && $payment->status === 'approved') {
        
        $transaction_id = (string)$payment->id;

        // Verifica duplicidade
        $check = $pdo->prepare("SELECT id FROM payments_history WHERE transaction_id = ?");
        $check->execute([$transaction_id]);

        if ($check->rowCount() == 0) {
            
            // Tenta pegar Acc ID de várias formas
            $account_id = $payment->external_reference ?? $payment->metadata->account_id ?? null;
            $points = $payment->metadata->points_amount ?? null;

            // Se não veio pontos no metadata, calcula baseado no valor
            if (!$points) {
                $points = floor($payment->transaction_amount * ($configMP['points_per_real'] ?? 1));
            }

            if ($account_id && $points > 0) {
                $pdo->beginTransaction();

                // 1. Atualiza Saldo
                $upd = $pdo->prepare("UPDATE accounts SET post_points = post_points + ? WHERE id = ?");
                $upd->execute([$points, $account_id]);

                // 2. Registra Log
                $log = $pdo->prepare("INSERT INTO payments_history (account_id, points_amount, value_brl, transaction_id, date_processed, status) VALUES (?, ?, ?, ?, ?, 'approved')");
                $log->execute([$account_id, $points, $payment->transaction_amount, $transaction_id, time()]);

                $pdo->commit();
            }
        }
    }
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    error_log("Webhook Error: " . $e->getMessage());
}
?>