<?php
// checklog.php

// $secret = "mysecret123";  // change this
// if (!isset($_GET['key']) || $_GET['key'] !== $secret) {
//     die("❌ Unauthorized access");
// }

$vouchno = isset($_GET['vouchno']) ? preg_replace('/[^0-9A-Za-z_-]/', '', $_GET['vouchno']) : '';
if ($vouchno == '') {
    die("❌ Missing voucher number.");
}

$logFile = "/tmp/whatsapp_send_" . $vouchno . ".log";

if (!file_exists($logFile)) {
    die("⚠️ No log found for voucher $vouchno");
}

// Read last 200 lines
$lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lastLines = array_slice($lines, -200);

echo "<h3>📄 WhatsApp Send Log for Voucher $vouchno</h3>";
echo "<pre style='background:#111;color:#0f0;padding:10px;border-radius:8px;'>";
echo htmlspecialchars(implode("\n", $lastLines));
echo "</pre>";

// ✅ Auto-delete log if success
if (preg_match('/"status"\s*:\s*"success"/i', implode("\n", $lines))) {
    unlink($logFile);
    echo "<p style='color:orange;'>🧹 Log auto-deleted after success.</p>";
}

// 🔹 Auto-close page after 5 seconds
echo "<script>
    setTimeout(function(){ window.close(); }, 5000);
</script>";
