<?php
session_start();
include('../../../includes/config.php');

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

$user_id = $_SESSION['user_id'];

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

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

// Count total threads sent by user
$count_sql = "
    SELECT COUNT(DISTINCT COALESCE(m.reply_to, m.id)) AS thread_count
    FROM messages m
    WHERE m.sender_id = ? AND (m.subject LIKE ? OR m.body LIKE ?)
";
$count_stmt = $conn->prepare($count_sql);
$count_stmt->bind_param("iss", $user_id, $search_sql, $search_sql);
$count_stmt->execute();
$count_stmt->bind_result($totalThreads);
$count_stmt->fetch();
$count_stmt->close();

$totalPages = ceil($totalThreads / $perPage);

// Fetch threads with latest message
$query = "
    SELECT 
        t.thread_id,
        MAX(t.message_id) AS latest_id,
        MAX(t.subject) AS subject,
        MAX(t.body) AS body,
        MAX(t.created_at) AS created_at,
        MAX(t.receiver_name) AS receiver_name
    FROM (
        SELECT 
            COALESCE(m.reply_to, m.id) AS thread_id,
            m.id AS message_id,
            m.subject,
            m.body,
            m.created_at,
            CONCAT(u.first_name, ' ', u.last_name) AS receiver_name
        FROM messages m
        JOIN users u ON m.receiver_id = u.id
        WHERE m.sender_id = ? AND (m.subject LIKE ? OR m.body LIKE ?)
    ) t
    GROUP BY t.thread_id
    ORDER BY MAX(t.created_at) DESC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($query);
$stmt->bind_param("issii", $user_id, $search_sql, $search_sql, $perPage, $offset);
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Sent Messages</title>
    <link rel="stylesheet" href="../../../css/messagin" />
    <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;
        }

        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;
        }

        .snippet {
            color: #666;
        }

        .view-link {
            text-decoration: none;
            color: #1a73e8;
            font-weight: bold;
        }

        .view-link:hover {
            text-decoration: underline;
        }

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

        .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;
        }

        form {
            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;
        }

    </style>
</head>
<body>

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

<!-- Main Content -->
<div class="main-content">
    <h2>Sent Messages</h2>

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

    <table id="messagesTable" aria-label="Sent Threads">
        <thead>
            <tr>
                <th>Subject</th>
                <th>Recipient</th>
                <th>Preview</th>
                <th>Date Sent</th>
                <th>View</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($row['subject']) ?></td>
                    <td><?= htmlspecialchars($row['receiver_name']) ?></td>
                    <td class="snippet"><?= htmlspecialchars($row['body']) ?></td>
                    <td><?= date('Y-m-d H:i', strtotime($row['created_at'])) ?></td>
                    <td><a class="view-link" href="view_thread.php?thread_id=<?= (int)$row['thread_id'] ?>">View</a></td>
                </tr>
            <?php endwhile; ?>
            <?php if ($result->num_rows === 0): ?>
                <tr><td colspan="5" style="text-align:center; color:#777;">No sent threads found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Pagination -->
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">&laquo; Prev</a>
        <?php endif; ?>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="<?= $i === $page ? 'active' : '' ?>"><?= $i ?></a>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
            <a href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next &raquo;</a>
        <?php endif; ?>
    </div>
</div>

</body>
</html>

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