<?php
/**
 * admin/cron-auctions.php
 * Cron Job do Leilão de Centavos
 *
 * Configure no servidor:
 *   * * * * * curl -s "https://seusite.com/admin/cron-auctions.php?secret=SEU_CRON_SECRET"
 *   (ou via painel de hospedagem: a cada 1 minuto)
 */

require_once '../settings.php';

$secret = $_GET['secret'] ?? $_SERVER['HTTP_X_CRON_SECRET'] ?? '';
if ($secret !== $_settings->info('cron_secret') && php_sapi_name() !== 'cli') {
    http_response_code(403); die('Forbidden');
}

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

$log = [];

// ─────────────────────────────────────────────────────────
// 1. ENCERRAR LEILÕES CUJO TIMER ZEROU (Fase 2)
// ─────────────────────────────────────────────────────────
$active = $conn->query(
    "SELECT * FROM auction_list WHERE status=2 AND phase=2 AND timer_reset_at IS NOT NULL"
);
while ($a = $active->fetch_assoc()) {
    $elapsed      = time() - strtotime($a['timer_reset_at']);
    $seconds_left = (int)$a['timer_seconds'] - $elapsed;

    if ($seconds_left <= 0) {
        // Encerra o leilão
        $winner_id = (int)($a['last_bidder_id'] ?: 0);
        $conn->query("UPDATE auction_list SET status=3, winner_id=$winner_id WHERE id={$a['id']}");

        if ($winner_id) {
            enqueue_whatsapp($winner_id, 'auction_won', $a['current_price']);
        }

        $log[] = "✅ Leilão #{$a['id']} encerrado. Vencedor: #{$winner_id}. Preço: R$"
                 . number_format($a['current_price'],2,',','.');
    }
}

// ─────────────────────────────────────────────────────────
// 2. LANCES SIMULADOS — PROVA SOCIAL (Fase 1 apenas)
// ─────────────────────────────────────────────────────────
$phase1 = $conn->query(
    "SELECT * FROM auction_list WHERE status=2 AND phase=1"
);
while ($a = $phase1->fetch_assoc()) {
    // Probabilidade: 60% de chance de simular um lance por minuto
    if (rand(1, 10) <= 6) {
        $new_price = round((float)$a['current_price'] + (float)$a['bid_increment'], 2);

        $conn->query("UPDATE auction_list SET
            current_price  = $new_price,
            timer_reset_at = NOW(),
            total_bids     = total_bids + 1,
            total_revenue  = total_revenue + 0.49
            WHERE id={$a['id']} AND phase=1");

        $conn->query("INSERT INTO auction_bids
            SET auction_id={$a['id']}, customer_id=NULL,
            price_at_bid=$new_price, is_simulated=1");

        // Verifica se atingiu o gatilho de Fase 2
        $new_revenue = (float)$a['total_revenue'] + 0.49;
        if ($a['phase2_trigger'] && $new_revenue >= (float)$a['phase2_trigger']) {
            $conn->query("UPDATE auction_list SET phase=2 WHERE id={$a['id']}");
            $log[] = "🔥 Leilão #{$a['id']} ativou FASE REAL! Receita: R$"
                     . number_format($new_revenue,2,',','.');
        }

        $log[] = "🎭 Lance simulado no leilão #{$a['id']} → R$"
                 . number_format($new_price,2,',','.');
    }
}

// ─────────────────────────────────────────────────────────
// 3. NOTIFICAÇÕES WHATSAPP — PROCESSAR FILA
// ─────────────────────────────────────────────────────────
$wpp_url = $_settings->info('wpp_api_url');
$wpp_key = $_settings->info('wpp_api_key');

if ($wpp_url) {
    $pending = $conn->query(
        "SELECT * FROM notification_queue WHERE status=0 ORDER BY created_at ASC LIMIT 20"
    );
    while ($n = $pending->fetch_assoc()) {
        $sent = drope_send_whatsapp($n['phone'], $n['message']);
        $status = $sent ? 1 : 2;
        $conn->query("UPDATE notification_queue SET status=$status, sent_at=NOW() WHERE id={$n['id']}");
        if ($sent) $log[] = "📲 WhatsApp enviado para {$n['phone']} [{$n['event_type']}]";
    }
}

// ─────────────────────────────────────────────────────────
// 4. LIMPAR NOTIFICAÇÕES ANTIGAS (> 30 dias)
// ─────────────────────────────────────────────────────────
$conn->query("DELETE FROM notification_queue WHERE status IN (1,2) AND created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)");

// ─────────────────────────────────────────────────────────
// RESPOSTA
// ─────────────────────────────────────────────────────────
$result = [
    'timestamp' => date('Y-m-d H:i:s'),
    'actions'   => count($log),
    'log'       => $log,
];

header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
