<?php
require (__DIR__) . '/../main.php';
$m = new Mother;
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip == "::1") $ip = "127.0.0.1";
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

// Simple authentication (you can improve this)
$adminPassword = 'admin123'; // Change this password!
$isAuthenticated = isset($_SESSION['chatbot_admin']) && $_SESSION['chatbot_admin'] === true;

if (isset($_POST['login'])) {
    if ($_POST['password'] === $adminPassword) {
        $_SESSION['chatbot_admin'] = true;
        $isAuthenticated = true;
    } else {
        $loginError = 'Falsches Passwort!';
    }
}

if (isset($_GET['logout'])) {
    unset($_SESSION['chatbot_admin']);
    header('Location: chatbot_admin.php');
    exit;
}

if (!$isAuthenticated) {
    ?>
    <!DOCTYPE html>
    <html lang="de">
    <head>
        <meta charset="UTF-8">
        <title>Chatbot Admin Login</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                background: #f5f5f5;
            }
            .login-box {
                background: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                width: 300px;
            }
            .login-box h2 {
                margin-top: 0;
                color: #0078c8;
            }
            .login-box input {
                width: 100%;
                padding: 10px;
                margin: 10px 0;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box;
            }
            .login-box button {
                width: 100%;
                padding: 10px;
                background: #0078c8;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }
            .error {
                color: red;
                font-size: 14px;
            }
        </style>
    </head>
    <body>
        <div class="login-box">
            <h2>🔐 Admin Login</h2>
            <?php if (isset($loginError)) echo '<div class="error">' . $loginError . '</div>'; ?>
            <form method="POST">
                <input type="password" name="password" placeholder="Passwort" required>
                <button type="submit" name="login">Anmelden</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Load messages
$logFile = __DIR__ . '/logs/chatbot_messages.json';
$messages = array();
if (file_exists($logFile)) {
    $messages = json_decode(file_get_contents($logFile), true);
    if (!is_array($messages)) {
        $messages = array();
    }
}
$messages = array_reverse($messages); // Newest first

// Handle response
if (isset($_POST['respond'])) {
    $sessionId = $_POST['session_id'];
    $response = $_POST['response'];
    
    // Update message with response
    foreach ($messages as &$msg) {
        if ($msg['session_id'] === $sessionId) {
            $msg['responded'] = true;
            $msg['response'] = $response;
            $msg['response_time'] = date('Y-m-d H:i:s');
            break;
        }
    }
    
    file_put_contents($logFile, json_encode(array_reverse($messages), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    
    // Mark response as new (not shown yet) by ensuring response_time is set
    // This will allow the chatbot to pick it up
    
    header('Location: chatbot_admin.php?responded=1&session=' . urlencode($sessionId));
    exit;
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatbot Admin Panel</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #0078c8 0%, #005a9e 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            font-size: 24px;
        }
        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
            padding: 8px 16px;
            border-radius: 4px;
            text-decoration: none;
            cursor: pointer;
        }
        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .stat-box {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .stat-box h3 {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .stat-box .number {
            font-size: 32px;
            font-weight: bold;
            color: #0078c8;
        }
        .messages-container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .message-item {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background: #fafafa;
        }
        .message-item.responded {
            background: #e8f5e9;
            border-color: #4caf50;
        }
        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 12px;
            color: #666;
        }
        .message-content {
            background: white;
            padding: 12px;
            border-radius: 4px;
            margin: 10px 0;
            border-left: 3px solid #0078c8;
        }
        .message-content strong {
            color: #0078c8;
        }
        .response-form {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e0e0e0;
        }
        .response-form textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            font-family: inherit;
            resize: vertical;
        }
        .response-form button {
            background: #4caf50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        .response-form button:hover {
            background: #45a049;
        }
        .response-display {
            background: #e8f5e9;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
            border-left: 3px solid #4caf50;
        }
        .badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
        }
        .badge-pending {
            background: #ff9800;
            color: white;
        }
        .badge-responded {
            background: #4caf50;
            color: white;
        }
        .info-row {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        .success-msg {
            background: #4caf50;
            color: white;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🤖 Chatbot Admin Panel</h1>
        <a href="?logout=1" class="logout-btn">Abmelden</a>
    </div>
    
    <?php if (isset($_GET['responded'])): ?>
        <div class="success-msg">✅ Antwort erfolgreich gesendet!</div>
    <?php endif; ?>
    
    <div class="stats">
        <div class="stat-box">
            <h3>Gesamt Nachrichten</h3>
            <div class="number"><?php echo count($messages); ?></div>
        </div>
        <div class="stat-box">
            <h3>Offene Nachrichten</h3>
            <div class="number"><?php echo count(array_filter($messages, function($m) { return !isset($m['responded']); })); ?></div>
        </div>
        <div class="stat-box">
            <h3>Beantwortet</h3>
            <div class="number"><?php echo count(array_filter($messages, function($m) { return isset($m['responded']); })); ?></div>
        </div>
        <div class="stat-box">
            <h3>Heute</h3>
            <div class="number"><?php 
                $today = date('Y-m-d');
                echo count(array_filter($messages, function($m) use ($today) { 
                    return strpos($m['timestamp'], $today) === 0; 
                })); 
            ?></div>
        </div>
    </div>
    
    <div class="messages-container">
        <h2 style="margin-bottom: 20px;">📨 Nachrichten</h2>
        
        <?php if (empty($messages)): ?>
            <p style="color: #999; text-align: center; padding: 40px;">Keine Nachrichten vorhanden.</p>
        <?php else: ?>
            <?php foreach ($messages as $msg): ?>
                <div class="message-item <?php echo isset($msg['responded']) ? 'responded' : ''; ?>">
                    <div class="message-header">
                        <div>
                            <span class="badge <?php echo isset($msg['responded']) ? 'badge-responded' : 'badge-pending'; ?>">
                                <?php echo isset($msg['responded']) ? '✓ Beantwortet' : '⏳ Ausstehend'; ?>
                            </span>
                            <span style="margin-left: 10px;"><?php echo htmlspecialchars($msg['timestamp']); ?></span>
                        </div>
                    </div>
                    
                    <div class="message-content">
                        <strong>Nachricht:</strong><br>
                        <?php echo nl2br(htmlspecialchars($msg['message'])); ?>
                    </div>
                    
                    <div class="info-row">
                        <span>🌐 IP: <?php echo htmlspecialchars($msg['ip']); ?></span>
                        <span>📦 Tracking: <?php echo htmlspecialchars($msg['tracking_number']); ?></span>
                        <span>🆔 Session: <?php echo substr(htmlspecialchars($msg['session_id']), 0, 20); ?>...</span>
                    </div>
                    
                    <?php if (isset($msg['responded']) && isset($msg['response'])): ?>
                        <div class="response-display">
                            <strong>Ihre Antwort:</strong><br>
                            <?php echo nl2br(htmlspecialchars($msg['response'])); ?><br>
                            <small style="color: #666;">Antwortzeit: <?php echo htmlspecialchars($msg['response_time']); ?></small>
                        </div>
                    <?php else: ?>
                        <form method="POST" class="response-form">
                            <input type="hidden" name="session_id" value="<?php echo htmlspecialchars($msg['session_id']); ?>">
                            <textarea name="response" rows="3" placeholder="Ihre Antwort hier eingeben..." required></textarea>
                            <button type="submit" name="respond">✅ Antwort senden</button>
                        </form>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</body>
</html>

