<?php
// csr_manager/messages.php — full manager chat view
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$title = 'Messages';
if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }

require_once '../config/database.php';
require_once '../includes/chat_helper.php';
require_once '../includes/csr_report_helpers.php';

$database = new Database();
$db = $database->getConnection();
ensureCsrRoleSchema($db);

ensureChatTables($db);
releaseOverdueChatAssignments($db, 5);
sendDueAppointmentReminders($db);

$current_csr_id = (int)($_SESSION['csr_id'] ?? 0);
$current_csr_role = getCsrRoleForChat($db, $current_csr_id);
if ($current_csr_role !== 'csr_manager') { header('Location: dashboard.php'); exit(); }
$is_csr_manager = in_array($current_csr_role, ['team_leader','csr_manager'], true);
$team_members_for_manager = [];
if ($is_csr_manager) {
    try {
        $tmStmt = $db->query("SELECT cu.id, CONCAT(cu.first_name, ' ', cu.last_name) AS name, cu.email,
                                    COALESCE(GROUP_CONCAT(DISTINCT t.team_name ORDER BY t.team_name SEPARATOR ', '), 'No Team') AS team_name
                             FROM csr_users cu
                             LEFT JOIN csr_team_members ctm ON ctm.csr_id = cu.id
                             LEFT JOIN csr_teams t ON t.id = ctm.team_id AND t.is_active = 1
                             WHERE cu.is_active = 1 AND COALESCE(cu.role, 'csr') = 'csr'
                             GROUP BY cu.id, cu.first_name, cu.last_name, cu.email
                             ORDER BY team_name, cu.first_name, cu.last_name");
        $team_members_for_manager = $tmStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $team_members_for_manager = getTeamMembersForManager($db, $current_csr_id);
    }
}
$request_id = isset($_GET['request_id']) ? (int)$_GET['request_id'] : 0;

$conversationWhere = "";
$conversationParams = [];

if ($is_csr_manager) {
    // CSR Manager sees conversations for all teams/agents plus open queues.
    $conversationWhere = "
        WHERE cc.assigned_manager_id = :current_manager
           OR t.manager_id = :current_manager2
           OR cc.assigned_csr_id = :current_csr_for_manager
           OR COALESCE(cc.assignment_status, 'unassigned') IN ('unassigned','manager_queue','returned_queue','waiting_first_response','active')
    ";
    $conversationParams = [
        ':current_manager' => $current_csr_id,
        ':current_manager2' => $current_csr_id,
        ':current_csr_for_manager' => $current_csr_id
    ];
} else {
    $conversationWhere = "
        WHERE cc.assigned_csr_id = :current_csr
           OR (cc.assignment_status IN ('unassigned','returned_queue') AND cc.assigned_team_id IS NULL)
    ";
    $conversationParams = [':current_csr' => $current_csr_id];
}

$stmt = $db->prepare("
    SELECT 
        cc.*, 
        sr.request_number, 
        sr.full_name, 
        COALESCE(a.name, sr.manual_appliance_type, 'Service') AS appliance_name,
        js.status_name, 
        js.color_code,
        CONCAT(cu.first_name, ' ', cu.last_name) AS assigned_csr_name,
        t.team_name,
        t.manager_id,
        CONCAT(mgr.first_name, ' ', mgr.last_name) AS assigned_manager_name,
        (
            SELECT message 
            FROM chat_messages cm 
            WHERE cm.conversation_id = cc.id 
            ORDER BY cm.id DESC 
            LIMIT 1
        ) AS last_message,
        (
            SELECT created_at 
            FROM chat_messages cm 
            WHERE cm.conversation_id = cc.id 
            ORDER BY cm.id DESC 
            LIMIT 1
        ) AS last_message_at,
        (
            SELECT COUNT(*) 
            FROM chat_messages cm 
            WHERE cm.conversation_id = cc.id 
            AND cm.sender_type = 'customer' 
            AND (
                cc.last_csr_read_at IS NULL 
                OR cm.created_at > cc.last_csr_read_at
            )
        ) AS unread_count
    FROM chat_conversations cc
    JOIN service_requests sr ON sr.id = cc.request_id
    LEFT JOIN appliance_types a ON sr.appliance_type_id = a.id
    LEFT JOIN job_statuses js ON sr.job_status_id = js.id
    LEFT JOIN csr_users cu ON cu.id = cc.assigned_csr_id
    LEFT JOIN csr_teams t ON t.id = cc.assigned_team_id
    LEFT JOIN csr_users mgr ON mgr.id = COALESCE(cc.assigned_manager_id, t.manager_id)
    $conversationWhere
    ORDER BY cc.updated_at DESC
");
$stmt->execute($conversationParams);
$conversations = $stmt->fetchAll(PDO::FETCH_ASSOC);

$selected_request = null;
$assignment_info = null;

if ($request_id) {
    $stmt = $db->prepare("
        SELECT 
            sr.*, 
            COALESCE(a.name, sr.manual_appliance_type, 'Service') AS appliance_name, 
            js.status_name, 
            js.color_code
        FROM service_requests sr
        LEFT JOIN appliance_types a ON sr.appliance_type_id = a.id
        LEFT JOIN job_statuses js ON sr.job_status_id = js.id
        WHERE sr.id = :id 
        LIMIT 1
    ");

    $stmt->execute([':id' => $request_id]);
    $selected_request = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($selected_request && !empty($selected_request['customer_id'])) {
        getOrCreateConversation($db, $request_id, null);
        $assignment_info = getChatAssignmentInfo($db, $request_id, $current_csr_id);
        if ($current_csr_role === 'csr_manager' && $assignment_info) {
            if (($assignment_info['assignment_status'] ?? '') === 'manager_queue' && empty($assignment_info['assigned_csr_id'])) {
                $assignment_info['can_manage_team'] = true;
                $assignment_info['is_team_manager'] = true;
                $assignment_info['label'] = 'Manager Queue - assign to an agent';
            }
        }
    }
}

function csrChatLabelClass($conversation, $current_csr_id) {
    $status = $conversation['assignment_status'] ?? 'unassigned';
    $assigned = !empty($conversation['assigned_csr_id']) ? (int)$conversation['assigned_csr_id'] : null;
    if ($assigned && $assigned === (int)$current_csr_id) return 'mine';
    if ($status === 'manager_queue') return 'manager';
    if ($assigned) return 'locked';
    if ($status === 'returned_queue') return 'queue';
    return 'unassigned';
}

function csrChatLabelText($conversation, $current_csr_id) {
    $status = $conversation['assignment_status'] ?? 'unassigned';
    $assigned = !empty($conversation['assigned_csr_id']) ? (int)$conversation['assigned_csr_id'] : null;
    $name = $conversation['assigned_csr_name'] ?: 'CSR';
    if ($assigned && $assigned === (int)$current_csr_id && $status === 'waiting_first_response') return 'Waiting for you';
    if ($assigned && $assigned === (int)$current_csr_id) return 'Assigned to you';
    if ($status === 'manager_queue') return 'Manager Queue';
    if ($assigned && $status === 'waiting_first_response') return 'Waiting response';
    if ($assigned) return 'Locked';
    if ($status === 'returned_queue') return 'Returned queue';
    return 'Unassigned';
}

ob_start();
?>

<style>
:root {
    --csr-bg-1: #080240;
    --csr-bg-2: #093349;
    --csr-card-1: #17295e;
    --csr-card-2: #102448;
    --csr-border: rgba(96, 165, 250, 0.24);
    --csr-border-strong: rgba(56, 189, 248, 0.42);
    --csr-cyan: #17bdd4;
    --csr-blue: #1d9bf0;
    --csr-text: #f8fafc;
    --csr-muted: #aebbd4;
    --csr-soft: #d7e7ff;
}

body {
    background: linear-gradient(135deg, var(--csr-bg-1) 0%, var(--csr-bg-2) 100%) !important;
    color: var(--csr-text) !important;
}

.container-fluid,
.main-content,
.content-wrapper {
    background: transparent !important;
}

.messages-page-header {
    margin-bottom: 14px;
}

.messages-page-title {
    color: #ffffff !important;
    font-weight: 900 !important;
    letter-spacing: 0.2px;
    margin: 0;
}

.messages-page-subtitle {
    color: var(--csr-muted) !important;
    font-size: 13px;
}

.message-shell {
    display: grid;
    grid-template-columns: 350px 1fr;
    gap: 14px;
    height: calc(100vh - 190px);
    min-height: 560px;
    padding-bottom: 8px;
}

.conversation-list,
.csr-chat-panel {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    border: 1px solid rgba(56, 189, 248, 0.28);
    border-radius: 16px;
    box-shadow: 0 10px 24px rgba(0, 0, 0, 0.24), inset 0 0 0 1px rgba(255, 255, 255, 0.025);
    overflow: hidden;
}

.conversation-list {
    display: flex;
    flex-direction: column;
}

.conversation-list-header,
.chat-head {
    padding: 14px 16px;
    background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08));
    border-bottom: 1px solid rgba(56, 189, 248, 0.22);
    flex-shrink: 0;
}

.conversation-list-header h6,
.chat-head h6 {
    margin: 0;
    font-weight: 900;
    color: #ffffff;
}

.conversation-list-header small,
.chat-head small {
    color: var(--csr-muted) !important;
}

.conversation-scroll {
    overflow-y: auto;
    padding: 10px;
}

.conversation-scroll::-webkit-scrollbar,
.chat-body::-webkit-scrollbar,
.quick-replies::-webkit-scrollbar {
    width: 6px;
    height: 4px;
}

.conversation-scroll::-webkit-scrollbar-thumb,
.chat-body::-webkit-scrollbar-thumb,
.quick-replies::-webkit-scrollbar-thumb {
    background: rgba(96, 165, 250, 0.40);
    border-radius: 999px;
}

.conversation-item {
    padding: 14px;
    border: 1px solid rgba(96, 165, 250, 0.18);
    background: rgba(8, 20, 48, 0.35);
    border-radius: 14px;
    cursor: pointer;
    margin-bottom: 10px;
    transition: all 0.25s ease;
}

.conversation-item:hover {
    background: rgba(56, 189, 248, 0.10);
    border-color: rgba(56, 189, 248, 0.36);
    transform: translateY(-1px);
}

.conversation-item.active {
    background: linear-gradient(135deg, rgba(29, 155, 240, 0.20), rgba(23, 189, 212, 0.12));
    border-color: rgba(56, 189, 248, 0.48);
}

.conversation-title {
    font-weight: 900;
    color: #ffffff;
    font-size: 14px;
    line-height: 1.25;
}

.conversation-meta {
    color: var(--csr-soft) !important;
    font-size: 12px;
    margin-top: 4px;
}

.last-message {
    font-size: 12px;
    color: var(--csr-muted);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 6px;
}

.unread-pill {
    background: linear-gradient(135deg, #ef4444 0%, #f43f5e 100%);
    color: #fff;
    border-radius: 999px;
    padding: 3px 8px;
    font-size: 11px;
    font-weight: 900;
}

.chat-label {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    border-radius: 999px;
    padding: 4px 8px;
    font-size: 10px;
    font-weight: 900;
    margin-top: 8px;
}

.chat-label.mine {
    background: rgba(34, 197, 94, 0.16);
    color: #bbf7d0;
    border: 1px solid rgba(34, 197, 94, 0.34);
}

.chat-label.locked {
    background: rgba(248, 113, 113, 0.16);
    color: #fecaca;
    border: 1px solid rgba(248, 113, 113, 0.34);
}

.chat-label.queue {
    background: rgba(245, 158, 11, 0.16);
    color: #fde68a;
    border: 1px solid rgba(245, 158, 11, 0.34);
}

.chat-label.manager {
    background: rgba(29, 155, 240, 0.18);
    color: #dff7ff;
    border: 1px solid rgba(56, 189, 248, 0.38);
}

.team-assign-box {
    margin: 10px 14px 0;
    background: rgba(8, 20, 48, 0.52);
    border: 1px solid rgba(56, 189, 248, 0.28);
    border-radius: 14px;
    padding: 12px;
}

.team-assign-box label {
    color: #ffffff !important;
    font-weight: 900;
    font-size: 13px;
}

.team-assign-box .form-select {
    background: rgba(8, 20, 48, 0.72) !important;
    border: 1px solid rgba(96, 165, 250, 0.34) !important;
    color: #ffffff !important;
    border-radius: 10px !important;
}

.team-assign-box .form-select option { background: #102448; color: #ffffff; }

.chat-label.unassigned {
    background: rgba(56, 189, 248, 0.14);
    color: #dff7ff;
    border: 1px solid rgba(56, 189, 248, 0.34);
}

.csr-chat-panel {
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.status-badge {
    border-radius: 999px;
    padding: 5px 10px;
    color: #ffffff;
    font-size: 11px;
    font-weight: 900;
    white-space: nowrap;
}

.assignment-banner {
    padding: 10px 16px;
    border-bottom: 1px solid rgba(56, 189, 248, 0.18);
    background: rgba(8, 20, 48, 0.42);
    color: #d7e7ff;
    font-size: 13px;
    font-weight: 800;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.assignment-banner.mine {
    color: #bbf7d0;
}

.assignment-banner.locked {
    color: #fecaca;
}

.assignment-banner.queue,
.assignment-banner.unassigned {
    color: #fde68a;
}

.assignment-banner.manager {
    color: #dff7ff;
    background: rgba(29, 155, 240, 0.12);
}

.handle-chat-btn {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border: none !important;
    color: #ffffff !important;
    border-radius: 999px !important;
    font-size: 12px !important;
    font-weight: 900 !important;
    padding: 7px 12px !important;
    white-space: nowrap;
}

.chat-body {
    flex: 1;
    overflow-y: auto;
    padding: 18px;
    background: radial-gradient(circle at top left, rgba(56, 189, 248, 0.08), transparent 32%), rgba(8, 20, 48, 0.34);
    min-height: 0;
}

.msg-row {
    display: flex;
    margin-bottom: 12px;
}

.msg-row.csr { justify-content: flex-end; }
.msg-row.customer { justify-content: flex-start; }
.msg-row.system, .msg-row.bot { justify-content: center; }

.msg {
    max-width: 76%;
    padding: 11px 13px;
    border-radius: 16px;
    white-space: pre-wrap;
    word-break: break-word;
    line-height: 1.4;
    font-size: 14px;
    box-shadow: 0 8px 18px rgba(0, 0, 0, 0.16);
}

.msg.csr {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
    color: #ffffff;
    border-bottom-right-radius: 5px;
}

.msg.customer {
    background: rgba(248, 250, 252, 0.96);
    color: #111827;
    border: 1px solid rgba(255, 255, 255, 0.32);
    border-bottom-left-radius: 5px;
}

.msg.system,
.msg.bot {
    background: rgba(245, 158, 11, 0.16);
    color: #fde68a;
    border: 1px solid rgba(245, 158, 11, 0.32);
    max-width: 92%;
    text-align: center;
    border-radius: 14px;
}

.msg-meta {
    font-size: 10px;
    opacity: 0.76;
    margin-top: 5px;
}

.chat-footer {
    flex-shrink: 0;
    background: rgba(8, 20, 48, 0.72);
    border-top: 1px solid rgba(56, 189, 248, 0.22);
    padding: 10px 14px 12px;
}

.quick-replies {
    display: flex;
    gap: 7px;
    overflow-x: auto;
    padding-bottom: 9px;
}

.quick-replies .btn {
    border-radius: 999px !important;
    font-size: 12px;
    font-weight: 800;
    white-space: nowrap;
    color: #dff7ff !important;
    background: rgba(56, 189, 248, 0.10) !important;
    border: 1px solid rgba(56, 189, 248, 0.34) !important;
}

.quick-replies .btn:disabled,
.chat-input .form-control:disabled,
.chat-input .btn-primary:disabled {
    opacity: 0.52 !important;
    cursor: not-allowed !important;
}

.chat-input { margin: 0; }

.chat-input .input-group {
    background: rgba(8, 20, 48, 0.70);
    border: 1px solid rgba(96, 165, 250, 0.34);
    border-radius: 14px;
    overflow: hidden;
}

.chat-input .form-control {
    background: transparent !important;
    border: none !important;
    color: #ffffff !important;
    min-height: 46px;
    box-shadow: none !important;
}

.chat-input .form-control::placeholder {
    color: #aebbd4 !important;
    opacity: 1;
}

.chat-input .btn-primary {
    width: 52px;
    border-radius: 0 !important;
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border: none !important;
    color: #ffffff !important;
}

.empty-chat-state,
.empty-conversation-state {
    height: 100%;
    min-height: 340px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 28px;
    color: var(--csr-muted);
}

.empty-chat-state i,
.empty-conversation-state i {
    color: #dff7ff;
}

.empty-chat-state h5,
.empty-conversation-state h5 {
    color: #ffffff;
    font-weight: 900;
}

.text-muted { color: var(--csr-muted) !important; }

@media (max-width: 992px) {
    .message-shell { grid-template-columns: 300px 1fr; }
}

@media (max-width: 768px) {
    .message-shell {
        display: flex;
        flex-direction: column;
        height: calc(100vh - 155px);
        min-height: 0;
    }

    .conversation-list {
        height: 240px;
        flex-shrink: 0;
    }

    .csr-chat-panel {
        flex: 1;
        min-height: 420px;
    }

    .msg { max-width: 88%; }
    .chat-body { padding: 14px; }
    .assignment-banner { flex-direction: column; align-items: flex-start; }
}
</style>

<div class="messages-page-header">
    <h4 class="messages-page-title">
        <i class="fas fa-comments me-2"></i>Customer Messages
    </h4>
    <div class="messages-page-subtitle">Team Leader queueing, manager distribution, 5-minute first-response timeout, and CSR locking are enabled.</div>
</div>

<div class="message-shell">
    <div class="conversation-list">
        <div class="conversation-list-header">
            <h6>Conversations</h6>
            <small><?php echo $is_csr_manager ? 'Your team queue and assigned chats are shown here.' : 'Only chats assigned to you are shown here.'; ?></small>
        </div>

        <div class="conversation-scroll">
            <?php if(empty($conversations)): ?>
                <div class="empty-conversation-state">
                    <div>
                        <i class="fas fa-comments fa-2x mb-3"></i>
                        <h5>No conversations yet</h5>
                        <p>No customer messages are available right now.</p>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach($conversations as $c): ?>
                    <?php $labelClass = csrChatLabelClass($c, $current_csr_id); $labelText = csrChatLabelText($c, $current_csr_id); ?>
                    <div class="conversation-item <?php echo (int)$c['request_id'] === $request_id ? 'active' : ''; ?>" 
                         onclick="window.location.href='messages.php?request_id=<?php echo (int)$c['request_id']; ?>'">

                        <div class="d-flex justify-content-between gap-2 align-items-start">
                            <div class="conversation-title">
                                #<?php echo htmlspecialchars($c['request_number']); ?>
                            </div>

                            <?php if((int)$c['unread_count'] > 0): ?>
                                <span class="unread-pill"><?php echo (int)$c['unread_count']; ?></span>
                            <?php endif; ?>
                        </div>

                        <div class="conversation-meta">
                            <?php echo htmlspecialchars($c['full_name']); ?> • <?php echo htmlspecialchars($c['appliance_name']); ?>
                        </div>

                        <div class="last-message">
                            <?php echo htmlspecialchars($c['last_message'] ?? 'No messages yet'); ?>
                        </div>

                        <span class="chat-label <?php echo htmlspecialchars($labelClass); ?>">
                            <?php if($labelClass === 'locked'): ?><i class="fas fa-lock"></i><?php elseif($labelClass === 'mine'): ?><i class="fas fa-user-check"></i><?php elseif($labelClass === 'manager'): ?><i class="fas fa-people-group"></i><?php elseif($labelClass === 'queue'): ?><i class="fas fa-clock"></i><?php else: ?><i class="fas fa-inbox"></i><?php endif; ?>
                            <?php echo htmlspecialchars($labelText); ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="csr-chat-panel">
        <?php if(!$selected_request): ?>
            <div class="empty-chat-state">
                <div>
                    <i class="fas fa-message fa-3x mb-3"></i>
                    <h5>Select a conversation</h5>
                    <p>Choose a customer request on the left to start chatting.</p>
                </div>
            </div>
        <?php elseif(empty($selected_request['customer_id'])): ?>
            <div class="empty-chat-state">
                <div>
                    <i class="fas fa-user-slash fa-3x mb-3"></i>
                    <h5>No customer account attached</h5>
                    <p>This request was created without a customer login, so live chat is unavailable.</p>
                </div>
            </div>
        <?php else: ?>
            <?php
                $bannerClass = 'unassigned';
                if (!empty($assignment_info['is_mine'])) $bannerClass = 'mine';
                elseif (($assignment_info['assignment_status'] ?? '') === 'manager_queue') $bannerClass = 'manager';
                elseif (!empty($assignment_info['assigned_csr_id'])) $bannerClass = 'locked';
                elseif (($assignment_info['assignment_status'] ?? '') === 'returned_queue') $bannerClass = 'queue';
            ?>
            <div class="chat-head">
                <div class="d-flex justify-content-between align-items-start gap-2">
                    <div>
                        <h6>
                            #<?php echo htmlspecialchars($selected_request['request_number']); ?> - 
                            <?php echo htmlspecialchars($selected_request['full_name']); ?>
                        </h6>

                        <small>
                            <?php echo htmlspecialchars($selected_request['appliance_name']); ?> • 
                            <?php echo htmlspecialchars($selected_request['status_name']); ?>
                        </small>
                    </div>

                    <span class="status-badge" style="background-color: <?php echo htmlspecialchars($selected_request['color_code'] ?? '#1d9bf0'); ?>;">
                        <?php echo htmlspecialchars($selected_request['status_name']); ?>
                    </span>
                </div>
            </div>

            <div class="assignment-banner <?php echo htmlspecialchars($bannerClass); ?>" id="assignmentBanner">
                <span id="assignmentLabel">
                    <i class="fas fa-info-circle me-1"></i><?php echo htmlspecialchars($assignment_info['label'] ?? 'Unassigned'); ?>
                </span>

                <button class="btn handle-chat-btn" id="handleChatBtn" onclick="claimChat()" style="<?php echo (!empty($assignment_info['assigned_csr_id']) && empty($assignment_info['is_mine'])) || (($assignment_info['assignment_status'] ?? '') === 'manager_queue' && empty($assignment_info['is_team_manager'])) ? 'display:none;' : ''; ?>">
                    <i class="fas fa-hand-paper me-1"></i><?php echo (($assignment_info['assignment_status'] ?? '') === 'manager_queue') ? 'Handle Myself' : 'Handle Chat'; ?>
                </button>
            </div>

            <?php if(!empty($assignment_info['can_manage_team'])): ?>
                <div class="team-assign-box" id="teamAssignBox">
                    <label class="form-label mb-2"><i class="fas fa-user-plus me-1"></i>Assign this chat to an agent</label>
                    <div class="input-group">
                        <select class="form-select" id="teamCsrSelect">
                            <option value="">Select CSR from your team</option>
                            <?php foreach($team_members_for_manager as $member): ?>
                                <option value="<?php echo (int)$member['id']; ?>"><?php echo htmlspecialchars($member['name']); ?> - <?php echo htmlspecialchars($member['email']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button class="btn btn-primary" type="button" onclick="assignTeamChat()"><i class="fas fa-paper-plane me-1"></i>Assign</button>
                    </div>
                    <?php if(empty($team_members_for_manager)): ?>
                        <small class="text-warning d-block mt-2">No regular CSR agents were found yet. Ask Admin to add agents or assign team members.</small>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <div class="chat-body" id="chatBox"></div>

            <div class="chat-footer">
                <div class="quick-replies">
                    <button class="btn btn-outline-primary btn-sm quick-reply-btn" onclick="sendQuick('Hi! We are checking your request now and will update you shortly.')">Checking now</button>
                    <button class="btn btn-outline-primary btn-sm quick-reply-btn" onclick="sendQuick('Your request is already in progress. We will notify you once there is an update.')">In progress</button>
                    <button class="btn btn-outline-primary btn-sm quick-reply-btn" onclick="sendQuick('Please confirm your preferred appointment date and time.')">Confirm schedule</button>
                    <button class="btn btn-outline-primary btn-sm quick-reply-btn" onclick="sendQuick('Thank you for your patience. We will coordinate this with the technician.')">Coordinate tech</button>
                </div>

                <form class="chat-input" id="chatForm">
                    <div class="input-group">
                        <input type="text" class="form-control" id="messageInput" placeholder="Type your message..." autocomplete="off">
                        <button class="btn btn-primary" id="sendMessageBtn" type="submit"><i class="fas fa-paper-plane"></i></button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
const requestId = <?php echo $selected_request ? (int)$selected_request['id'] : 0; ?>;
const currentCsrId = <?php echo (int)$current_csr_id; ?>;
let lastId = 0;
let canReply = <?php echo !empty($assignment_info['can_reply']) && (!empty($assignment_info['is_mine']) || empty($assignment_info['assigned_csr_id'])) ? 'true' : 'false'; ?>;
let isMine = <?php echo !empty($assignment_info['is_mine']) ? 'true' : 'false'; ?>;

function escapeHtml(s) {
    return $('<div>').text(s || '').html();
}

function renderMessage(m) {
    let cls = m.sender_type;
    let name = '';

    if(m.sender_type === 'csr') name = (m.csr_name || 'CSR') + ' • ';
    if(m.sender_type === 'customer') name = 'Customer • ';
    if(m.sender_type === 'bot') name = 'Support Bot • ';
    if(m.sender_type === 'system') name = 'System • ';

    $('#chatBox').append(`
        <div class="msg-row ${cls}">
            <div class="msg ${cls}">
                ${escapeHtml(m.message)}
                <div class="msg-meta">${name}${escapeHtml(m.created_at)}</div>
            </div>
        </div>
    `);

    lastId = Math.max(lastId, parseInt(m.id));
    $('#chatBox').scrollTop($('#chatBox')[0].scrollHeight);
}

function updateAssignmentState(assignment) {
    if(!assignment) return;

    canReply = !!assignment.can_reply;
    isMine = !!assignment.is_mine;

    let label = assignment.label || 'Unassigned';
    let status = assignment.assignment_status || 'unassigned';
    let assignedId = assignment.assigned_csr_id ? parseInt(assignment.assigned_csr_id) : null;

    $('#assignmentLabel').html(`<i class="fas fa-info-circle me-1"></i>${escapeHtml(label)}`);

    $('#assignmentBanner')
        .removeClass('mine locked queue unassigned')
        .addClass(isMine ? 'mine' : (status === 'manager_queue' ? 'manager' : (assignedId ? 'locked' : (status === 'returned_queue' ? 'queue' : 'unassigned'))));

    if(isMine) {
        $('#messageInput').prop('disabled', false).attr('placeholder', 'Type your message...');
        $('#sendMessageBtn').prop('disabled', false);
        $('.quick-reply-btn').prop('disabled', false);
        $('#handleChatBtn').hide();
    } else if(status === 'manager_queue') {
        $('#messageInput').prop('disabled', true).attr('placeholder', assignment.can_manage_team ? 'Assign this chat to a CSR first, or click Handle Myself.' : 'Waiting for Team Leader assignment.');
        $('#sendMessageBtn').prop('disabled', true);
        $('.quick-reply-btn').prop('disabled', true);
        if (assignment.is_team_manager) { $('#handleChatBtn').show(); } else { $('#handleChatBtn').hide(); }
    } else if(!assignedId && (status === 'returned_queue' || status === 'unassigned')) {
        $('#messageInput').prop('disabled', true).attr('placeholder', 'Click Handle Chat to reply...');
        $('#sendMessageBtn').prop('disabled', true);
        $('.quick-reply-btn').prop('disabled', true);
        $('#handleChatBtn').show();
    } else {
        $('#messageInput').prop('disabled', true).attr('placeholder', 'This chat is locked by another CSR.');
        $('#sendMessageBtn').prop('disabled', true);
        $('.quick-reply-btn').prop('disabled', true);
        $('#handleChatBtn').hide();
    }
}

function loadMessages() {
    if(!requestId) return;

    $.getJSON('ajax/get_chat_messages.php', {
        request_id: requestId,
        last_id: lastId
    }, function(res) {
        if(res.success) {
            if(res.messages) res.messages.forEach(renderMessage);
            updateAssignmentState(res.assignment);
        }
    });
}

function assignTeamChat() {
    if(!requestId) return;
    const csrId = $('#teamCsrSelect').val();
    if(!csrId) {
        alert('Please select a CSR from your team.');
        return;
    }

    $.post('ajax/assign_team_chat.php', { request_id: requestId, csr_id: csrId }, function(res) {
        if(res.success) {
            $('#teamAssignBox').hide();
            updateAssignmentState(res.assignment);
            loadMessages();
        } else {
            alert(res.message || 'Unable to assign this chat.');
            loadMessages();
        }
    }, 'json');
}

function claimChat() {
    if(!requestId) return;

    $.post('ajax/claim_chat.php', { request_id: requestId }, function(res) {
        if(res.success) {
            updateAssignmentState(res.assignment);
        } else {
            alert(res.message || 'Unable to handle this chat.');
            loadMessages();
        }
    }, 'json');
}

function sendMessage(message) {
    if(!message.trim()) return;
    if(!isMine) {
        alert('Please click Handle Chat first, or wait until this chat is assigned to you.');
        return;
    }

    $.post('ajax/send_chat_message.php', {
        request_id: requestId,
        message: message
    }, function(res) {
        if(res.success) {
            $('#messageInput').val('');
            updateAssignmentState(res.assignment);
            loadMessages();
        } else {
            alert(res.message || 'Unable to send message');
            loadMessages();
        }
    }, 'json');
}

function sendQuick(message) {
    sendMessage(message);
}

$('#chatForm').on('submit', function(e) {
    e.preventDefault();
    sendMessage($('#messageInput').val());
});

if(requestId) {
    updateAssignmentState(<?php echo json_encode($assignment_info ?: []); ?>);
    loadMessages();
    setInterval(loadMessages, 3000);
}
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
