<?php
// --- DATABASE CONFIGURATION AND PHP LOGIC (REMAINS THE SAME) ---
$db_host = 'localhost';
$db_user = 'webhookuser';
$db_pass = 'Psdf3234ddsdg';
$db_name = 'whatsapp_webhook_data';

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$conn->set_charset("utf8mb4");

$direction_filter = $_GET['direction_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = isset($_GET['per_page']) && in_array((int)$_GET['per_page'], [25, 50, 100]) ? (int)$_GET['per_page'] : 25;

$latest_status_subquery = "
    (
        SELECT message_wamid, status, status_timestamp, recipient_wa_id, ROW_NUMBER() OVER(PARTITION BY message_wamid ORDER BY 
            CASE status WHEN 'read' THEN 4 WHEN 'failed' THEN 3 WHEN 'delivered' THEN 2 WHEN 'sent' THEN 1 ELSE 0 END DESC, status_timestamp DESC) as rn
        FROM message_statuses
    ) AS latest_status ON m.wamid = latest_status.message_wamid AND latest_status.rn = 1
";

$where_clauses = [];
$params = [];
$param_types = '';

if (!empty($direction_filter)) { $where_clauses[] = "m.direction = ?"; $params[] = $direction_filter; $param_types .= 's'; }
if (!empty($date_from)) { $where_clauses[] = "m.message_timestamp >= ?"; $params[] = $date_from . ' 00:00:00'; $param_types .= 's'; }
if (!empty($date_to)) { $where_clauses[] = "m.message_timestamp <= ?"; $params[] = $date_to . ' 23:59:59'; $param_types .= 's'; }
if (!empty($status_filter)) {
    if ($status_filter == 'no_status') { $where_clauses[] = "latest_status.status IS NULL"; } 
    else { $where_clauses[] = "latest_status.status = ?"; $params[] = $status_filter; $param_types .= 's'; }
}
$where_sql = !empty($where_clauses) ? " WHERE " . implode(" AND ", $where_clauses) : "";

$count_sql = "SELECT COUNT(DISTINCT m.id) as total FROM messages AS m LEFT JOIN $latest_status_subquery $where_sql";
$count_stmt = $conn->prepare($count_sql);
if ($count_stmt) {
    if (!empty($params)) { $count_stmt->bind_param($param_types, ...$params); }
    $count_stmt->execute();
    $total_records = $count_stmt->get_result()->fetch_assoc()['total'] ?? 0;
    $count_stmt->close();
} else { $total_records = 0; }

$total_pages = ceil($total_records / $per_page);
$offset = ($page - 1) * $per_page;

$summary_sql = "
    SELECT 
        SUM(CASE WHEN m.direction = 'incoming' THEN 1 ELSE 0 END) as incoming_count,
        SUM(CASE WHEN m.direction = 'outgoing' THEN 1 ELSE 0 END) as outgoing_count,
        SUM(CASE WHEN latest_status.status = 'sent' THEN 1 ELSE 0 END) as sent_count,
        SUM(CASE WHEN latest_status.status = 'delivered' THEN 1 ELSE 0 END) as delivered_count,
        SUM(CASE WHEN latest_status.status = 'read' THEN 1 ELSE 0 END) as read_count,
        SUM(CASE WHEN latest_status.status = 'failed' THEN 1 ELSE 0 END) as failed_count,
        SUM(CASE WHEN p.billable = 1 AND m.direction = 'outgoing' THEN 1 ELSE 0 END) as billable_count,
        SUM(CASE WHEN p.billable = 1 AND m.direction = 'outgoing' THEN 
            CASE p.category WHEN 'marketing' THEN pm.marketing WHEN 'utility' THEN pm.utility WHEN 'authentication' THEN pm.authentication WHEN 'authentication-international' THEN pm.authentication_international ELSE 0 END
        ELSE 0 END) as total_cost
    FROM messages AS m
    LEFT JOIN pricing AS p ON m.wamid = p.message_wamid
    LEFT JOIN contacts AS c ON m.contact_wa_id = c.wa_id
    LEFT JOIN pricing_master AS pm ON c.market = pm.market
    LEFT JOIN $latest_status_subquery $where_sql
";
$summary_stmt = $conn->prepare($summary_sql);
if ($summary_stmt) {
    if (!empty($params)) { $summary_stmt->bind_param($param_types, ...$params); }
    $summary_stmt->execute();
    $summary = $summary_stmt->get_result()->fetch_assoc();
    $summary_stmt->close();
} else { $summary = []; }

$sql = "
    SELECT m.id, m.wamid, m.direction, m.message_type, m.content, m.message_timestamp, c.profile_name, m.contact_wa_id, c.market,
        conv.conversation_id, conv.origin_type, p.billable, p.category AS pricing_category, latest_status.status AS highest_status,
        latest_status.status_timestamp, latest_status.recipient_wa_id AS status_recipient_id, pm.currency,
        (CASE WHEN p.billable = 1 THEN 
            CASE p.category WHEN 'marketing' THEN pm.marketing WHEN 'utility' THEN pm.utility WHEN 'authentication' THEN pm.authentication WHEN 'authentication-international' THEN pm.authentication_international ELSE 0 END
        ELSE 0 END) as row_cost
    FROM messages AS m
    LEFT JOIN contacts AS c ON m.contact_wa_id = c.wa_id
    LEFT JOIN conversations AS conv ON m.conversation_id_str = conv.conversation_id
    LEFT JOIN pricing AS p ON m.wamid = p.message_wamid
    LEFT JOIN pricing_master AS pm ON c.market = pm.market
    LEFT JOIN $latest_status_subquery
    $where_sql
    ORDER BY m.message_timestamp DESC
    LIMIT ? OFFSET ?
";
$stmt = $conn->prepare($sql);
$all_params = array_merge($params, [$per_page, $offset]);
$all_param_types = $param_types . 'ii';
if ($stmt) {
    if (!empty($params)) { $stmt->bind_param($all_param_types, ...$all_params); }
    else { $stmt->bind_param("ii", $per_page, $offset); }
    $stmt->execute();
    $result = $stmt->get_result();
} else { die("Error preparing main statement: " . $conn->error); }

$free_outgoing_count = ($summary['outgoing_count'] ?? 0) - ($summary['billable_count'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Igarashi Motors | Business WhatsApp Log</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 20px; }
        .container { background-color: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow-x: auto; padding: 20px; }
        .header-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 15px;}
        h1 { color: #075E54; font-size: 1.5em; margin: 0; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 0.88em; }
        th, td { padding: 6px 10px; text-align: left; border-bottom: 1px solid #ddd; vertical-align: top; line-height: 1.3; }
        th { background-color: #ECE5DD; font-weight: 600; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        tr:hover { background-color: #f1f1f1; }
        .status-badge { display: inline-block; padding: 4px 8px; border-radius: 12px; font-size: 0.9em; color: white; min-width: 70px; text-align: center; }
        .status-badge small { font-size: 0.85em; opacity: 0.8; display: block; line-height: 1.2; }
        .status-sent { background-color: #34B7F1; }
        .status-delivered { background-color: #001f3f; }
        .status-read { background-color: #28a745; }
        .status-failed { background-color: #c0392b; }
        .dir-incoming { color: #008000; font-weight: bold; }
        .dir-outgoing { color: #D44638; font-weight: bold; }
        .cost-billable { color: #c0392b; font-weight: bold; }
        .cost-free { color: #28a745; }
        .no-data { text-align: center; padding: 20px; color: #888; }
        .filter-form { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
        .filter-form label { font-weight: 600; font-size: 0.9em; }
        .filter-form select, .filter-form input[type="date"] { padding: 6px; border-radius: 4px; border: 1px solid #ccc; font-size: 0.9em; }
        .filter-form button, .reset-btn { padding: 6px 12px; border-radius: 4px; border: none; cursor: pointer; font-weight: 600; font-size: 0.9em; text-decoration: none; display: inline-block; }
        .filter-form button { background-color: #075E54; color: white; }
        .filter-form button:hover { background-color: #054e46; }
        .reset-btn { background-color: #6c757d; color: white; }
        .reset-btn:hover { background-color: #5a6268; }
        .summary-wrapper { display: flex; flex-wrap: wrap; gap: 15px; align-items: stretch; margin-bottom: 20px; }
        .summary-card { padding: 10px 15px; border-radius: 8px; color: #fff; box-shadow: 0 1px 4px rgba(0,0,0,0.1); display: flex; flex-direction: column; justify-content: center; }
        .summary-card .count { font-size: 1.8em; font-weight: 600; text-align: center; }
        .summary-card .label { font-size: 0.9em; opacity: 0.9; text-align: center; }
        .summary-card.primary { flex: 1; min-width: 180px; }
        .outgoing-summary-group { flex: 2; border: 1px solid #e0e0e0; border-radius: 8px; padding: 10px; }
        .outgoing-summary-group h3 { margin: 0 0 10px 5px; font-size: 1em; color: #555; }
        .outgoing-summary-group .cards-container { display: flex; flex-wrap: wrap; gap: 10px; }
        .outgoing-summary-group .summary-card { flex: 1; min-width: 90px; }
        .sub-counts { display: flex; justify-content: space-around; margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(255, 255, 255, 0.2); }
        .sub-count-item { text-align: center; }
        .sub-count-label { font-size: 0.75em; opacity: 0.8; display: block; }
        .sub-count-value { font-size: 1.1em; font-weight: 600; }
        .incoming-card { background: linear-gradient(45deg, #17a2b8, #117a8b); }
        .outgoing-card { background: linear-gradient(45deg, #e87b32, #d6681d); }
        .sent-card { background: linear-gradient(45deg, #57c0e8, #34B7F1); }
        .delivered-card { background: linear-gradient(45deg, #2c4a6e, #001f3f); }
        .read-card { background: linear-gradient(45deg, #44bb61, #28a745); }
        .failed-card { background: linear-gradient(45deg, #e74c3c, #c0392b); }
        .pagination-container { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; font-size: 0.9em; }
        .pagination-links a, .pagination-links strong { display: inline-block; padding: 5px 10px; margin: 0 2px; border: 1px solid #ddd; text-decoration: none; color: #075E54; background-color: #fff; border-radius: 4px; }
        .pagination-links a:hover { background-color: #f0f0f0; }
        .pagination-links strong { background-color: #ECE5DD; color: #333; }
        .pagination-container .per-page-form { display: flex; align-items: center; gap: 8px; }
        .view-chat-link { display: block; margin-top: 4px; font-size: 0.9em; text-decoration: none; color: #0056b3; font-weight: 500; cursor: pointer; }
        .view-chat-link:hover { text-decoration: underline; }

        /* --- CHAT DRAWER STYLES --- */
        #drawer-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background-color: rgba(0, 0, 0, 0.5); z-index: 999;
            opacity: 0; visibility: hidden; transition: opacity 0.3s, visibility 0s 0.3s;
        }
        #chat-drawer {
            position: fixed; top: 0; right: 0; width: 100%; max-width: 450px; height: 100%;
            background-color: #f0f0f0; box-shadow: -5px 0 15px rgba(0,0,0,0.2); z-index: 1000;
            transform: translateX(100%); transition: transform 0.3s ease-in-out;
            display: flex; flex-direction: column;
        }
        #drawer-overlay.is-open { opacity: 1; visibility: visible; transition: opacity 0.3s; }
        #chat-drawer.is-open { transform: translateX(0); }
        #chat-header {
            background-color: #075E54; color: white; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0;
        }
        #chat-header h2 { margin: 0; font-size: 1.2em; }
        #close-chat { font-size: 1.5em; color: white; cursor: pointer; background: none; border: none; }
        #chat-messages {
            flex-grow: 1; padding: 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 12px;
            background-color: #E5DDD5;
            background-image: url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png');
        }
        .message-bubble { max-width: 75%; padding: 8px 12px; border-radius: 18px; line-height: 1.4; word-wrap: break-word; box-shadow: 0 1px 1px rgba(0,0,0,0.1); }
        .message-bubble.incoming { background-color: #FFFFFF; align-self: flex-start; border-top-left-radius: 4px; }
        .message-bubble.outgoing { background-color: #DCF8C6; align-self: flex-end; border-top-right-radius: 4px; }
        .message-bubble .content { font-size: 0.95em; }
        .message-bubble .timestamp { font-size: 0.7em; color: #888; margin-top: 4px; text-align: right; }
        #chat-loader { text-align: center; padding: 40px; font-size: 1.2em; color: #555; }
        #chat-footer {
            flex-shrink: 0; background-color: #f0f0f0; padding: 10px; border-top: 1px solid #ddd;
        }
        #send-message-form { display: flex; gap: 10px; }
        #message-input {
            flex-grow: 1; border: 1px solid #ccc; border-radius: 20px; padding: 10px 15px; font-size: 1em;
        }
        #send-button {
            border: none; background-color: #075E54; color: white; border-radius: 50%; width: 45px; height: 45px;
            font-size: 1.5em; cursor: pointer; display: flex; align-items: center; justify-content: center;
        }
        #send-button:disabled { background-color: #a0a0a0; }
    </style>
</head>
<body>
    <div class="container">
        <!-- Main content remains here -->
        <div class="header-container">
            <h1>Igarashi Motors | Business WhatsApp Log</h1>
            <form action="" method="get" class="filter-form">
                <div><label for="direction_filter">Direction:</label><select name="direction_filter" id="direction_filter"><option value="">All</option><option value="incoming" <?php if ($direction_filter == 'incoming') echo 'selected'; ?>>Incoming</option><option value="outgoing" <?php if ($direction_filter == 'outgoing') echo 'selected'; ?>>Outgoing</option></select></div>
                <div><label for="status_filter">Status:</label><select name="status_filter" id="status_filter"><option value="">All</option><option value="sent" <?php if ($status_filter == 'sent') echo 'selected'; ?>>Sent</option><option value="delivered" <?php if ($status_filter == 'delivered') echo 'selected'; ?>>Delivered</option><option value="read" <?php if ($status_filter == 'read') echo 'selected'; ?>>Read</option><option value="failed" <?php if ($status_filter == 'failed') echo 'selected'; ?>>Failed</option><option value="no_status" <?php if ($status_filter == 'no_status') echo 'selected'; ?>>No Status</option></select></div>
                <div><label for="date_from">From:</label><input type="date" name="date_from" id="date_from" value="<?php echo htmlspecialchars($date_from); ?>"></div>
                <div><label for="date_to">To:</label><input type="date" name="date_to" id="date_to" value="<?php echo htmlspecialchars($date_to); ?>"></div>
                <div><button type="submit">Filter</button></div>
                <div><a href="?" class="reset-btn">Reset</a></div>
            </form>
        </div>

        <div class="summary-wrapper">
            <div class="summary-card primary incoming-card"><span class="count"><?php echo $summary['incoming_count'] ?? 0; ?></span><span class="label">Total Incoming</span></div>
            <div class="summary-card primary outgoing-card">
                <div><span class="count"><?php echo $summary['outgoing_count'] ?? 0; ?></span><span class="label">Total Outgoing</span></div>
                <div class="sub-counts">
                    <div class="sub-count-item"><span class="sub-count-label">Billable</span><span class="sub-count-value"><?php echo $summary['billable_count'] ?? 0; ?> (₹<?php echo number_format($summary['total_cost'] ?? 0, 2); ?>)</span></div>
                    <div class="sub-count-item"><span class="sub-count-label">Free</span><span class="sub-count-value"><?php echo $free_outgoing_count; ?></span></div>
                </div>
            </div>
            <div class="outgoing-summary-group">
                <h3>Outgoing Status</h3>
                <div class="cards-container">
                    <div class="summary-card sent-card"><span class="count"><?php echo $summary['sent_count'] ?? 0; ?></span><span class="label">Sent</span></div>
                    <div class="summary-card delivered-card"><span class="count"><?php echo $summary['delivered_count'] ?? 0; ?></span><span class="label">Delivered</span></div>
                    <div class="summary-card read-card"><span class="count"><?php echo $summary['read_count'] ?? 0; ?></span><span class="label">Read</span></div>
                    <div class="summary-card failed-card"><span class="count"><?php echo $summary['failed_count'] ?? 0; ?></span><span class="label">Failed</span></div>
                </div>
            </div>
        </div>

        <table>
            <!-- Table content remains the same, but the chat link now has data attributes -->
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>Direction</th>
                    <th>Contact</th>
                    <th>Content</th>
                    <th>Conversation Details</th>
                    <th>Cost</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo htmlspecialchars(substr($row['message_timestamp'], 2, 14)); ?></td>
                            <td><span class="dir-<?php echo htmlspecialchars($row['direction']); ?>"><?php echo ucfirst(htmlspecialchars($row['direction'])); ?></span></td>
                            <td>
                                <?php
                                $display_name = $row['profile_name'];
                                $display_wa_id = $row['contact_wa_id'] ?: $row['status_recipient_id'] ?: 'N/A';
                                if (!empty($display_name)) {
                                    echo '<strong>' . htmlspecialchars($display_name) . '</strong><br>';
                                    echo '<small>' . htmlspecialchars($display_wa_id) . '</small>';
                                } else {
                                    echo '<strong>' . htmlspecialchars($display_wa_id) . '</strong>';
                                }
                                ?>
                            </td>
                            <td>
                                <?php echo nl2br(htmlspecialchars($row['content'])); ?>
                                <!-- THIS IS THE CLICKABLE CHAT LINK FOR JAVASCRIPT -->
                                <a href="#" class="view-chat-link" 
                                   data-wamid="<?php echo htmlspecialchars($row['wamid']); ?>" 
                                   data-contact-name="<?php echo htmlspecialchars($display_name ?: $display_wa_id); ?>">💬 View Chat</a>
                                <br><small>Type: <?php echo htmlspecialchars($row['message_type']); ?></small>
                            </td>
                            <td>
                                <?php if($row['conversation_id']): ?>
                                    <small><strong>Conv ID:</strong> <?php echo htmlspecialchars($row['conversation_id']); ?></small><br>
                                    <small><strong>Category:</strong> <?php echo htmlspecialchars($row['pricing_category'] ?: 'N/A'); ?></small>
                                <?php else: ?><small>N/A</small><?php endif; ?>
                            </td>
                            <td>
                                <?php 
                                if ($row['billable']) {
                                    $currency_symbol = ($row['currency'] === 'INR') ? '₹' : ($row['currency'] ?? '$');
                                    echo '<span class="cost-billable">Billable</span><br><small>' . $currency_symbol . number_format($row['row_cost'], 4) . '</small>';
                                } else { echo '<span class="cost-free">Free</span>'; }
                                ?>
                            </td>
                            <td>
                                <?php
                                if (!empty($row['highest_status'])) {
                                    $status_class = strtolower(htmlspecialchars($row['highest_status']));
                                    $status_name = ucfirst($status_class);
                                    $prefix = ($status_class === 'read') ? '✓ ' : '';
                                    $formatted_time = 'N/A';
                                    if (!empty($row['highest_status_timestamp'])) {
                                        try {
                                            $date = new DateTime($row['highest_status_timestamp']);
                                            $formatted_time = $date->format('M d, H:i');
                                        } catch (Exception $e) { $formatted_time = 'Invalid date'; }
                                    }
                                    echo "<span class='status-badge status-{$status_class}'>{$prefix}{$status_name}<small>{$formatted_time}</small></span>";
                                } else { echo "<small>N/A</small>"; }
                                ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="7" class="no-data">No messages found for the selected criteria.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>

        <div class="pagination-container">
            <!-- Pagination remains the same -->
             <div class="per-page-form">
                <form action="" method="get" id="perPageForm">
                    <input type="hidden" name="direction_filter" value="<?php echo htmlspecialchars($direction_filter); ?>">
                    <input type="hidden" name="status_filter" value="<?php echo htmlspecialchars($status_filter); ?>">
                    <input type="hidden" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
                    <input type="hidden" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
                    <label for="per_page">Show:</label>
                    <select name="per_page" id="per_page" onchange="document.getElementById('perPageForm').submit();">
                        <option value="25" <?php if ($per_page == 25) echo 'selected'; ?>>25</option>
                        <option value="50" <?php if ($per_page == 50) echo 'selected'; ?>>50</option>
                        <option value="100" <?php if ($per_page == 100) echo 'selected'; ?>>100</option>
                    </select>
                    <span>records</span>
                </form>
            </div>
            <div class="pagination-links">
                <?php if ($total_records > 0):
                    $query_params = ['direction_filter' => $direction_filter,'status_filter' => $status_filter,'date_from' => $date_from,'date_to' => $date_to,'per_page' => $per_page];
                    if ($page > 1) { echo '<a href="?' . http_build_query(array_merge($query_params, ['page' => $page - 1])) . '">« Prev</a>'; }
                    for ($i = 1; $i <= $total_pages; $i++) {
                        if ($i == $page) { echo '<strong>' . $i . '</strong>'; } 
                        else { echo '<a href="?' . http_build_query(array_merge($query_params, ['page' => $i])) . '">' . $i . '</a>'; }
                    }
                    if ($page < $total_pages) { echo '<a href="?' . http_build_query(array_merge($query_params, ['page' => $page + 1])) . '">Next »</a>'; }
                endif; ?>
            </div>
        </div>
    </div>

    <!-- CHAT DRAWER HTML -->
    <div id="drawer-overlay"></div>
    <div id="chat-drawer">
        <div id="chat-header">
            <h2 id="chat-contact-name">Chat</h2>
            <button id="close-chat">×</button>
        </div>
        <div id="chat-messages">
            <!-- Messages will be loaded here by JavaScript -->
        </div>
        <div id="chat-footer">
            <form id="send-message-form">
                <input type="text" id="message-input" placeholder="Type a message..." autocomplete="off">
                <button type="submit" id="send-button" title="Send Message">➤</button>
            </form>
        </div>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // --- Element Variables ---
    const chatDrawer = document.getElementById('chat-drawer');
    const drawerOverlay = document.getElementById('drawer-overlay');
    const closeChatButton = document.getElementById('close-chat');
    const chatMessagesContainer = document.getElementById('chat-messages');
    const chatContactName = document.getElementById('chat-contact-name');
    const sendMessageForm = document.getElementById('send-message-form');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');

    let currentChatWaId = null; // Stores the wa_id of the current open chat

    // --- Functions ---
    function openDrawer() {
        chatDrawer.classList.add('is-open');
        drawerOverlay.classList.add('is-open');
    }

    function closeDrawer() {
        chatDrawer.classList.remove('is-open');
        drawerOverlay.classList.remove('is-open');
        currentChatWaId = null; // Reset when drawer closes
    }

    function escapeHTML(str) {
        const p = document.createElement('p');
        p.textContent = str;
        return p.innerHTML.replace(/\n/g, '<br>');
    }

    function appendMessageBubble(direction, text, timestamp) {
        const messageBubble = document.createElement('div');
        messageBubble.classList.add('message-bubble', direction);
        messageBubble.innerHTML = `
            <div class="content">${escapeHTML(text)}</div>
            <div class="timestamp">${escapeHTML(timestamp)}</div>`;
        chatMessagesContainer.appendChild(messageBubble);
        chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
    }

    // --- Event Listeners ---
    document.body.addEventListener('click', function(event) {
        if (event.target.classList.contains('view-chat-link')) {
            event.preventDefault();

            const link = event.target;
            const wamid = link.dataset.wamid;
            
            chatContactName.textContent = link.dataset.contactName;
            chatMessagesContainer.innerHTML = '<div id="chat-loader">Loading chat...</div>';
            openDrawer();

            fetch(`fetch_chat.php?wamid=${wamid}`)
                .then(response => response.json())
                .then(data => {
                    chatMessagesContainer.innerHTML = '';
                    if (data.success) {
                        currentChatWaId = data.contact_wa_id; // CRITICAL: Set the wa_id for replying
                        if (data.messages.length > 0) {
                            data.messages.forEach(msg => appendMessageBubble(msg.direction, msg.content, msg.message_timestamp));
                        } else {
                            chatMessagesContainer.innerHTML = '<div id="chat-loader">No messages found in this conversation.</div>';
                        }
                    } else {
                        chatMessagesContainer.innerHTML = `<div id="chat-loader">Error: ${data.error || 'Could not load chat.'}</div>`;
                    }
                })
                .catch(error => {
                    console.error('Error fetching chat:', error);
                    chatMessagesContainer.innerHTML = '<div id="chat-loader">Error loading chat.</div>';
                });
        }
    });

    sendMessageForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const messageText = messageInput.value.trim();

        if (!messageText || !currentChatWaId) {
            return;
        }

        const originalButtonText = sendButton.innerHTML;
        sendButton.innerHTML = '...';
        sendButton.disabled = true;
        messageInput.disabled = true;

        // Optimistic UI update: show the message immediately
        const now = new Date().toISOString().slice(0, 19).replace('T', ' ');
        appendMessageBubble('outgoing', messageText, now);
        const optimisticMessage = messageText; // Save for potential retry
        messageInput.value = '';

        fetch('send_message_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                recipient_wa_id: currentChatWaId,
                message_text: optimisticMessage
            })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                alert(`Failed to send message: ${data.error || 'Unknown error'}`);
                messageInput.value = optimisticMessage; // Put message back on failure
            }
            // On success, do nothing extra as we already updated the UI.
        })
        .catch(error => {
            console.error('Error sending message:', error);
            alert('A network error occurred. Please try again.');
            messageInput.value = optimisticMessage;
        })
        .finally(() => {
            sendButton.innerHTML = originalButtonText;
            sendButton.disabled = false;
            messageInput.disabled = false;
            messageInput.focus();
        });
    });

    closeChatButton.addEventListener('click', closeDrawer);
    drawerOverlay.addEventListener('click', closeDrawer);
});
</script>

</body>
</html>
<?php
$stmt->close();
$conn->close();
?>