<?php
/**
 * webhook.php — Bloco adicional para depósitos via PIX
 * Adicione este trecho dentro do webhook.php existente,
 * nos cases de cada gateway, para processar depósitos.
 *
 * Estrutura já existente no webhook.php:
 *   switch ($_GET['notify']) {
 *     case 'openpix':    ...
 *     case 'mercadopago': ...
 *     ...
 *   }
 *
 * Adicione o handler abaixo de cada gateway.
 */

require_once __DIR__ . '/settings.php';
require_once __DIR__ . '/includes/wallet-functions.php';

// ─────────────────────────────────────────────────────────
// Função central: confirma depósito e credita na carteira
// ─────────────────────────────────────────────────────────
function confirm_deposit($correlation_id, $amount_cents = null) {
    global $conn;

    // correlationID foi definido como "DEP-{id}" no depósito
    $dep_id = 0;
    if (str_starts_with($correlation_id, 'DEP-')) {
        $dep_id = (int) substr($correlation_id, 4);
    } else {
        $dep_id = (int) $correlation_id;
    }

    if (!$dep_id) return;

    $dep = $conn->query("SELECT * FROM deposits WHERE id = $dep_id AND status = 1")->fetch_assoc();
    if (!$dep) return; // Já processado ou não encontrado

    $amount = $amount_cents ? ($amount_cents / 100) : (float)$dep['amount'];

    // Atualiza status do depósito
    $conn->query("UPDATE deposits
                  SET status = 2, confirmed_at = NOW()
                  WHERE id = $dep_id");

    // Credita na carteira
    wallet_credit(
        $dep['customer_id'],
        $dep['amount'],          // Sempre usa o valor original (sem taxa extra)
        'deposit',
        "Depósito via PIX confirmado — #$dep_id",
        $dep_id,
        'deposit'
    );

    // WhatsApp
    enqueue_whatsapp($dep['customer_id'], 'deposit_confirmed', $dep['amount']);
}

// ─────────────────────────────────────────────────────────
// OPENPIX — Adicione dentro do case 'openpix':
// ─────────────────────────────────────────────────────────
if (($_GET['notify'] ?? '') === 'openpix_deposit') {
    $body    = file_get_contents('php://input');
    $payload = json_decode($body, true);

    if (($payload['event'] ?? '') === 'OPENPIX:CHARGE_COMPLETED') {
        $corr_id = $payload['charge']['correlationID'] ?? '';
        confirm_deposit($corr_id);
    }
    http_response_code(200);
    exit('ok');
}

// ─────────────────────────────────────────────────────────
// MERCADOPAGO — Adicione no handler MP existente
// ─────────────────────────────────────────────────────────
if (($_GET['notify'] ?? '') === 'mercadopago_deposit') {
    require_once 'includes/gateway/mercadopago/vendor/autoload.php';
    $body    = file_get_contents('php://input');
    $payload = json_decode($body, true);

    if (($payload['type'] ?? '') === 'payment') {
        $payment_id    = $payload['data']['id'];
        $access_token  = $_settings->info('mercadopago_access_token');
        $curl = curl_init("https://api.mercadopago.com/v1/payments/$payment_id");
        curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ["Authorization: Bearer $access_token"]]);
        $resp    = json_decode(curl_exec($curl), true);
        curl_close($curl);

        if (($resp['status'] ?? '') === 'approved') {
            $ext_ref = $resp['external_reference'] ?? '';
            confirm_deposit($ext_ref, null);
        }
    }
    http_response_code(200);
    exit('ok');
}

// ─────────────────────────────────────────────────────────
// GERENCIANET / EFÍ — Adicione no handler GN existente
// ─────────────────────────────────────────────────────────
if (($_GET['notify'] ?? '') === 'gerencianet_deposit') {
    $body    = file_get_contents('php://input');
    $payload = json_decode($body, true);

    if (isset($payload['pix'])) {
        foreach ($payload['pix'] as $pix) {
            if (($pix['status'] ?? '') === 'CONCLUIDA') {
                $txid = $pix['txid'] ?? '';
                // Busca depósito pelo txid
                $dep = $conn->query("SELECT id FROM deposits WHERE txid = '"
                                     . $conn->real_escape_string($txid) . "' AND status = 1")
                            ->fetch_assoc();
                if ($dep) confirm_deposit($dep['id']);
            }
        }
    }
    http_response_code(200);
    exit('ok');
}

// ─────────────────────────────────────────────────────────
// ENDPOINT AJAX: checar status do depósito (polling frontend)
// ─────────────────────────────────────────────────────────
if (($_GET['f'] ?? '') === 'check_deposit_status') {
    header('Content-Type: application/json');
    $dep_id = (int)($_GET['id'] ?? 0);
    $cid    = (int)($_settings->userdata('id') ?? 0);

    if (!$dep_id || !$cid) { echo json_encode(['status' => 0]); exit(); }

    $dep = $conn->query("SELECT status FROM deposits WHERE id = $dep_id AND customer_id = $cid")
                ->fetch_assoc();
    echo json_encode(['status' => (int)($dep['status'] ?? 0)]);
    exit();
}

// ─────────────────────────────────────────────────────────
// ENDPOINT AJAX: status do leilão (polling dashboard)
// ─────────────────────────────────────────────────────────
if (($_GET['f'] ?? '') === 'auction_status') {
    header('Content-Type: application/json');
    $aid = (int)($_GET['id'] ?? 0);
    if (!$aid) { echo json_encode([]); exit(); }

    $a = $conn->query("SELECT current_price, timer_seconds, timer_reset_at, phase,
                              last_bidder_id, total_bids, status
                        FROM auction_list WHERE id = $aid")->fetch_assoc();
    if (!$a) { echo json_encode([]); exit(); }

    $elapsed      = $a['timer_reset_at'] ? time() - strtotime($a['timer_reset_at']) : 0;
    $seconds_left = ($a['phase'] == 2) ? max(0, $a['timer_seconds'] - $elapsed) : $a['timer_seconds'];

    $last_bidder = '';
    if ($a['last_bidder_id']) {
        $lb = $conn->query("SELECT firstname FROM customer_list WHERE id = ".(int)$a['last_bidder_id'])->fetch_assoc();
        $last_bidder = $lb['firstname'] ?? '';
    }

    $recent = $conn->query("SELECT b.price_at_bid, b.created_at, b.is_simulated,
                                    c.firstname
                             FROM auction_bids b
                             LEFT JOIN customer_list c ON b.customer_id = c.id
                             WHERE b.auction_id = $aid
                             ORDER BY b.created_at DESC LIMIT 5");
    $bids = [];
    while ($r = $recent->fetch_assoc()) {
        $bids[] = [
            'name'  => $r['is_simulated'] ? 'Usuário ***' : htmlspecialchars($r['firstname'] ?? 'Anônimo'),
            'price' => 'R$ ' . number_format($r['price_at_bid'], 2, ',', '.'),
            'time'  => date('H:i:s', strtotime($r['created_at']))
        ];
    }

    echo json_encode([
        'current_price'    => 'R$ ' . number_format($a['current_price'], 2, ',', '.'),
        'seconds_left'     => $seconds_left,
        'phase'            => (int)$a['phase'],
        'total_bids'       => (int)$a['total_bids'],
        'last_bidder_name' => $last_bidder,
        'recent_bids'      => $bids,
        'status'           => (int)$a['status'],
    ]);
    exit();
}
