<?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.28) . " 
            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.02) . " 
                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']);

    // =========================
    // 🎁 GIRO POR INDICADO N1
    // =========================

    // só dá giro se ainda não concedeu
    $checkGiro = $conn->prepare("
        SELECT giro_concedido 
        FROM deposits 
        WHERE id=?
        FOR UPDATE
    ");
    $checkGiro->execute([$dep['id']]);
    $jaDeu = (int) $checkGiro->fetchColumn();

    if ($jaDeu === 0) {

        // busca quem é o dono do depósito e quem indicou
        $stmt = $conn->prepare("
            SELECT u.indicado_por
            FROM users u
            WHERE u.id = ?
        ");
        $stmt->execute([$dep['user_id']]);
        $indicadoPor = (int) $stmt->fetchColumn();

        if ($indicadoPor > 0) {

            // garante registro em user_giros
            $check = $conn->prepare("
                SELECT giros 
                FROM user_giros 
                WHERE user_id=?
                FOR UPDATE
            ");
            $check->execute([$indicadoPor]);

            if ($check->fetch()) {

                // soma +1 giro
                $conn->prepare("
                    UPDATE user_giros
                    SET giros = giros + 1,
                        updated_at = NOW()
                    WHERE user_id=?
                ")->execute([$indicadoPor]);

            } else {

                // cria registro com 1 giro
                $conn->prepare("
                    INSERT INTO user_giros (user_id, giros, updated_at)
                    VALUES (?, 1, NOW())
                ")->execute([$indicadoPor]);
            }

            // (opcional) log
            $conn->prepare("
                INSERT INTO roleta_log_convite (user_id, convidado_id, criado_em)
                VALUES (?, ?, NOW())
            ")->execute([$indicadoPor, $dep['user_id']]);
        }

        // marca que este depósito já gerou giro
        $conn->prepare("
            UPDATE deposits 
            SET giro_concedido = 1
            WHERE id=?
        ")->execute([$dep['id']]);
    }

    $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']} | GIRO_N1 " . ($jaDeu === 0 ? 'SIM' : 'JÁ_DADO') . "\n",
        FILE_APPEND
    );

    http_response_code(200);
    exit;
}

/* =========================
   2️⃣GANHA GIRO CADSTROE
========================= */

$ref = $usuarioQueDepositou['ref_id'];

if ($ref) {
    $conn->prepare("
        INSERT INTO user_giros (user_id, giros, updated_at)
        VALUES (?, 1, NOW())
        ON DUPLICATE KEY UPDATE 
            giros = giros + 1,
            updated_at = NOW()
    ")->execute([$ref]);
}

/* =========================
   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);