<?php
/**
 * Verbose Administrator Reporting & Log Panel
 */

// Optional: Hardcoded basic password protection
$adminPassword = 'admin'; // Change this!
session_start();

if (isset($_POST['password'])) {
    if ($_POST['password'] === $adminPassword) {
        $_SESSION['admin_logged_in'] = true;
    } else {
        $error = "Incorrect password.";
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin.php");
    exit;
}

if (empty($_SESSION['admin_logged_in'])) {
    echo '<!DOCTYPE html><html><head><title>Admin Login</title><style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;background:#f0f2f5;} form{background:#fff;padding:2rem;border-radius:8px;box-shadow:0 4px 6px rgba(0,0,0,0.1);text-align:center;} input{padding:0.5rem;margin:1rem 0;width:100%;border:1px solid #ccc;border-radius:4px;} button{background:#0078D4;color:#fff;border:none;padding:0.5rem 1rem;border-radius:4px;cursor:pointer;}</style></head><body>';
    echo '<form method="POST"><h2>Admin Portal</h2>';
    if (!empty($error))
        echo '<p style="color:red;">' . $error . '</p>';
    echo '<input type="password" name="password" placeholder="Enter Admin Password" required autofocus><br><button type="submit">Login</button></form></body></html>';
    exit;
}

$apiLogFile = __DIR__ . '/api_log.json';
$webhookLogFile = __DIR__ . '/webhook_log.json';
$phpErrorLogFile = __DIR__ . '/php_errors.log';

if (isset($_GET['clear'])) {
    if ($_GET['clear'] === 'api')
        @unlink($apiLogFile);
    if ($_GET['clear'] === 'webhook')
        @unlink($webhookLogFile);
    if ($_GET['clear'] === 'php')
        @unlink($phpErrorLogFile);
    header("Location: admin.php");
    exit;
}

$apiLogs = file_exists($apiLogFile) ? array_reverse(json_decode((string) file_get_contents($apiLogFile), true) ?: []) : [];
$webhookLogs = file_exists($webhookLogFile) ? array_reverse(json_decode((string) file_get_contents($webhookLogFile), true) ?: []) : [];
$phpErrors = file_exists($phpErrorLogFile) ? file_get_contents($phpErrorLogFile) : 'No PHP errors logged.';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>System Logs & Admin Panel</title>
    <style>
        body {
            font-family: system-ui, -apple-system, sans-serif;
            background: #1e1e1e;
            color: #d4d4d4;
            margin: 0;
            padding: 20px;
        }

        h1,
        h2 {
            color: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #333;
            padding-bottom: 10px;
            margin-top: 0;
        }

        .nav {
            margin-bottom: 20px;
        }

        .nav button {
            background: #333;
            color: #fff;
            border: 1px solid #555;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        .nav button.active {
            background: #0078D4;
            border-color: #0078D4;
        }

        .panel {
            display: none;
            background: #252526;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #333;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
        }

        .panel.active {
            display: block;
        }

        .log-entry {
            background: #1e1e1e;
            margin-bottom: 15px;
            border-radius: 6px;
            border: 1px solid #444;
            overflow: hidden;
        }

        .log-header {
            background: #333;
            padding: 10px 15px;
            display: flex;
            justify-content: space-between;
            font-weight: bold;
            font-size: 0.9em;
        }

        .log-header.success {
            border-left: 4px solid #4CAF50;
        }

        .log-header.error {
            border-left: 4px solid #F44336;
        }

        .log-body {
            padding: 15px;
            overflow-x: auto;
            font-family: monospace;
            font-size: 0.85em;
            color: #9CDCFE;
        }

        .btn-danger {
            background: #F44336;
            color: #fff;
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
        }

        pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .badge {
            background: #555;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.8em;
            margin-left: 10px;
        }
    </style>
</head>

<body>

    <h1>
        <span>📡 Server & API Admin Console</span>
        <div>
            <a href="?logout=1"
                style="color: #F44336; text-decoration: none; font-size:1rem; margin-right: 20px;">Logout</a>
            <button onclick="location.reload()"
                style="background:#0078D4;color:#fff;border:none;padding:8px 16px;border-radius:4px;cursor:pointer;">Refresh
                Logs</button>
        </div>
    </h1>

    <div class="nav">
        <button class="tab-btn active" onclick="switchTab('api')">Telstra API Logs <span
                class="badge"><?= count($apiLogs) ?></span></button>
        <button class="tab-btn" onclick="switchTab('webhooks')">Incoming Webhooks <span
                class="badge"><?= count($webhookLogs) ?></span></button>
        <button class="tab-btn" onclick="switchTab('php')">PHP Error Log</button>
    </div>

    <!-- Telstra API Logs -->
    <div id="api" class="panel active">
        <h2>Outgoing Telstra API Requests <a href="?clear=api" class="btn-danger"
                onclick="return confirm('Clear API logs?')">Clear Logs</a></h2>
        <?php if (empty($apiLogs)): ?>
            <p>No API requests logged yet.</p>
        <?php else: ?>
            <?php foreach ($apiLogs as $log): ?>
                <?php
                $isError = ($log['http_code'] < 200 || $log['http_code'] > 299 || $log['curl_error']);
                $statusClass = $isError ? 'error' : 'success';
                ?>
                <div class="log-entry">
                    <div class="log-header <?= $statusClass ?>">
                        <span><?= htmlspecialchars($log['endpoint']) ?></span>
                        <span>HTTP <?= htmlspecialchars($log['http_code']) ?> |
                            <?= htmlspecialchars($log['timestamp']) ?></span>
                    </div>
                    <div class="log-body">
                        <strong style="color:#CE9178;">Request Payload:</strong>
                        <pre><?= htmlspecialchars(json_encode($log['request_payload'], JSON_PRETTY_PRINT)) ?></pre>
                        <hr style="border:0;border-top:1px dashed #444;margin:10px 0;">
                        <strong style="color:#CE9178;">Response Body:</strong>
                        <pre><?= htmlspecialchars(json_encode($log['response_body'], JSON_PRETTY_PRINT)) ?></pre>
                        <?php if ($log['curl_error']): ?>
                            <hr style="border:0;border-top:1px dashed #444;margin:10px 0;">
                            <strong style="color:#F44336;">cURL Error:</strong>
                            <pre><?= htmlspecialchars($log['curl_error']) ?></pre>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Webhook Logs -->
    <div id="webhooks" class="panel">
        <h2>Incoming Telstra Webhooks <a href="?clear=webhook" class="btn-danger"
                onclick="return confirm('Clear Webhook logs?')">Clear Logs</a></h2>
        <?php if (empty($webhookLogs)): ?>
            <p>No webhooks received yet. Have you configured the URL in the Telstra Developer portal?</p>
        <?php else: ?>
            <?php foreach ($webhookLogs as $log): ?>
                <div class="log-entry">
                    <div class="log-header success">
                        <span>Incoming POST Request</span>
                        <span><?= htmlspecialchars($log['timestamp']) ?></span>
                    </div>
                    <div class="log-body">
                        <pre><?= htmlspecialchars(json_encode($log['payload'], JSON_PRETTY_PRINT)) ?></pre>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- PHP Error Logs -->
    <div id="php" class="panel">
        <h2>PHP Fatal Errors & Warnings <a href="?clear=php" class="btn-danger"
                onclick="return confirm('Clear PHP errors?')">Clear Logs</a></h2>
        <div class="log-entry">
            <div class="log-body" style="color: #F44336;">
                <pre><?= htmlspecialchars($phpErrors) ?></pre>
            </div>
        </div>
    </div>

    <script>
        function switchTab(tabId) {
            document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.getElementById(tabId).classList.add('active');
            event.target.classList.add('active');
        }
    </script>
</body>

</html>