<?php
session_start();
if (strlen($_SESSION['id']) == 0) {
    $logoutUrl = dirname($_SERVER['PHP_SELF'], 1) . '/../logout.php';
    $logoutUrl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/' . trim($logoutUrl, '/');
    header("Location: $logoutUrl");
    exit();
} else {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chatwoot Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <style>
        .contact-form { text-align: center; margin-left: 258px; margin-top: 60px; }
        
        /*delete btn on chat*/
        .message {
            position: relative;
            padding-right: 30px; /* space for the button */
        }
        
        .delete-btn {
            position: absolute;
            right: 5px;
            top: 5px;
            background: transparent;
            border: none;
            color: red;
            font-size: 16px;
            cursor: pointer;
            display: none;
        }
        
        .message:hover .delete-btn {
            display: block;
        }

    </style>
</head>
<body>
<div class="dashboard">
    <aside class="sidebar">
        <div class="logo"><img src="dashboard_image/23416667.png" alt="Logo" style="height: 100px; width: 150px"/></div>
        <div class="profile">
            <div class="name">Haven Cleaning</div>
            <div class="number">+13322308524</div>
            <div class="status-indicator"><span class="dot"></span><span>Available</span></div>
        </div>
        <nav class="nav">
            <a href="" class="nav-item active" onclick="showSection('conversation', event)"><i class="fa-solid fa-comment-sms"></i> Conversation</a>
            <a href="#" class="nav-item" onclick="showSection('contacts', event)"><i class="fa-solid fa-address-book"></i> Contacts</a>
        </nav>
        <div class="logout"><i class="fa-solid fa-right-from-bracket"></i> Logout</div>
    </aside>
    <main class="main-content">
        <section id="conversation" class="content-section active">
            <header class="top-bar">
                <div class="title" id="section-title">
                    Conversation <img src="dashboard_image/icons8-question-mark-50.png">
                </div>
            </header>
            <div class="message-con">
                <div class="message-list-container">
                    <div class="search-filter-wrapper">
                        <div class="search-filter-input">
                            <input type="text" class="search-conv-input" placeholder="Search conversations" id="conversation-search" />
                        </div>
                        <div class="search-filter-svg">
                            <button class="search-filter-btn">
                                <svg viewBox="64 64 896 896" focusable="false" fill="currentColor" width="1em" height="1em" data-icon="filter" aria-hidden="true">
                                    <path d="M880.1 154H143.9c-24.5 0-39.8 26.7-27.5 48L349 597.4V838c0 17.7 14.2 32 31.8 32h262.4c17.6 0 31.8-14.3 31.8-32V597.4L907.7 202c12.2-21.3-3.1-48-27.6-48zM603.4 798H420.6V642h182.9v156zm9.6-236.6l-9.5 16.6h-183l-9.5-16.6L212.7 226h598.6L613 561.4z"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                    <div class="toolbar">
                        <div class="toolbar-checkbox">
                            <input type="checkbox" id="toolbar-check">
                        </div>
                        <div class="toolbar-btn">
                            <button class="icon-btn"><i class="fa-solid fa-box-archive"></i></button>
                            <button class="icon-btn"><i class="fas fa-envelope-open-text"></i></button>
                            <button class="icon-btn"><i class="fa-solid fa-upload"></i></button>
                            <button class="icon-btn"><i class="fas fa-ban"></i></button>
                        </div>
                    </div>
                    <div id="conversation-list"> <!-- Loaded by JavaScript --> </div>
                </div>
                <div class="contact-detail"> Select a conversation from the list. </div>
            </div>
        </section>
        <section id="contacts" class="content content-section">
            <header class="top-bar">
                <div class="title" id="section-title">
                    Contacts <img src="dashboard_image/icons8-question-mark-50.png">
                </div>
                <div class="buttons">
                    <button class="btn" id="add-contact-btn">
                        <i class="far fa-comment-plus" style="color: #ffffff;"></i>
                        <span>Add New Contact</span>
                    </button>
                </div>
            </header>
            <div class="contact-con">
                <div class="contact-list">
                    <div class="contact-input">
                        <input type="text" placeholder="Search Contacts..." class="search-box" />
                    </div>
                    <div id="contact-list-container"> <!-- Contacts will load here --> </div>
                    <div class="pagination">
                        <button disabled>&lt;</button>
                        <button class="btn1">1</button>
                        <span> / 1</span>
                        <button disabled>&gt;</button>
                    </div>
                </div>
                <div class="contact-detailssssss"></div>
            </div>
        </section>
        <section id="responses" class="content-section">
            <header class="top-bar">
                <div class="title" id="section-title">
                    Canned Responses <img src="dashboard_image/icons8-question-mark-50.png">
                </div>
                <div class="buttons">
                    <button class="btn"><img src="dashboard_image/icons8-comment-plus-24 (1).png"> Add New Response</button>
                </div>
            </header>
            <div class="conversation-entry">This is the Canned Responses section.</div>
        </section>
        <section id="profile" class="content-section">
            <header class="top-bar">
                <div class="title" id="section-title">
                    My Profile<img src="dashboard_image/icons8-question-mark-50.png">
                </div>
            </header>
            <div class="conversation-entry">This is the My Profile section.</div>
        </section>
    </main>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let currentPhone = null;
let refreshInterval = null;
let lastMessageId = 0;

// ======== Conversation Filtering Logic =========

let conversationData = []; // Stores full conversation data for filtering/search

function loadConversations() {
    $.ajax({
        url: 'Get_conversation.php',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            conversationData = data; // Save full list for live filter
            renderConversations();
        }
    });
}

// Renders conversations based on search input
function renderConversations() {
    const container = document.getElementById('conversation-list');
    container.innerHTML = '';
    let filterText = document.getElementById('conversation-search').value.trim().toLowerCase();

    // Filter conversations by contact name or number, case-insensitive
    let filteredData = conversationData.filter(row => {
        let name = (row.contact_name || '').toLowerCase();
        let number = (row.Sender || '').toLowerCase();
        return name.includes(filterText) || number.includes(filterText);
    });

    if (filteredData.length === 0) {
        container.innerHTML = '<div>No conversations found.</div>';
        return;
    }

    filteredData.forEach(row => {
        const item = document.createElement('div');
        item.className = 'message-item';
        item.onclick = () => {
            updateSeen(row.Sender);
            loadMessages(row.Sender);
        };

        let phoneStyle = '';
        let MSGStyle = '';
        if (row.Seen === '') phoneStyle = 'font-weight:bold; color:green;';
        else MSGStyle = 'margin-left:20px; font-style: italic; font-size:15px';

        function formatDateToMDY(dateStr) {
            const [day, month, yearWithTime] = dateStr.split('-');
            const [year, time] = yearWithTime.split(' ');
            return `${month}-${day}-${year} ${time}`;
        }
        const formattedDate = formatDateToMDY(row.created_at);

        if (row.contact_name && row.contact_name.trim() !== "") {
            item.innerHTML = `<input type="checkbox">
                <div class="message-info">
                    <div class="phone" style="${phoneStyle}">${row.contact_name}</div>
                    <div class="phone" style="${phoneStyle}">${row.Sender}</div>
                    <div style="${MSGStyle}">${row.Body}</div>
                </div>
                <div class="message-meta">
                    <div class="timestamp">${formattedDate}</div>
                </div>
            `;
        } else {
            item.innerHTML = `<input type="checkbox">
                <div class="message-info">
                    <div class="phone" style="${phoneStyle}">${row.Sender}</div>
                    <div style="${MSGStyle}">${row.Body}</div>
                </div>
                <div class="message-meta">
                    <div class="timestamp">${formattedDate}</div>
                </div>
            `;
        }
        container.appendChild(item);
    });
}

// Listen to search filter changes
document.addEventListener('DOMContentLoaded', function () {
    loadConversations();
    setInterval(loadConversations, 10000);
    document.getElementById('conversation-search').addEventListener('input', renderConversations);
});

// ======== Message Loading Logic (unchanged, for context) =========

function loadMessages(phone) {
    currentPhone = phone;
    lastMessageId = 0;
    if (refreshInterval) clearInterval(refreshInterval);
    fetchMessages(true);
    refreshInterval = setInterval(() => fetchMessages(false), 5000);

    function fetchMessages(isInitialLoad) {
        const inputFocused = document.activeElement.id === 'message-input';
        if (inputFocused) return;
        $.ajax({
            url: 'get_messages.php',
            type: 'POST',
            data: { phone: phone, last_id: isInitialLoad ? 0 : lastMessageId },
            success: function (response) {
                if (isInitialLoad) {
                    $('.contact-detail').html(
                        `<div class="chat-container">${response}</div>
                        <div class='message-input-container'>
                            <input type='text' id='message-input' placeholder='Type your message...' />
                            <button onclick='sendMessage("${phone}")'>Send</button>
                        </div>`
                    );
                } else {
                    if (response.trim()) {
                        $('.chat-container').append(response);
                    }
                }
                // Update lastMessageId
                const allMessages = document.querySelectorAll('.chat-container .message');
                if (allMessages.length > 0) {
                    const last = allMessages[allMessages.length - 1];
                    const newId = parseInt(last.getAttribute('data-id'));
                    if (!isNaN(newId)) lastMessageId = newId;
                }
                // Scroll to bottom only on initial load
                if (isInitialLoad) {
                    const container = document.querySelector('.chat-container');
                    if (container) container.scrollTop = container.scrollHeight;
                }
            }
        });
    }
}

function sendMessage(phone) {
    const message = document.getElementById('message-input').value.trim();
    if (!message) return;
    $.ajax({
        url: 'Send_sms.php',
        type: 'POST',
        data: { phone: phone, message: message },
        success: function (res) {
            document.getElementById('message-input').value = '';
            loadMessages(phone); // reload chat
        }
    });
}

// Update Seen status in database
function updateSeen(sender) {
    $.ajax({
        url: 'update_seen.php',
        type: 'POST',
        data: { sender: sender },
        success: function (res) {
            setTimeout(loadConversations, 500);
        },
        error: function () {
            console.error('Failed to update Seen status');
        }
    });
}

// delete the msg 
function deleteMessage(id) {
    if (!confirm("Are you sure you want to delete this message?")) return;

    $.ajax({
        url: 'delete_Chat_message.php',
        type: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.trim() === "success") {
                $(`.message[data-id='${id}']`).remove();
            } else {
                alert("Failed to delete message.");
            }
        }
    });
}


// ======== Contact Add, List, Delete (unchanged) =========

document.getElementById('add-contact-btn').addEventListener('click', function () {
    const formHtml = `<div class="contact-form">
        <h3>Add New Contact</h3>
        <form id="contactForm">
            <label>Full Name:</label><br>
            <input type="text" id="fullName" name="fullName" required><br><br>
            <label>Phone Number:</label><br>
            <input type="text" id="phoneNumber" name="phoneNumber" required><br><br>
            <button type="submit">Save Contact</button>
        </form>
        <div id="form-message" style="margin-top:10px;"></div>
    </div>`;
    document.querySelector('.contact-detailssssss').innerHTML = formHtml;
    document.getElementById('contactForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const fullName = document.getElementById('fullName').value.trim();
        const phoneNumber = document.getElementById('phoneNumber').value.trim();
        if (!fullName || !phoneNumber) {
            document.getElementById('form-message').textContent = 'Both fields are required.';
            return;
        }
        $.ajax({
            url: 'insert_contact.php',
            type: 'POST',
            data: { fullName: fullName, phoneNumber: phoneNumber },
            success: function (res) {
                res = res.trim();
                if (res === "success") {
                    Swal.fire({
                        icon: 'success', title: 'Success!', text: 'Contact added successfully.', confirmButtonColor: '#3085d6'
                    });
                    loadContacts();
                    document.querySelector('.contact-detailssssss').innerHTML = '';
                } else {
                    document.getElementById('form-message').textContent = "Contact wasn't added";
                }
            }, error: function () {
                document.getElementById('form-message').textContent = 'Error saving contact.';
            }
        });
    });
});

let contactsData = [];
function loadContacts() {
    $.ajax({
        url: 'get_contacts.php',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            contactsData = data;
            renderContacts();
        },
        error: function () {
            document.getElementById('contact-list-container').innerHTML = '<div class="contact-entry"><span>Error loading contacts.</span></div>';
        }
    });
}
function renderContacts() {
    const container = document.getElementById('contact-list-container');
    container.innerHTML = '';

    let searchValue = document.querySelector('.search-box').value.trim().toLowerCase();

    let filteredContacts = contactsData.filter(contact => {
        let name = (contact.name || '').toLowerCase();
        let number = (contact.from_number || '').toLowerCase();
        return name.includes(searchValue) || number.includes(searchValue);
    });

    if (filteredContacts.length === 0) {
        container.innerHTML = '<div class="contact-entry"><span>No contacts found.</span></div>';
        return;
    }

    filteredContacts.forEach(contact => {
        const div = document.createElement('div');
        div.className = 'contact-entry';
        div.innerHTML = `
            <div class="phone_no">
                <div class="Contact_name"><span>${contact.name}</span></div>
                <div class="phone_no"><span>${contact.from_number}</span></div>
            </div>
            <div class="action">
                <span class="action-label">Action ▼</span>
                <div class="dropdown-menu">
                    <div class="dropdown-item" onclick="sendMessageToContact('${contact.from_number}')">Send Message</div>
                    <div class="dropdown-item" onclick="deleteContact('${contact.from_number}')">Delete</div>
                </div>
            </div>`;
        container.appendChild(div);
    });
}
document.addEventListener('DOMContentLoaded', function () {
    document.querySelector('.search-box').addEventListener('input', renderContacts);
});
document.querySelector('[onclick*="showSection(\'contacts\'"]').addEventListener('click', loadContacts);

// delete and send message
function sendMessageToContact(phoneNumber) {
    showSection('conversation', { currentTarget: document.querySelector('[onclick*="showSection(\'conversation\'"]') });
    loadMessages(phoneNumber);
}
function deleteContact(phoneNumber) {
    if (confirm(`Are you sure you want to delete contact: ${phoneNumber}?`)) {
        $.ajax({
            url: 'delete_contact.php',
            type: 'POST',
            data: { phoneNumber: phoneNumber },
            success: function (res) {
                Swal.fire({
                    icon: 'success', title: 'Success!', text: 'Contact Delete Successfully.', confirmButtonColor: '#3085d6'
                });
                loadContacts();
            }, error: function () {
                alert('Error deleting contact');
            }
        });
    }
}

// ======= Show/Hide Section Logic (unchanged) =========

function showSection(sectionId, event) {
    const sections = document.querySelectorAll('.content-section');
    const navLinks = document.querySelectorAll('.nav-item');
    const titles = {
        'conversation': 'Conversation',
        'contacts': 'Contacts',
        'responses': 'Canned Responses',
        'profile': 'My Profile'
    };
    sections.forEach(sec => sec.classList.remove('active'));
    document.getElementById(sectionId).classList.add('active');
    navLinks.forEach(link => link.classList.remove('active'));
    if (event && event.currentTarget) event.currentTarget.classList.add('active');
    document.getElementById('section-title').innerHTML = `${titles[sectionId]} <img src="dashboard_image/icons8-question-mark-50.png">`;
}

// Toolbar checkbox logic
document.addEventListener('DOMContentLoaded', function () {
    const checkbox = document.getElementById('toolbar-check');
    const toolbar = document.querySelector('.toolbar-btn');
    const buttons = toolbar.querySelectorAll('.icon-btn');
    checkbox.addEventListener('change', function () {
    });
});
</script>
</body>
</html>
<?php } ?>
