<?php
// transactions.php - Public M-Pesa transaction history page with fixed status update
ob_start();
session_start();
error_log("Entering transactions.php: Session ID = " . session_id());

// Include required files
$required_files = ['config.php', 'auth.php', 'functions.php'];
foreach ($required_files as $file) {
    if (!file_exists($file)) {
        error_log("Missing required file: $file");
        header('HTTP/1.1 500 Internal Server Error');
        echo "Server error: Missing $file. Please contact support.";
        ob_end_flush();
        exit();
    }
}
include_once 'config.php';
include_once 'auth.php';
include_once 'functions.php';
include_once 'header.php';

// Enable error reporting for debugging
ini_set('display_errors', 0); // Disable display for production
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

// Log session data
error_log("Session data: " . json_encode($_SESSION));

// Generate CSRF token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
error_log("CSRF token generated: " . $_SESSION['csrf_token']);

// Handle transaction updates (admin-only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    error_log("Processing POST request: " . json_encode($_POST));
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        error_log("CSRF token validation failed");
        set_flash_message('error', 'Invalid CSRF token.');
    } elseif (!is_admin()) {
        error_log("Non-admin attempted to update status: User ID = " . ($_SESSION['user_id'] ?? 'None'));
        set_flash_message('error', 'Access denied. Admin privileges required to update status.');
    } else {
        try {
            if (!isset($conn) || !$conn instanceof mysqli) {
                throw new Exception("Database connection not established.");
            }
            $order_id = (int)$_POST['order_id'];
            $status = sanitize_input($_POST['status']);
            if (!in_array($status, ['pending', 'completed', 'failed'])) {
                throw new Exception("Invalid status value: $status");
            }
            $stmt = $conn->prepare("UPDATE orders SET status = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("si", $status, $order_id);
            if (!$stmt->execute()) {
                throw new Exception("Failed to update status: " . $stmt->error);
            }
            set_flash_message('success', "Order #$order_id status updated to $status.");
            error_log("Status updated for Order #$order_id to $status");
            $stmt->close();
        } catch (Exception $e) {
            error_log("Status update error: " . $e->getMessage());
            set_flash_message('error', 'Error updating status: ' . htmlspecialchars($e->getMessage()));
        }
    }
    // Redirect to preserve filters and refresh page
    $query_string = http_build_query($_GET);
    header("Location: transactions.php" . ($query_string ? "?$query_string" : ""));
    ob_end_flush();
    exit();
}

// Handle transaction deletion (admin-only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        error_log("CSRF token validation failed for delete");
        set_flash_message('error', 'Invalid CSRF token.');
    } elseif (!is_admin()) {
        error_log("Non-admin attempted to delete order: User ID = " . ($_SESSION['user_id'] ?? 'None'));
        set_flash_message('error', 'Access denied. Admin privileges required to delete orders.');
    } else {
        try {
            if (!isset($conn) || !$conn instanceof mysqli) {
                throw new Exception("Database connection not established.");
            }
            $order_id = (int)$_POST['order_id'];
            $stmt = $conn->prepare("DELETE FROM orders WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("i", $order_id);
            if (!$stmt->execute()) {
                throw new Exception("Failed to delete order: " . $stmt->error);
            }
            set_flash_message('success', "Order #$order_id deleted.");
            error_log("Order #$order_id deleted");
            $stmt->close();
        } catch (Exception $e) {
            error_log("Delete error: " . $e->getMessage());
            set_flash_message('error', 'Error deleting order: ' . htmlspecialchars($e->getMessage()));
        }
    }
    // Redirect to preserve filters
    $query_string = http_build_query($_GET);
    header("Location: transactions.php" . ($query_string ? "?$query_string" : ""));
    ob_end_flush();
    exit();
}

// Build filter conditions
$where = ["o.mpesa_checkout_request_id IS NOT NULL"];
$params = [];
$types = '';
if (!empty($_GET['status'])) {
    $where[] = "o.status = ?";
    $params[] = $_GET['status'];
    $types .= 's';
}
if (!empty($_GET['date_from'])) {
    $where[] = "o.created_at >= ?";
    $params[] = $_GET['date_from'];
    $types .= 's';
}
if (!empty($_GET['date_to'])) {
    $where[] = "o.created_at <= ?";
    $params[] = $_GET['date_to'] . ' 23:59:59';
    $types .= 's';
}
if (!empty($_GET['username'])) {
    $where[] = "u.username = ?";
    $params[] = $_GET['username'];
    $types .= 's';
}

// Fetch analytics with filters
try {
    if (!isset($conn) || !$conn instanceof mysqli) {
        throw new Exception("Database connection not established.");
    }
    $where_sql = $where ? " WHERE " . implode(" AND ", $where) : "";
    $sql_total_transactions = "SELECT COUNT(*) as count FROM orders o JOIN users u ON o.user_id = u.id" . $where_sql;
    $sql_total_amount = "SELECT SUM(o.total) as total FROM orders o JOIN users u ON o.user_id = u.id" . $where_sql;
    $sql_status_breakdown = "SELECT o.status, COUNT(*) as count, SUM(o.total) as total FROM orders o JOIN users u ON o.user_id = u.id" . $where_sql . " GROUP BY o.status";

    $stmt_total_transactions = $conn->prepare($sql_total_transactions);
    $stmt_total_amount = $conn->prepare($sql_total_amount);
    $stmt_status_breakdown = $conn->prepare($sql_status_breakdown);

    if ($params) {
        $stmt_total_transactions->bind_param($types, ...$params);
        $stmt_total_amount->bind_param($types, ...$params);
        $stmt_status_breakdown->bind_param($types, ...$params);
    }

    $stmt_total_transactions->execute();
    $total_transactions = $stmt_total_transactions->get_result()->fetch_assoc()['count'];
    $stmt_total_transactions->close();

    $stmt_total_amount->execute();
    $total_amount = $stmt_total_amount->get_result()->fetch_assoc()['total'] ?? 0;
    $stmt_total_amount->close();

    $stmt_status_breakdown->execute();
    $status_breakdown = $stmt_status_breakdown->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_status_breakdown->close();
} catch (Exception $e) {
    error_log("Analytics fetch error: " . $e->getMessage());
    set_flash_message('error', 'Error fetching analytics: ' . htmlspecialchars($e->getMessage()));
}

// Fetch transactions with filters
$transactions = [];
try {
    $where_sql = $where ? " WHERE " . implode(" AND ", $where) : "";
    $sql_transactions = "SELECT o.id, o.user_id, u.username, u.email, o.total, o.status, o.mpesa_checkout_request_id, o.mpesa_result_desc, o.created_at 
                         FROM orders o JOIN users u ON o.user_id = u.id" . $where_sql . " ORDER BY o.created_at DESC";
    $stmt_transactions = $conn->prepare($sql_transactions);
    if ($params) {
        $stmt_transactions->bind_param($types, ...$params);
    }
    $stmt_transactions->execute();
    $transactions = $stmt_transactions->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_transactions->close();
} catch (Exception $e) {
    error_log("Transaction fetch error: " . $e->getMessage());
    set_flash_message('error', 'Error fetching transactions: ' . htmlspecialchars($e->getMessage()));
}

// Build export URL with filter parameters
$export_url = "export_transactions.php?" . http_build_query($_GET);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transaction History - Doyle Enterprise</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; }
        .admin-card { border: none; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
        .admin-header { background: linear-gradient(135deg, #0D6EFD 0%, #764ba2 100%); color: white; padding: 2rem; text-align: center; }
        .admin-body { padding: 2.5rem; }
        .nav-tabs { border-bottom: 2px solid #e9ecef; }
        .nav-link { color: #333; font-weight: 500; }
        .nav-link.active { background: #e3f2fd; border-color: #0D6EFD; }
        .stat-card { border-radius: 10px; padding: 1.5rem; background: #fff; box-shadow: 0 5px 15px rgba(0,0,0,0.08); }
        .btn-action { border-radius: 8px; }
        .btn-export { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; }
        .btn-export:hover { background: linear-gradient(135deg, #218838 0%, #1baa87 100%); }
        .table-responsive { border-radius: 10px; overflow: hidden; }
        .status-pending { color: #ffc107; font-weight: bold; }
        .status-completed { color: #28a745; font-weight: bold; }
        .status-failed { color: #dc3545; font-weight: bold; }
        .sticky-nav { position: sticky; top: 0; z-index: 1000; background: #fff; padding: 1rem; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .chat-btn {
            position: fixed; bottom: 20px; right: 20px; background-color: #f68b1e; color: #fff;
            border: none; border-radius: 50%; width: 50px; height: 50px;
            display: flex; align-items: center; justify-content: center; font-size: 1.5rem;
            cursor: pointer; box-shadow: 0 2px 5px rgba(0,0,0,0.2); transition: transform 0.3s ease, box-shadow 0.3s ease; z-index: 1000;
        }
        .chat-btn:hover { transform: translateY(-3px); box-shadow: 0 4px 10px rgba(0,0,0,0.3); }
        .chat-box {
            position: fixed; bottom: 80px; right: 20px; width: 300px; height: 400px;
            background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            display: none; flex-direction: column; z-index: 1000;
        }
        .chat-header {
            background-color: #0D6EFD; color: #fff; padding: 10px;
            border-top-left-radius: 8px; border-top-right-radius: 8px;
            display: flex; justify-content: space-between; align-items: center;
        }
        .chat-header h5 { margin: 0; font-size: 1rem; }
        .chat-header .close-chat { background: none; border: none; color: #fff; font-size: 1rem; cursor: pointer; }
        .chat-body { flex-grow: 1; padding: 10px; overflow-y: auto; background-color: #f8f9fa; }
        .chat-message { margin-bottom: 10px; padding: 8px; border-radius: 8px; max-width: 80%; }
        .chat-message.user { background-color: #0D6EFD; color: #fff; margin-left: auto; }
        .chat-message.bot { background-color: #e9ecef; color: #333; margin-right: auto; }
        .chat-footer { padding: 10px; border-top: 1px solid #dee2e6; display: flex; align-items: center; }
        .chat-footer input { flex-grow: 1; border: 1px solid #dee2e6; border-radius: 4px; padding: 8px; font-size: 0.9rem; }
        .chat-footer button { background-color: #f68b1e; border: none; color: #fff; padding: 8px 12px; border-radius: 4px; margin-left: 5px; cursor: pointer; transition: background-color 0.3s ease; }
        .chat-footer button:hover { background-color: #d94f1f; }
        .spinner { display: none; margin-left: 10px; }
        .status-form { position: relative; }
        .status-form.submitting .spinner { display: inline-block; }
        .status-form.submitting select { opacity: 0.5; pointer-events: none; }
        @media (max-width: 576px) {
            .chat-box { width: 90%; max-width: 300px; bottom: 60px; right: 10px; }
            .chat-btn { bottom: 10px; right: 10px; }
            .admin-body { padding: 1.5rem; }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Sticky Navigation -->
        <div class="sticky-nav">
            <div class="d-flex justify-content-between align-items-center">
                <h4><i class="fas fa-money-bill-wave me-2"></i>Transaction History</h4>
                <div>
                    <a href="index.php" class="btn btn-primary btn-sm me-2"><i class="fas fa-home me-2"></i>Home</a>
                    <?php if (is_logged_in()): ?>
                        <a href="logout.php" class="btn btn-outline-danger btn-sm"><i class="fas fa-sign-out-alt me-2"></i>Logout</a>
                    <?php else: ?>
                        <a href="login.php" class="btn btn-outline-primary btn-sm"><i class="fas fa-sign-in-alt me-2"></i>Login</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Transaction Card -->
        <div class="row justify-content-center mt-4">
            <div class="col-12">
                <div class="admin-card">
                    <div class="admin-header">
                        <h2><i class="fas fa-money-bill-wave me-2"></i>M-Pesa Transaction History</h2>
                        <p class="mb-0 opacity-75">View all M-Pesa payments for Doyle Enterprise</p>
                    </div>
                    <div class="admin-body">
                        <?php display_flash_message(); ?>
                        <!-- Tabs -->
                        <ul class="nav nav-tabs mb-4">
                            <li class="nav-item"><a class="nav-link active" href="#transactions" data-bs-toggle="tab">Transactions</a></li>
                            <li class="nav-item"><a class="nav-link" href="#analytics" data-bs-toggle="tab">Analytics</a></li>
                        </ul>
                        <div class="tab-content">
                            <!-- Transactions Tab -->
                            <div class="tab-pane fade show active" id="transactions">
                                <!-- Filters -->
                                <form method="GET" class="row g-3 mb-4">
                                    <div class="col-md-3">
                                        <select class="form-select" name="status">
                                            <option value="">All Statuses</option>
                                            <option value="pending" <?php echo isset($_GET['status']) && $_GET['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                            <option value="completed" <?php echo isset($_GET['status']) && $_GET['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                                            <option value="failed" <?php echo isset($_GET['status']) && $_GET['status'] == 'failed' ? 'selected' : ''; ?>>Failed</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="date" class="form-control" name="date_from" value="<?php echo isset($_GET['date_from']) ? htmlspecialchars($_GET['date_from']) : ''; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <input type="date" class="form-control" name="date_to" value="<?php echo isset($_GET['date_to']) ? htmlspecialchars($_GET['date_to']) : ''; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" class="form-control" name="username" placeholder="Filter by Username" value="<?php echo isset($_GET['username']) ? htmlspecialchars($_GET['username']) : ''; ?>">
                                    </div>
                                    <div class="col-12">
                                        <button type="submit" class="btn btn-primary btn-action"><i class="fas fa-filter me-2"></i>Apply Filters</button>
                                        <a href="transactions.php" class="btn btn-outline-secondary btn-action"><i class="fas fa-undo me-2"></i>Clear Filters</a>
                                        <a href="<?php echo htmlspecialchars($export_url); ?>" class="btn btn-export btn-action float-end"><i class="fas fa-download me-2"></i>Export to CSV</a>
                                    </div>
                                </form>

                                <!-- Transactions Table -->
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Order ID</th>
                                                <th>Username</th>
                                                <th>Email</th>
                                                <th>Amount (KES)</th>
                                                <th>Status</th>
                                                <th>M-Pesa Checkout ID</th>
                                                <th>M-Pesa Result</th>
                                                <th>Date</th>
                                                <?php if (is_admin()): ?>
                                                    <th>Actions</th>
                                                <?php endif; ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($transactions)): ?>
                                                <tr><td colspan="<?php echo is_admin() ? 9 : 8; ?>" class="text-center">No M-Pesa transactions found.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($transactions as $row): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($row['id']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['username'] ?: 'Unknown'); ?></td>
                                                        <td><?php echo htmlspecialchars($row['email'] ?: 'Unknown'); ?></td>
                                                        <td><?php echo number_format($row['total'], 2); ?></td>
                                                        <td class="status-<?php echo strtolower($row['status']); ?>">
                                                            <?php echo htmlspecialchars(ucfirst($row['status'])); ?>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($row['mpesa_checkout_request_id'] ?: 'N/A'); ?></td>
                                                        <td><?php echo htmlspecialchars($row['mpesa_result_desc'] ?: 'N/A'); ?></td>
                                                        <td><?php echo date('M d, Y H:i', strtotime($row['created_at'])); ?></td>
                                                        <?php if (is_admin()): ?>
                                                            <td>
                                                                <form method="POST" class="status-form d-inline" id="status-form-<?php echo $row['id']; ?>">
                                                                    <input type="hidden" name="order_id" value="<?php echo $row['id']; ?>">
                                                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                                                    <input type="hidden" name="action" value="update_status">
                                                                    <select name="status" class="form-select form-select-sm d-inline w-auto">
                                                                        <option value="pending" <?php echo $row['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                                        <option value="completed" <?php echo $row['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                                                                        <option value="failed" <?php echo $row['status'] == 'failed' ? 'selected' : ''; ?>>Failed</option>
                                                                    </select>
                                                                    <span class="spinner fa fa-spinner fa-spin"></span>
                                                                </form>
                                                                <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this order?');">
                                                                    <input type="hidden" name="order_id" value="<?php echo $row['id']; ?>">
                                                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                                                    <input type="hidden" name="action" value="delete">
                                                                    <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>
                                                                </form>
                                                            </td>
                                                        <?php endif; ?>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Analytics Tab -->
                            <div class="tab-pane fade" id="analytics">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="stat-card">
                                            <h5>Total Transactions</h5>
                                            <p class="fs-4"><?php echo htmlspecialchars($total_transactions); ?></p>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="stat-card">
                                            <h5>Total Amount (KES)</h5>
                                            <p class="fs-4"><?php echo number_format($total_amount, 2); ?></p>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="stat-card">
                                            <h5>Status Breakdown</h5>
                                            <?php foreach ($status_breakdown as $status): ?>
                                                <p><?php echo htmlspecialchars(ucfirst($status['status'])); ?>: <?php echo $status['count']; ?> (KES <?php echo number_format($status['total'], 2); ?>)</p>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chat Box -->
        <div class="chat-btn" id="chatBtn">
            <i class="fas fa-comment"></i>
        </div>
        <div class="chat-box" id="chatBox">
            <div class="chat-header">
                <h5>Support Chat</h5>
                <button class="close-chat" onclick="toggleChatBox()"><i class="fas fa-times"></i></button>
            </div>
            <div class="chat-body" id="chatBody"></div>
            <div class="chat-footer">
                <input type="text" id="chatInput" placeholder="Type your message..." onkeypress="if(event.key === 'Enter') sendMessage()">
                <button onclick="sendMessage()"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>

        <!-- Footer -->
        <div class="text-center mt-4">
            <small class="text-muted"><i class="fas fa-lock me-1"></i>Secured by M-Pesa | Compliant with CBK Regulations</small>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Get user ID from PHP session or generate guest ID
        const userId = '<?php echo isset($_SESSION['user_id']) ? htmlspecialchars($_SESSION['user_id']) : 'guest_' . mt_rand(100000, 999999); ?>';
        const chatStorageKey = `chatMessages_${userId}`;

        // Status update form handling
        document.querySelectorAll('.status-form').forEach(form => {
            const select = form.querySelector('select[name="status"]');
            select.addEventListener('change', async () => {
                form.classList.add('submitting');
                try {
                    const formData = new FormData(form);
                    const response = await fetch('transactions.php', {
                        method: 'POST',
                        body: formData
                    });
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    // Reload page to reflect changes and preserve filters
                    const urlParams = new URLSearchParams(window.location.search);
                    window.location.href = 'transactions.php?' + urlParams.toString();
                } catch (error) {
                    console.error('Status update error:', error);
                    form.classList.remove('submitting');
                    alert('Error updating status. Please try again.');
                }
            });
        });

        // Chat box functionality
        function toggleChatBox() {
            const chatBox = document.getElementById('chatBox');
            const chatBtn = document.getElementById('chatBtn');
            if (chatBox.style.display === 'flex') {
                chatBox.style.display = 'none';
                chatBtn.innerHTML = '<i class="fas fa-comment"></i>';
            } else {
                chatBox.style.display = 'flex';
                chatBtn.innerHTML = '<i class="fas fa-times"></i>';
                loadMessages();
            }
        }

        function sendMessage() {
            const input = document.getElementById('chatInput');
            const message = input.value.trim();
            if (!message) return;

            appendMessage('user', message);
            saveMessage('user', message);
            input.value = '';

            // Automated response
            setTimeout(() => {
                const response = getBotResponse(message.toLowerCase());
                appendMessage('bot', response);
                saveMessage('bot', response);
            }, 500);
        }

        function appendMessage(sender, text) {
            const chatBody = document.getElementById('chatBody');
            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-message ${sender}`;
            messageDiv.textContent = text;
            chatBody.appendChild(messageDiv);
            chatBody.scrollTop = chatBody.scrollHeight;
        }

        function saveMessage(sender, text) {
            let messages = JSON.parse(sessionStorage.getItem(chatStorageKey) || '[]');
            messages.push({ sender, text, timestamp: new Date().toISOString() });
            sessionStorage.setItem(chatStorageKey, JSON.stringify(messages));
        }

        function loadMessages() {
            const chatBody = document.getElementById('chatBody');
            chatBody.innerHTML = '';
            let messages = JSON.parse(sessionStorage.getItem(chatStorageKey) || '[]');
            messages.forEach(msg => appendMessage(msg.sender, msg.text));
        }

        function getBotResponse(message) {
            if (message.includes('track') || message.includes('order status')) {
                return 'Please provide the order number, and we’ll check the status for you!';
            } else if (message.includes('return') || message.includes('refund')) {
                return 'You can manage returns for eligible orders within 7 days. Provide the order number for assistance.';
            } else if (message.includes('contact') || message.includes('support')) {
                return 'Reach us at mautimasea14@gmail.com or call +254 746 071 550. How else can we assist you?';
            } else if (message.includes('delivery') || message.includes('shipping')) {
                return 'Delivery times vary by location. Provide an order number for specific details.';
            } else {
                return 'I’m here to help! Try asking about order tracking, returns, or contact details.';
            }
        }

        // Initialize chat
        document.getElementById('chatBtn').addEventListener('click', toggleChatBox);
    </script>
    <?php include_once 'footer.php'; ?>
</body>
</html>
<?php ob_end_flush(); ?>