<?php
require '../config.php';

/* =========================
   LOG RAW
========================= */
$raw = file_get_contents("php://input");
file_put_contents(
    __DIR__ . '/../logs/webhook_connectpay.log',
    date('Y-m-d H:i:s') . " RAW: " . $raw . PHP_EOL,
    FILE_APPEND
);

$body = json_decode($raw, true);

// valida payload
if (!$body || empty($body['status']) || empty($body['id'])) {
    http_response_code(200);
    exit;
}

$status = strtoupper($body['status']);
$transactionId = $body['id'];

/* =========================
   STATUS IGNORADOS
========================= */
if (!in_array($status, ['AUTHORIZED', 'PAID', 'FAILED'])) {
    file_put_contents(
        __DIR__ . '/../logs/webhook_connectpay_status.log',
        date('Y-m-d H:i:s') . " STATUS IGNORADO: {$status}\n",
        FILE_APPEND
    );
    http_response_code(200);
    exit;
}

/* =========================
   FUNÇÃO DE COMISSÃO
========================= */
function pagarComissao($conn, $userId, $valor) {

    // nível 1
    $nivel1 = $conn->query("
        SELECT indicado_por FROM users WHERE id = $userId
    ")->fetchColumn();

    // bloqueia auto-indicação
    if ($nivel1 == $userId) return;

    if ($nivel1) {
        $conn->query("
            UPDATE users 
            SET saldo = saldo + " . ($valor * 0.10) . " 
            WHERE id = $nivel1
        ");
    }

    // nível 2
    $nivel2 = null;
    if ($nivel1) {
        $nivel2 = $conn->query("
            SELECT indicado_por FROM users WHERE id = $nivel1
        ")->fetchColumn();

        if ($nivel2 && $nivel2 != $userId && $nivel2 != $nivel1) {
            $conn->query("
                UPDATE users 
                SET saldo = saldo + " . ($valor * 0.03) . " 
                WHERE id = $nivel2
            ");
        }
    }

    // nível 3
    if (!empty($nivel2)) {
        $nivel3 = $conn->query("
            SELECT indicado_por FROM users WHERE id = $nivel2
        ")->fetchColumn();

        if ($nivel3 && !in_array($nivel3, [$userId, $nivel1, $nivel2])) {
            $conn->query("
                UPDATE users 
                SET saldo = saldo + " . ($valor * 0.01) . " 
                WHERE id = $nivel3
            ");
        }
    }
}

/* =========================
   1️⃣ PROCESSA DEPÓSITO
========================= */
$stmt = $conn->prepare("
    SELECT * FROM deposits 
    WHERE transaction_id=? AND status='PENDING'
");
$stmt->execute([$transactionId]);
$dep = $stmt->fetch();

if ($dep) {

    if ($status === 'FAILED') {
        http_response_code(200);
        exit;
    }

    $conn->beginTransaction();

    // marca depósito como pago
    $conn->prepare("
        UPDATE deposits 
        SET status='PAID', paid_at=NOW()
        WHERE id=?
    ")->execute([$dep['id']]);

    // credita saldo
    $conn->prepare("
        UPDATE users 
        SET saldo = saldo + ?
        WHERE id=?
    ")->execute([$dep['amount'], $dep['user_id']]);

    // paga comissões
    pagarComissao($conn, $dep['user_id'], $dep['amount']);

    $conn->commit();

    file_put_contents(
        __DIR__ . '/../logs/webhook_connectpay_status.log',
        date('Y-m-d H:i:s') .
        " DEPÓSITO PAGO | USER {$dep['user_id']} | R$ {$dep['amount']}\n",
        FILE_APPEND
    );

    http_response_code(200);
    exit;
}

/* =========================
   2️⃣ PROCESSA SAQUE
========================= */
$stmt = $conn->prepare("
    SELECT * FROM withdrawals 
    WHERE transaction_id=? AND status='PENDING'
");
$stmt->execute([$transactionId]);
$wd = $stmt->fetch();

if ($wd) {

    // saque aprovado
    if ($status === 'PAID') {

        $conn->prepare("
            UPDATE withdrawals 
            SET status='PAID', paid_at=NOW()
            WHERE id=?
        ")->execute([$wd['id']]);

        file_put_contents(
            __DIR__ . '/../logs/webhook_connectpay_status.log',
            date('Y-m-d H:i:s') .
            " SAQUE PAGO | USER {$wd['user_id']} | R$ {$wd['amount']}\n",
            FILE_APPEND
        );
    }

    // saque falhou → devolve saldo
    if ($status === 'FAILED') {

        $conn->beginTransaction();

        $conn->prepare("
            UPDATE users 
            SET saldo = saldo + ?
            WHERE id=?
        ")->execute([$wd['amount'], $wd['user_id']]);

        $conn->prepare("
            UPDATE withdrawals 
            SET status='FAILED'
            WHERE id=?
        ")->execute([$wd['id']]);

        $conn->commit();

        file_put_contents(
            __DIR__ . '/../logs/webhook_connectpay_status.log',
            date('Y-m-d H:i:s') .
            " SAQUE FALHOU | USER {$wd['user_id']} | R$ {$wd['amount']} DEVOLVIDO\n",
            FILE_APPEND
        );
    }

    http_response_code(200);
    exit;
}

/* =========================
   NADA ENCONTRADO
========================= */
file_put_contents(
    __DIR__ . '/../logs/webhook_connectpay_status.log',
    date('Y-m-d H:i:s') .
    " TRANSAÇÃO NÃO ENCONTRADA | ID {$transactionId}\n",
    FILE_APPEND
);

http_response_code(200);
