<?php
session_start();
require_once '../config/database.php';
require_once '../includes/chat_helper.php';

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

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

ensureChatTables($db);
sendDueAppointmentReminders($db);

$request_id = isset($_GET['request_id']) ? (int)$_GET['request_id'] : 0;

$requests_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.customer_id = :customer_id
    ORDER BY sr.requested_at DESC
");

$requests_stmt->execute([':customer_id' => $_SESSION['customer_id']]);
$requests = $requests_stmt->fetchAll(PDO::FETCH_ASSOC);

$selected_request = null;

if ($request_id) {
    foreach ($requests as $r) {
        if ((int)$r['id'] === $request_id) {
            $selected_request = $r;
            break;
        }
    }

    if ($selected_request) {
        getOrCreateConversation($db, $request_id);
    }
}

$pageTitle  = 'Messages';
$activePage = 'messages';
$notifCount = 0; // messages page doesn't need live count in the data section
include __DIR__ . '/includes/header.php';
?>
<style>
html,
body {
    min-height: 100vh;
    margin: 0;
}

body {
    background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
    margin-bottom: 72px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    color: #ffffff;
}

/* Header */
.app-header {
    background: rgba(15, 31, 74, 0.92) !important;
    padding: 12px 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.16);
    position: sticky;
    top: 0;
    z-index: 1000;
    border-bottom: 1px solid rgba(96, 165, 250, 0.16);
}

.header-content {
    display: grid;
    grid-template-columns: 40px 1fr 40px;
    align-items: center;
}

.back-btn {
    background: none;
    border: 0;
    font-size: 22px;
    color: #ffffff !important;
    padding: 0;
    cursor: pointer;
}

.header-title {
    font-weight: 800;
    font-size: 18px;
    color: #ffffff !important;
    text-align: center;
    letter-spacing: 0.2px;
}

/* Main Messenger Layout */
.messages-layout {
    display: grid;
    grid-template-columns: 360px 1fr;
    gap: 14px;
    padding: 14px;
    height: calc(100vh - 145px);
}

.requests-panel,
.chat-panel {
    background: rgba(8, 20, 48, 0.38);
    border: 1px solid rgba(96, 165, 250, 0.22);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 10px 24px rgba(0,0,0,0.22);
}

.requests-panel {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.panel-header {
    padding: 16px;
    border-bottom: 1px solid rgba(96, 165, 250, 0.18);
    background: linear-gradient(135deg, #17295e 0%, #102448 100%);
}

.panel-title {
    color: #ffffff;
    font-size: 17px;
    font-weight: 800;
    margin: 0 0 4px;
}

.panel-subtitle {
    color: #aebbd4;
    font-size: 13px;
    margin: 0;
}

.requests-list {
    padding: 12px;
    overflow-y: auto;
    flex: 1;
}

.requests-list::-webkit-scrollbar,
.chat-box::-webkit-scrollbar {
    width: 8px;
}

.requests-list::-webkit-scrollbar-thumb,
.chat-box::-webkit-scrollbar-thumb {
    background: rgba(56, 189, 248, 0.45);
    border-radius: 999px;
}

/* Request card */
.request-card {
    background: linear-gradient(135deg, #17295e 0%, #102448 100%) !important;
    border: 1px solid rgba(96, 165, 250, 0.22);
    border-radius: 14px;
    padding: 14px;
    margin-bottom: 10px;
    box-shadow: 0 10px 24px rgba(0,0,0,0.18);
    cursor: pointer;
    transition: all 0.2s ease;
}

.request-card:hover {
    transform: translateY(-2px);
    border-color: rgba(56, 189, 248, 0.45);
    box-shadow: 0 14px 30px rgba(0,0,0,0.28);
}

.request-card.active {
    border-color: rgba(56, 189, 248, 0.70);
    box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.16), 0 14px 30px rgba(0,0,0,0.28);
}

.request-card-top {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 10px;
}

.request-number {
    color: #f8fafc !important;
    font-weight: 800;
    font-size: 15px;
}

.request-appliance {
    color: #d7e7ff !important;
    font-size: 13px;
    margin-top: 3px;
}

.request-date {
    color: #aebbd4 !important;
    font-size: 12px;
    margin-top: 5px;
}

.request-date i {
    color: #dff7ff !important;
}

.status-badge {
    color: #ffffff !important;
    border-radius: 20px;
    font-size: 11px;
    padding: 5px 9px;
    white-space: nowrap;
    font-weight: 800;
    border: 1px solid rgba(255,255,255,0.12);
}

/* Empty card */
.empty-card {
    background: linear-gradient(135deg, #17295e 0%, #102448 100%) !important;
    border: 1px solid rgba(96, 165, 250, 0.22);
    color: #ffffff !important;
    box-shadow: 0 10px 24px rgba(0,0,0,0.22);
}

.empty-card h5 {
    color: #ffffff !important;
}

.empty-card p {
    color: #aebbd4 !important;
}

/* Chat panel */
.chat-panel {
    display: flex;
    flex-direction: column;
    min-width: 0;
    min-height: 0;
}

.chat-header {
    padding: 15px 16px;
    background: linear-gradient(135deg, #17295e 0%, #102448 100%);
    border-bottom: 1px solid rgba(96, 165, 250, 0.18);
}

.chat-selected-title {
    color: #ffffff !important;
    font-weight: 800;
    font-size: 16px;
    margin: 0;
}

.chat-selected-subtitle {
    color: #aebbd4 !important;
    font-size: 13px;
    margin: 3px 0 0;
}

.chat-header-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.change-request-link {
    color: #dff7ff !important;
    font-weight: 700;
    font-size: 12px;
    text-decoration: none;
    display: none;
}

.quick-actions {
    padding: 10px 12px;
    border-bottom: 1px solid rgba(96, 165, 250, 0.14);
    background: rgba(8, 20, 48, 0.28);
    display: flex;
    gap: 7px;
    overflow-x: auto;
}

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

.quick-btn:hover {
    background: rgba(56, 189, 248, 0.22) !important;
    color: #ffffff !important;
}

.chat-box {
    background: linear-gradient(135deg, rgba(8, 2, 64, 0.45), rgba(9, 51, 73, 0.45));
    padding: 18px;
    flex: 1;
    overflow-y: auto;
    min-height: 0;
}

/* Message bubbles */
.msg {
    max-width: 72%;
    padding: 11px 13px;
    border-radius: 16px;
    margin-bottom: 12px;
    white-space: pre-wrap;
    word-wrap: break-word;
    line-height: 1.35;
    box-shadow: 0 8px 18px rgba(0,0,0,0.14);
}

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

.msg.csr {
    background: rgba(255, 255, 255, 0.12);
    color: #ffffff;
    border: 1px solid rgba(96, 165, 250, 0.20);
    border-bottom-left-radius: 5px;
}

.msg.system,
.msg.bot {
    background: rgba(250, 204, 21, 0.14);
    color: #fef3c7;
    border: 1px solid rgba(250, 204, 21, 0.25);
    max-width: 88%;
    text-align: left;
}

.msg-meta {
    font-size: 10px;
    opacity: .78;
    margin-top: 6px;
}

/* Input */
.chat-input {
    background: rgba(8, 20, 48, 0.72);
    border-top: 1px solid rgba(96, 165, 250, 0.18);
    padding: 12px;
}

.chat-input .input-group {
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(96, 165, 250, 0.30);
    border-radius: 14px;
    overflow: hidden;
}

.chat-input .form-control {
    color: #ffffff !important;
    background: transparent !important;
    border: none !important;
    padding: 12px 14px;
    box-shadow: none !important;
}

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

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

/* No selected chat */
.no-chat-state {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    padding: 30px;
    color: #ffffff;
}

.no-chat-icon {
    width: 72px;
    height: 72px;
    background: rgba(56, 189, 248, 0.14);
    border: 1px solid rgba(56, 189, 248, 0.32);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #dff7ff;
    font-size: 30px;
    margin-bottom: 16px;
}

.no-chat-state h5 {
    color: #ffffff;
    font-weight: 800;
}

.no-chat-state p {
    color: #aebbd4;
    max-width: 360px;
}

/* Bottom nav */
.bottom-nav {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #080240;
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
    box-shadow: 0 -2px 12px rgba(0,0,0,0.22);
    border-top: 1px solid rgba(96, 165, 250, 0.18);
    z-index: 1000;
}

.nav-item {
    text-align: center;
    color: #aebbd4 !important;
    text-decoration: none;
    font-size: 12px;
    flex: 1;
}

.nav-item.active {
    color: #ffffff !important;
}

.nav-item i {
    font-size: 22px;
    display: block;
    margin-bottom: 4px;
    color: inherit !important;
}

.nav-item span {
    color: inherit !important;
}

@media (max-width: 900px) {
    .messages-layout {
        grid-template-columns: 1fr;
        height: auto;
        min-height: calc(100vh - 145px);
    }

    .requests-panel {
        <?php if($selected_request): ?>
        display: none;
        <?php endif; ?>
    }

    .chat-panel {
        min-height: calc(100vh - 165px);
    }

    .change-request-link {
        display: inline-flex;
    }

    .msg {
        max-width: 86%;
    }
}

@media (max-width: 576px) {
    .messages-layout {
        padding: 12px;
        gap: 12px;
    }

    .panel-header,
    .chat-header {
        padding: 14px;
    }

    .request-card {
        padding: 13px;
    }

    .chat-box {
        padding: 14px;
    }

    .quick-actions {
        padding: 9px 10px;
    }

    .msg {
        max-width: 90%;
    }
}
</style>

<link rel="stylesheet" href="../assets/portal-dark.css">

<style>
/* Final overrides after portal-dark.css */
body {
    background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
    color: #ffffff !important;
}

.app-header {
    background: rgba(15, 31, 74, 0.92) !important;
}

.header-title,
.back-btn {
    color: #ffffff !important;
}

.request-card,
.requests-panel,
.chat-panel {
    border-color: rgba(96, 165, 250, 0.22) !important;
}

.bottom-nav {
    background: #080240 !important;
}
</style>

<div class="messages-layout">

    <aside class="requests-panel">
        <div class="panel-header">
            <h5 class="panel-title">Service Requests</h5>
            <p class="panel-subtitle">Choose a request to start or continue a chat.</p>
        </div>

        <div class="requests-list">
            <?php if(empty($requests)): ?>

                <div class="text-center rounded-4 p-4 empty-card">
                    <i class="fas fa-comments fa-3x mb-3"></i>

                    <h5>No requests yet</h5>

                    <p>Create a repair request first before starting a support chat.</p>

                    <a href="request.php" class="btn btn-primary">
                        Request Service
                    </a>
                </div>

            <?php else: ?>

                <?php foreach($requests as $request): ?>
                    <?php $isActive = $selected_request && (int)$selected_request['id'] === (int)$request['id']; ?>

                    <div class="request-card <?php echo $isActive ? 'active' : ''; ?>" onclick="window.location.href='messages.php?request_id=<?php echo (int)$request['id']; ?>'">
                        <div class="request-card-top">
                            <div>
                                <strong class="request-number">
                                    #<?php echo htmlspecialchars($request['request_number']); ?>
                                </strong>

                                <div class="request-appliance">
                                    <?php echo htmlspecialchars($request['appliance_name']); ?> Repair
                                </div>

                                <div class="request-date">
                                    <i class="far fa-calendar me-1"></i>
                                    <?php echo date('M d, Y', strtotime($request['requested_at'])); ?>
                                </div>
                            </div>

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

                <?php endforeach; ?>

            <?php endif; ?>
        </div>
    </aside>

    <main class="chat-panel">
        <?php if(!$selected_request): ?>

            <div class="no-chat-state">
                <div class="no-chat-icon">
                    <i class="fas fa-comments"></i>
                </div>

                <h5>Select a request</h5>
                <p>Pick a service request from the left side to open its support conversation.</p>
            </div>

        <?php else: ?>

            <div class="chat-header">
                <div class="chat-header-row">
                    <div>
                        <a href="messages.php" class="change-request-link mb-1">
                            <i class="fas fa-chevron-left me-1"></i>
                            Change request
                        </a>

                        <h6 class="chat-selected-title">
                            #<?php echo htmlspecialchars($selected_request['request_number']); ?> -
                            <?php echo htmlspecialchars($selected_request['appliance_name']); ?>
                        </h6>

                        <p class="chat-selected-subtitle">
                            Support chat connected to this request
                        </p>
                    </div>

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

            <div class="quick-actions">
                <button class="btn quick-btn" onclick="sendQuick('Can I get an update on my technician?')">
                    Track Technician
                </button>

                <button class="btn quick-btn" onclick="sendQuick('I would like to reschedule my appointment.')">
                    Reschedule
                </button>

                <button class="btn quick-btn" onclick="sendQuick('I have a billing concern.')">
                    Billing Concern
                </button>

                <button class="btn quick-btn" onclick="sendQuick('I would like to talk to a CSR.')">
                    Talk to CSR
                </button>
            </div>

            <div class="chat-box" id="chatBox"></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" type="submit">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </form>

        <?php endif; ?>
    </main>

</div>

<?php include __DIR__ . '/includes/footer.php'; ?>

<script>
const requestId = <?php echo $selected_request ? (int)$selected_request['id'] : 0; ?>;
let lastId = 0;

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 === 'bot') {
        name = 'Support Bot • ';
    }

    if(m.sender_type === 'system') {
        name = 'System • ';
    }

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

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

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

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

function sendMessage(message) {
    if(!message.trim()) return;

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

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

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

if(requestId) {
    loadMessages();
    setInterval(loadMessages, 3000);
}
</script>

</body>
</html>