<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT'] . '/digital_pos/includes/config.php');

if (!isset($_SESSION['user_id'])) {
    header('Location: /digital_pos/index.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// Pagination
$limit = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Search
$search = trim($_GET['search'] ?? '');
$search_sql = '%' . $search . '%';

// Count total threads query
$count_sql = "
    SELECT COUNT(*) AS thread_count
    FROM (
        SELECT COALESCE(reply_to, id) AS thread_id
        FROM messages
        WHERE (receiver_id = ? OR sender_id = ?) AND (subject LIKE ? OR body LIKE ?)
        GROUP BY thread_id
    ) grouped
";
$count_stmt = $conn->prepare($count_sql);
$count_stmt->bind_param("iiss", $user_id, $user_id, $search_sql, $search_sql);
$count_stmt->execute();
$count_stmt->bind_result($total_threads);
$count_stmt->fetch();
$count_stmt->close();

$total_pages = max(1, ceil($total_threads / $limit));

// Main threads query
$threads_sql = "
    SELECT 
        m.id AS message_id,
        m.subject,
        m.body,
        m.created_at,
        u.username AS sender_name,
        COALESCE(m.reply_to, m.id) AS thread_id,
        IFNULL(unread_counts.unread_count, 0) AS unread_count,
        m.is_read
    FROM (
        SELECT 
            COALESCE(reply_to, id) AS thread_id,
            MAX(id) AS latest_msg_id
        FROM messages
        WHERE (receiver_id = ? OR sender_id = ?) AND (subject LIKE ? OR body LIKE ?)
        GROUP BY thread_id
        ORDER BY MAX(created_at) DESC
        LIMIT ? OFFSET ?
    ) t
    JOIN messages m ON m.id = t.latest_msg_id
    JOIN users u ON m.sender_id = u.id
    LEFT JOIN (
        SELECT 
            COALESCE(reply_to, id) AS thread_id,
            COUNT(*) AS unread_count
        FROM messages
        WHERE receiver_id = ? AND is_read = 0
        GROUP BY thread_id
    ) unread_counts ON unread_counts.thread_id = t.thread_id
    ORDER BY unread_count DESC, m.created_at DESC
";

$stmt = $conn->prepare($threads_sql);
$stmt->bind_param("iissiii", $user_id, $user_id, $search_sql, $search_sql, $limit, $offset, $user_id);
$stmt->execute();
$result = $stmt->get_result();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Inbox - Threads</title>
    <link rel="stylesheet" href="/digital_pos/css/messaging.s" />
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            display: flex;
            background-color: #f1f3f4;
            height: 100vh;
        }

        .sidebar {
            width: 240px;
            background-color: #fff;
            padding: 20px;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
        }

        .sidebar h3 {
            margin-bottom: 20px;
            color: #202124;
        }

        .sidebar a {
            display: block;
            color: #202124;
            padding: 10px 15px;
            margin-bottom: 8px;
            border-radius: 4px;
            text-decoration: none;
        }

        .sidebar a:hover,
        .sidebar a.active {
            background-color: #e8f0fe;
            color: #1a73e8;
        }

        .main-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }

        h2 {
            margin-top: 0;
        }

        .flash.success { background-color: #d4edda; padding: 10px; margin-bottom: 15px; border-radius: 4px; }
        .flash.error { background-color: #f8d7da; padding: 10px; margin-bottom: 15px; border-radius: 4px; }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            border-radius: 6px;
            overflow: hidden;
        }

        table th, table td {
            padding: 12px;
            border-bottom: 1px solid #ddd;
            text-align: left;
        }

        tr:hover {
            background-color: #f5f5f5;
            cursor: pointer;
        }

        .unread {
            font-weight: bold;
            background-color: #e8f0fe;
        }

        .pagination {
            margin-top: 15px;
            display: flex;
            gap: 8px;
        }

        .pagination a {
            padding: 6px 12px;
            text-decoration: none;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .pagination a.active {
            background-color: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        #inbox-badge {
            background: red;
            color: white;
            font-size: 12px;
            border-radius: 50%;
            padding: 2px 8px;
            vertical-align: top;
            display: none;
        }

        form[method="GET"] {
            margin-bottom: 15px;
        }

        form input[type="text"] {
            padding: 6px;
            width: 250px;
        }

        form button {
            padding: 6px 12px;
            background-color: #1a73e8;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        form button:hover {
            background-color: #155db2;
        }

        .snippet {
            color: #666;
        }
    </style>
</head>
<body>

<!-- Sidebar -->
<div class="sidebar">
    <h3>Messaging</h3>
    <a href="inbox.php" class="active">Inbox</a>
    <a href="sent.php">Sent</a>
    <a href="compose.php">Compose</a>
</div>

<!-- Main content -->
<div class="main-content">
    <h2>Inbox <span id="inbox-badge" title="Unread messages"></span></h2>

    <?php
    if (!empty($_SESSION['flash'])) {
        foreach ($_SESSION['flash'] as $type => $message) {
            echo "<div class='flash $type'>" . htmlspecialchars($message) . "</div>";
        }
        unset($_SESSION['flash']);
    }
    ?>

    <form method="GET" action="inbox.php">
        <input type="text" name="search" placeholder="Search subject/body" value="<?= htmlspecialchars($search) ?>" />
        <button type="submit">Search</button>
    </form>

    <table id="inboxTable" aria-label="Inbox message threads">
        <thead>
        <tr>
            <th scope="col">From</th>
            <th scope="col">Subject</th>
            <th scope="col">Preview</th>
            <th scope="col">Date</th>
            <th scope="col">Unread</th>
        </tr>
        </thead>
        <tbody>
        <?php if ($total_threads == 0): ?>
            <tr><td colspan="5" style="text-align:center;">No messages found.</td></tr>
        <?php else: ?>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr data-thread-id="<?= htmlspecialchars($row['thread_id']) ?>" class="<?= ($row['unread_count'] > 0) ? 'unread' : '' ?>" tabindex="0" title="Click to view thread">
                    <td><?= htmlspecialchars($row['sender_name']) ?></td>
                    <td title="<?= htmlspecialchars($row['subject']) ?>"><?= htmlspecialchars($row['subject']) ?></td>
                    <td class="snippet" title="<?= htmlspecialchars($row['body']) ?>"><?= htmlspecialchars($row['body']) ?></td>
                    <td><?= date("Y-m-d H:i", strtotime($row['created_at'])) ?></td>
                    <td><?= $row['unread_count'] > 0 ? (int)$row['unread_count'] : '' ?></td>
                </tr>
            <?php endwhile; ?>
        <?php endif; ?>
        </tbody>
    </table>

    <!-- Pagination -->
    <div class="pagination" aria-label="Page navigation">
        <?php
        $query_string = $_GET;
        for ($i = 1; $i <= $total_pages; $i++):
            $query_string['page'] = $i;
            $query_str = http_build_query($query_string);
            ?>
            <a href="inbox.php?<?= $query_str ?>" class="<?= $i === $page ? 'active' : '' ?>" aria-current="<?= $i === $page ? 'page' : '' ?>"><?= $i ?></a>
        <?php endfor; ?>
    </div>
</div>

<script>
    document.querySelectorAll('#inboxTable tbody tr').forEach(row => {
        row.addEventListener('click', () => {
            const threadId = row.getAttribute('data-thread-id');
            window.location.href = 'view_thread.php?thread_id=' + encodeURIComponent(threadId);
        });
        row.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                row.click();
            }
        });
    });

    setTimeout(() => {
        document.querySelectorAll('.flash').forEach(el => el.style.display = 'none');
    }, 4000);

    function updateUnreadThreads() {
        fetch('/digital_pos/pages/shared/messaging/unread_count.php')
            .then(res => res.json())
            .then(data => {
                if (!data.success) return;

                const badge = document.getElementById('inbox-badge');
                if (data.count > 0) {
                    badge.innerText = data.count;
                    badge.style.display = 'inline-block';
                } else {
                    badge.style.display = 'none';
                }

                const unreadMap = {};
                data.threads.forEach(thread => {
                    unreadMap[thread.thread_id] = thread.unread_count;
                });

                document.querySelectorAll('#inboxTable tbody tr[data-thread-id]').forEach(row => {
                    const threadId = row.getAttribute('data-thread-id');
                    const unreadCount = unreadMap[threadId] || 0;
                    const unreadCell = row.querySelector('td:last-child');
                    if (unreadCount > 0) {
                        unreadCell.textContent = unreadCount;
                        row.classList.add('unread');
                    } else {
                        unreadCell.textContent = '';
                        row.classList.remove('unread');
                    }
                });
            })
            .catch(console.error);
    }

    updateUnreadThreads();
    setInterval(updateUnreadThreads, 60000);
</script>

</body>
</html>

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