<?php
session_start();
include 'dbconnect.php'; // ✅ Ensure $con is defined properly

$today = date('Y-m-d');

// 🔔 Notification: Show next_day_plan_date matches for today
$notif_sql = "SELECT * FROM client_agent_conversations WHERE next_day_plan_date = ?";
$notif_stmt = $con->prepare($notif_sql);
$notif_stmt->bind_param("s", $today);
$notif_stmt->execute();
$notif_res = $notif_stmt->get_result();

// 🔍 Filters
$search_name = $_GET['search_name'] ?? "";
$from_date = $_GET['from_date'] ?? "";
$to_date = $_GET['to_date'] ?? "";

$limit = 10;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$where = [];
$params = [];
$types = "";

// Build WHERE clause
if (!empty($search_name)) {
    $where[] = "client_name LIKE ?";
    $params[] = "%$search_name%";
    $types .= "s";
}

if (!empty($from_date) && !empty($to_date)) {
    $where[] = "conversation_date BETWEEN ? AND ?";
    $params[] = $from_date;
    $params[] = $to_date;
    $types .= "ss";
} elseif (!empty($from_date)) {
    $where[] = "conversation_date >= ?";
    $params[] = $from_date;
    $types .= "s";
} elseif (!empty($to_date)) {
    $where[] = "conversation_date <= ?";
    $params[] = $to_date;
    $types .= "s";
}

$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// 🧮 Count total records
$count_sql = "SELECT COUNT(*) AS total FROM client_agent_conversations $where_sql";
$count_stmt = $con->prepare($count_sql);
if ($types) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$count_result = $count_stmt->get_result()->fetch_assoc();
$total_records = $count_result['total'];
$total_pages = ceil($total_records / $limit);

// 📥 Get paginated data
$data_sql = "SELECT * FROM client_agent_conversations $where_sql ORDER BY conversation_date DESC LIMIT ?, ?";
$data_stmt = $con->prepare($data_sql);

if ($types) {
    $bind_types = $types . "ii";
    $bind_params = array_merge($params, [$offset, $limit]);
    $data_stmt->bind_param($bind_types, ...$bind_params);
} else {
    $data_stmt->bind_param("ii", $offset, $limit);
}

$data_stmt->execute();
$data_res = $data_stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>All Conversations</title>
    <style>
        /* General Body */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 30px;
            background: #e0f7fa;
            color: #004d40;
        }

        h2 {
            color: #00796b;
            margin-bottom: 15px;
        }

        /* Logout Button */
        .logout-btn {
            float: right;
            background-color: #d32f2f;
            color: white;
            border: none;
            padding: 8px 16px;
            font-size: 14px;
            cursor: pointer;
            border-radius: 4px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            font-weight: 600;
        }
        .logout-btn:hover {
            background-color: #b71c1c;
        }
        .logout-btn svg {
            width: 16px;
            height: 16px;
            fill: white;
        }

        /* Notification marquee container */
        .notification-marquee {
            background: #fff3cd;
            border: 1px solid #ffeeba;
            color: #856404;
            padding: 12px 20px;
            border-radius: 6px;
            margin-bottom: 25px;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .notification-marquee svg {
            fill: #856404;
            width: 20px;
            height: 20px;
            flex-shrink: 0;
        }

        /* Filter Form */
        .filter-form {
            margin-bottom: 20px;
            background: #ffffffcc;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .filter-form input[type="text"],
        .filter-form input[type="date"] {
            padding: 8px;
            margin-right: 12px;
            border: 1px solid #00796b;
            border-radius: 4px;
            font-size: 14px;
        }

        .filter-form input[type="submit"] {
            background-color: #00796b;
            border: none;
            padding: 8px 18px;
            color: white;
            font-weight: 600;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .filter-form input[type="submit"]:hover {
            background-color: #004d40;
        }

        /* Table styles */
        table {
            width: 100%;
            border-collapse: collapse;
            background-color: #ffffffcc;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        thead {
            background-color: #004d40;
            color: #e0f2f1;
        }

        th, td {
            padding: 12px 15px;
            border-bottom: 1px solid #b2dfdb;
            text-align: left;
            vertical-align: top;
        }

        tbody tr:nth-child(even) {
            background-color: #e0f2f1;
        }

        tbody tr:hover {
            background-color: #b2dfdb;
            cursor: pointer;
        }

        /* Pagination */
        .pagination {
            margin-top: 25px;
            text-align: center;
        }

        .pagination a,
        .pagination span {
            display: inline-block;
            padding: 8px 14px;
            margin: 3px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 600;
            font-size: 14px;
            border: 1px solid #00796b;
            color: #004d40;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .pagination a:hover {
            background-color: #00796b;
            color: white;
        }

        .pagination .active {
            background-color: #004d40;
            color: white;
            border-color: #004d40;
        }

        /* Actions column */
        .actions a {
            color: #d32f2f;
            font-weight: 700;
            text-decoration: none;
        }
        .actions a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>

    <!-- Logout button -->
    <a href="logout.php" class="logout-btn" title="Logout">
        <!-- Simple logout SVG icon -->
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M16 13v-2H7V8l-5 4 5 4v-3zM20 19h-8v-2h8v-10h-8v-2h8c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2z"/></svg>
        Logout
    </a>

    <h2>All Conversations</h2>

    <!-- Notification marquee -->
    <?php if ($notif_res->num_rows > 0): ?>
        <div class="notification-marquee">
            <!-- Notification bell icon SVG -->
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 22c1.1 0 2-.9 2-2h-4a2 2 0 002 2zm6-6V9c0-3.07-1.63-5.64-4.5-6.32V2a1.5 1.5 0 00-3 0v.68C7.63 3.36 6 5.92 6 9v7l-2 2v1h16v-1l-2-2z"/></svg>
            <marquee behavior="scroll" direction="left" scrollamount="6" onmouseover="this.stop();" onmouseout="this.start();">
                <?php
                $messages = [];
                $notif_res->data_seek(0); // Reset pointer
                while ($n = $notif_res->fetch_assoc()) {
                    $messages[] = "Reminder: <strong>" . htmlspecialchars($n['client_name']) . "</strong> has plan today — " . htmlspecialchars($n['next_day_plan']);
                }
                echo implode(" &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; ", $messages);
                ?>
            </marquee>
        </div>
    <?php endif; ?>

    <!-- Filter Form -->
    <form method="get" class="filter-form">
        <input type="text" name="search_name" placeholder="Search Client Name" value="<?php echo htmlspecialchars($search_name); ?>" />
        <label>From:</label>
        <input type="date" name="from_date" value="<?php echo htmlspecialchars($from_date); ?>" />
        <label>To:</label>
        <input type="date" name="to_date" value="<?php echo htmlspecialchars($to_date); ?>" />
        <input type="submit" value="Filter" />
    </form>

    <!-- Data Table -->
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Client</th>
                <th>Agent</th>
                <th>Topic</th>
                <th>Date</th>
                <th>Client Msg</th>
                <th>Agent Reply</th>
                <th>Next Plan</th>
                <th>Plan Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($data_res->num_rows > 0): ?>
                <?php while ($row = $data_res->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $row['id']; ?></td>
                        <td><?php echo htmlspecialchars($row['client_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['agent_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['topic']); ?></td>
                        <td><?php echo $row['conversation_date']; ?></td>
                        <td><?php echo nl2br(htmlspecialchars($row['client_message'])); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($row['agent_reply'])); ?></td>
                        <td><?php echo htmlspecialchars($row['next_day_plan']); ?></td>
                        <td><?php echo $row['next_day_plan_date']; ?></td>
                        <td class="actions">
                            <a href="condelete.php?id=<?php echo $row['id']; ?>" onclick="return confirm('Are you sure?');" title="Delete">&#128465;</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="10" style="text-align:center; font-style:italic;">No records found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Pagination -->
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search_name=<?php echo urlencode($search_name); ?>&from_date=<?php echo urlencode($from_date); ?>&to_date=<?php echo urlencode($to_date); ?>">&laquo; Prev</a>
        <?php endif; ?>

        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <?php if ($i == $page): ?>
                <span class="active"><?php echo $i; ?></span>
            <?php else: ?>
                <a href="?page=<?php echo $i; ?>&search_name=<?php echo urlencode($search_name); ?>&from_date=<?php echo urlencode($from_date); ?>&to_date=<?php echo urlencode($to_date); ?>"><?php echo $i; ?></a>
            <?php endif; ?>
        <?php endfor; ?>

        <?php if ($page < $total_pages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search_name=<?php echo urlencode($search_name); ?>&from_date=<?php echo urlencode($from_date); ?>&to_date=<?php echo urlencode($to_date); ?>">Next &raquo;</a>
        <?php endif; ?>
    </div>

</body>
</html>
