<?php

include '../../includes/header.php';

$auth = new Auth($conn);
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);

require_once __DIR__ . '/../../classes/MailboxService.php';

$accounts = MailboxService::listAccounts($conn);

$accountId = (int)($_GET['account_id'] ?? 0);
if (!$accountId || !in_array($accountId, array_column($accounts, 'account_id'), true)) {
    $default = null;
    foreach ($accounts as $account) {
        if ($account['is_default']) { $default = $account; break; }
    }
    $accountId = (int)($default['account_id'] ?? ($accounts[0]['account_id'] ?? 0));
}

$mailboxService = $accountId ? new MailboxService($conn, $accountId) : null;
$isConfigured = $mailboxService ? $mailboxService->isConfigured() : false;
?>

<style>
    .mail-app {
        display: flex;
        height: calc(100vh - 180px);
        min-height: 520px;
        border: 1px solid #dee2e6;
        border-radius: 6px;
        overflow: hidden;
        background: #fff;
    }

    .mail-folders {
        width: 200px;
        flex-shrink: 0;
        background: #f8f9fa;
        border-right: 1px solid #dee2e6;
        overflow-y: auto;
        padding: 10px 0;
    }

    .mail-folders .folder-item {
        display: block;
        padding: 8px 16px;
        color: #333;
        text-decoration: none;
        border-radius: 0 20px 20px 0;
        margin-right: 8px;
        font-size: 0.9rem;
        cursor: pointer;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .mail-folders .folder-item:hover {
        background: #e9ecef;
    }

    .mail-folders .folder-item.active {
        background: #d2e3fc;
        color: #1a73e8;
        font-weight: 600;
    }

    .mail-list {
        width: 340px;
        flex-shrink: 0;
        border-right: 1px solid #dee2e6;
        overflow-y: auto;
    }

    .mail-list .mail-row {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 14px;
        border-bottom: 1px solid #f1f1f1;
        cursor: pointer;
        font-size: 0.87rem;
    }

    .mail-list .mail-row:hover {
        background: #f8f9fa;
        box-shadow: inset 1px 0 0 #dee2e6, 0 1px 2px 0 rgba(0,0,0,.1);
    }

    .mail-list .mail-row.active {
        background: #d2e3fc;
    }

    .mail-list .mail-row.unread {
        font-weight: 700;
    }

    .mail-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.8rem;
        flex-shrink: 0;
    }

    .mail-row-body {
        min-width: 0;
        flex: 1;
    }

    .mail-row-from {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .mail-row-subject {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #555;
    }

    .mail-row-date {
        font-size: 0.75rem;
        color: #888;
        flex-shrink: 0;
    }

    .mail-row-delete {
        color: #999;
        flex-shrink: 0;
        padding: 4px 6px;
        border-radius: 4px;
    }

    .mail-row-delete:hover {
        color: #d93025;
        background: #fde8e6;
    }

    .mail-reading-pane {
        flex: 1;
        overflow-y: auto;
        padding: 20px;
        display: flex;
        flex-direction: column;
    }

    .mail-reading-pane iframe {
        flex: 1;
        width: 100%;
        min-height: 300px;
        border: none;
    }

    .mail-empty-state {
        margin: auto;
        color: #999;
        text-align: center;
    }

    .compose-panel {
        position: fixed;
        bottom: 0;
        right: 30px;
        width: 420px;
        background: #fff;
        border: 1px solid #dee2e6;
        border-radius: 8px 8px 0 0;
        box-shadow: 0 4px 20px rgba(0,0,0,.2);
        z-index: 1050;
        display: none;
    }

    .compose-panel.open {
        display: block;
    }

    .compose-header {
        background: #404040;
        color: #fff;
        padding: 10px 14px;
        border-radius: 8px 8px 0 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
    }

    .compose-body {
        padding: 12px;
    }

    .compose-body input, .compose-body textarea {
        border: none;
        border-bottom: 1px solid #eee;
        border-radius: 0;
        box-shadow: none;
    }

    .compose-body input:focus, .compose-body textarea:focus {
        box-shadow: none;
        border-bottom-color: #1a73e8;
    }
</style>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12 d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-1">
                        <li class="breadcrumb-item"><a href="../dashboard/admin.php">Dashboard</a></li>
                        <li class="breadcrumb-item active">Emails</li>
                    </ol>
                </nav>
                <h2><i class="fas fa-envelope"></i> Emails</h2>
            </div>
            <div class="d-flex align-items-center gap-2">
                <?php if (count($accounts) > 1): ?>
                    <form method="GET" class="d-flex align-items-center gap-1 mb-0">
                        <select name="account_id" class="form-select form-select-sm" style="width:auto;" onchange="this.form.submit()">
                            <?php foreach ($accounts as $account): ?>
                                <option value="<?php echo (int)$account['account_id']; ?>" <?php echo $account['account_id'] == $accountId ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($account['account_label']); ?><?php echo $account['branch_name'] ? ' (' . htmlspecialchars($account['branch_name']) . ')' : ' (Head Office)'; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                <?php endif; ?>
                <a href="../admin/settings.php#mailbox-accounts" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-cog"></i> Settings
                </a>
            </div>
        </div>
    </div>

    <?php if (!$accounts): ?>
        <div class="alert alert-warning mt-3">
            No mailbox accounts have been set up yet. Go to
            <a href="../admin/settings.php#mailbox-accounts">Settings &gt; Mailbox Accounts</a> to create one.
        </div>
    <?php elseif (!$isConfigured): ?>
        <div class="alert alert-warning mt-3">
            This mailbox account isn't fully configured yet. Go to
            <a href="../admin/settings.php#mailbox-accounts">Settings &gt; Mailbox Accounts</a> to set the
            mailbox address, password, and server details before using this inbox.
        </div>
    <?php else: ?>
        <div class="mail-app mt-3">
            <div class="mail-folders" id="mailFolders">
                <div class="text-center text-muted small py-3">Loading folders...</div>
            </div>
            <div class="mail-list" id="mailList">
                <div class="text-center text-muted small py-3">Loading messages...</div>
            </div>
            <div class="mail-reading-pane" id="mailReadingPane">
                <div class="mail-empty-state">
                    <i class="fas fa-envelope-open-text fa-3x mb-2"></i>
                    <p>Select a message to read it</p>
                </div>
            </div>
        </div>

        <button type="button" class="btn btn-primary rounded-pill shadow position-fixed" id="composeToggleBtn"
                style="bottom: 20px; right: 30px; z-index: 1040; padding: 12px 24px;">
            <i class="fas fa-pen"></i> Compose
        </button>

        <div class="compose-panel" id="composePanel">
            <div class="compose-header" id="composeHeader">
                <span>New Message</span>
                <span><i class="fas fa-times" id="composeCloseBtn"></i></span>
            </div>
            <div class="compose-body">
                <div id="composeAlert"></div>
                <input type="email" class="form-control mb-1" id="composeTo" placeholder="To">
                <input type="text" class="form-control mb-1" id="composeSubject" placeholder="Subject">
                <textarea class="form-control mb-2" id="composeBody" rows="8" placeholder="Message"></textarea>
                <button type="button" class="btn btn-primary btn-sm" id="composeSendBtn">
                    <i class="fas fa-paper-plane"></i> Send
                </button>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (!document.getElementById('mailFolders')) {
        return; // mailbox not configured
    }

    const AJAX_BASE = '/IMS/ajax/admin/';
    const currentAccountId = <?php echo (int)$accountId; ?>;
    let currentFolder = 'INBOX';
    let currentUid = null;

    const avatarColors = ['#1a73e8', '#d93025', '#188038', '#e37400', '#9334e6', '#12a4af', '#c26401'];
    function colorFor(text) {
        let hash = 0;
        for (let i = 0; i < text.length; i++) {
            hash = text.charCodeAt(i) + ((hash << 5) - hash);
        }
        return avatarColors[Math.abs(hash) % avatarColors.length];
    }

    function parseFrom(from) {
        const match = from.match(/^(.*?)<(.+?)>$/);
        if (match) {
            const name = match[1].trim().replace(/^"|"$/g, '');
            return { name: name || match[2], email: match[2] };
        }
        return { name: from, email: from };
    }

    function initials(name) {
        const parts = name.trim().split(/\s+/);
        const chars = parts.length > 1 ? parts[0][0] + parts[1][0] : name.substring(0, 2);
        return chars.toUpperCase();
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    // Reverses the server's htmlspecialchars() via the DOM's entity decoder, then reads
    // textContent (strips any tags), so this only ever yields plain text - safe to use.
    function unescapeHtml(str) {
        const div = document.createElement('div');
        div.innerHTML = str;
        return div.textContent;
    }

    function loadFolders() {
        fetch(AJAX_BASE + 'mailbox_folders.php?account_id=' + currentAccountId)
            .then(function(res) { return res.json(); })
            .then(function(data) {
                const container = document.getElementById('mailFolders');
                if (!data.success) {
                    container.innerHTML = '<div class="alert alert-danger m-2 p-2 small">' + escapeHtml(data.error || 'Failed to load folders') + '</div>';
                    return;
                }
                container.innerHTML = '';
                data.folders.forEach(function(folder) {
                    const el = document.createElement('a');
                    el.className = 'folder-item' + (folder.name === currentFolder ? ' active' : '');
                    el.textContent = folder.display;
                    el.dataset.folder = folder.name;
                    el.addEventListener('click', function() {
                        currentFolder = folder.name;
                        document.querySelectorAll('.folder-item').forEach(function(f) { f.classList.remove('active'); });
                        el.classList.add('active');
                        loadMessages(folder.name);
                        resetReadingPane();
                    });
                    container.appendChild(el);
                });
            })
            .catch(function() {
                document.getElementById('mailFolders').innerHTML = '<div class="alert alert-danger m-2 p-2 small">Failed to load folders.</div>';
            });
    }

    function loadMessages(folder) {
        const list = document.getElementById('mailList');
        list.innerHTML = '<div class="text-center text-muted small py-3">Loading...</div>';

        fetch(AJAX_BASE + 'mailbox_messages.php?account_id=' + currentAccountId + '&folder=' + encodeURIComponent(folder) + '&limit=30')
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (!data.success) {
                    list.innerHTML = '<div class="alert alert-danger m-2 p-2 small">' + escapeHtml(data.error || 'Failed to load messages') + '</div>';
                    return;
                }
                if (!data.messages.length) {
                    list.innerHTML = '<div class="text-center text-muted small py-4">No messages</div>';
                    return;
                }
                list.innerHTML = '';
                data.messages.forEach(function(msg) {
                    const from = parseFrom(msg.from);
                    const row = document.createElement('div');
                    row.className = 'mail-row' + (msg.seen ? '' : ' unread');
                    row.dataset.uid = msg.uid;

                    const avatar = document.createElement('div');
                    avatar.className = 'mail-avatar';
                    avatar.style.background = colorFor(from.email);
                    avatar.textContent = initials(from.name);

                    const body = document.createElement('div');
                    body.className = 'mail-row-body';
                    body.innerHTML =
                        '<div class="mail-row-from">' + escapeHtml(from.name) + '</div>' +
                        '<div class="mail-row-subject">' + escapeHtml(msg.subject) + '</div>';

                    const date = document.createElement('div');
                    date.className = 'mail-row-date';
                    date.textContent = msg.date ? new Date(msg.date).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) : '';

                    const deleteBtn = document.createElement('span');
                    deleteBtn.className = 'mail-row-delete';
                    deleteBtn.title = 'Delete';
                    deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
                    deleteBtn.addEventListener('click', function(e) {
                        e.stopPropagation();
                        deleteMessage(msg.uid, folder, row);
                    });

                    row.appendChild(avatar);
                    row.appendChild(body);
                    row.appendChild(date);
                    row.appendChild(deleteBtn);

                    row.addEventListener('click', function() {
                        document.querySelectorAll('.mail-row').forEach(function(r) { r.classList.remove('active'); });
                        row.classList.add('active');
                        row.classList.remove('unread');
                        viewMessage(msg.uid, folder);
                    });

                    list.appendChild(row);
                });
            })
            .catch(function() {
                list.innerHTML = '<div class="alert alert-danger m-2 p-2 small">Failed to load messages.</div>';
            });
    }

    function deleteMessage(uid, folder, row) {
        if (!confirm('Delete this message?')) return;

        fetch(AJAX_BASE + 'mailbox_delete_message.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ account_id: currentAccountId, uid: uid, folder: folder }).toString(),
        })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (!data.success) {
                    alert(data.error || 'Unable to delete message.');
                    return;
                }
                row.remove();
                if (currentUid == uid) {
                    resetReadingPane();
                }
            })
            .catch(function() {
                alert('Unable to delete message.');
            });
    }

    function resetReadingPane() {
        currentUid = null;
        document.getElementById('mailReadingPane').innerHTML =
            '<div class="mail-empty-state"><i class="fas fa-envelope-open-text fa-3x mb-2"></i><p>Select a message to read it</p></div>';
    }

    function viewMessage(uid, folder) {
        currentUid = uid;
        const pane = document.getElementById('mailReadingPane');
        pane.innerHTML = '<p class="text-muted">Loading...</p>';

        fetch(AJAX_BASE + 'mailbox_view_message.php?account_id=' + currentAccountId + '&uid=' + encodeURIComponent(uid) + '&folder=' + encodeURIComponent(folder))
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (!data.success) {
                    pane.innerHTML = '<div class="alert alert-danger">' + escapeHtml(data.error || 'Failed to load message') + '</div>';
                    return;
                }
                const from = parseFrom(data.message.from);
                pane.innerHTML =
                    '<h5 class="mb-1">' + (data.message.subject || '(no subject)') + '</h5>' +
                    '<p class="text-muted mb-1"><strong>' + data.message.from + '</strong></p>' +
                    '<p class="text-muted mb-3 small">' + data.message.date + '</p>' +
                    '<div class="mb-2"><button type="button" class="btn btn-sm btn-outline-primary" id="replyBtn">' +
                    '<i class="fas fa-reply"></i> Reply</button> ' +
                    '<button type="button" class="btn btn-sm btn-outline-danger" id="deleteBtn">' +
                    '<i class="fas fa-trash-alt"></i> Delete</button></div>' +
                    '<iframe sandbox=""></iframe>';

                // Rendered inside a sandboxed iframe (no allow-scripts/allow-same-origin) so any
                // script/markup in the received email cannot execute or reach the admin session.
                pane.querySelector('iframe').srcdoc = data.message.body_html || '<pre>' + (data.message.body_plain || '') + '</pre>';

                document.getElementById('replyBtn').addEventListener('click', function() {
                    // data.message.* fields are htmlspecialchars-escaped by the server (needed for
                    // safe rendering above); decode back to plain text before using as textarea/input values.
                    const plainSubject = unescapeHtml(data.message.subject || '');
                    const plainFromEmail = unescapeHtml(from.email);
                    const plainDate = unescapeHtml(data.message.date || '');
                    const plainBody = unescapeHtml(data.message.body_plain || '');

                    openCompose({
                        to: plainFromEmail,
                        subject: /^Re:/i.test(plainSubject) ? plainSubject : 'Re: ' + plainSubject,
                        body: '\n\n---- Original message from ' + plainFromEmail + ' on ' + plainDate + ' ----\n' + plainBody
                    });
                });

                document.getElementById('deleteBtn').addEventListener('click', function() {
                    const row = document.querySelector('.mail-row[data-uid="' + uid + '"]');
                    deleteMessage(uid, folder, row || { remove: function() {} });
                });
            })
            .catch(function() {
                pane.innerHTML = '<div class="alert alert-danger">Failed to load message.</div>';
            });
    }

    function openCompose(prefill) {
        prefill = prefill || {};
        document.getElementById('composeTo').value = prefill.to || '';
        document.getElementById('composeSubject').value = prefill.subject || '';
        document.getElementById('composeBody').value = prefill.body || '';
        document.getElementById('composeAlert').innerHTML = '';
        document.getElementById('composePanel').classList.add('open');
    }

    document.getElementById('composeToggleBtn').addEventListener('click', function() { openCompose(); });
    document.getElementById('composeCloseBtn').addEventListener('click', function(e) {
        e.stopPropagation();
        document.getElementById('composePanel').classList.remove('open');
    });
    document.getElementById('composeHeader').addEventListener('click', function() {
        document.getElementById('composePanel').classList.toggle('open');
    });

    document.getElementById('composeSendBtn').addEventListener('click', function() {
        const btn = this;
        const alertBox = document.getElementById('composeAlert');
        const payload = new URLSearchParams({
            account_id: currentAccountId,
            to: document.getElementById('composeTo').value,
            subject: document.getElementById('composeSubject').value,
            body: document.getElementById('composeBody').value,
        });

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';

        fetch(AJAX_BASE + 'mailbox_send.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload.toString(),
        })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-paper-plane"></i> Send';
                if (!data.success) {
                    alertBox.innerHTML = '<div class="alert alert-danger py-1 px-2 small">' + escapeHtml(data.error || 'Failed to send') + '</div>';
                    return;
                }
                document.getElementById('composePanel').classList.remove('open');
                if (currentFolder.toLowerCase().indexOf('sent') !== -1) {
                    loadMessages(currentFolder);
                }
            })
            .catch(function() {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-paper-plane"></i> Send';
                alertBox.innerHTML = '<div class="alert alert-danger py-1 px-2 small">Failed to send.</div>';
            });
    });

    loadFolders();
    loadMessages(currentFolder);
});
</script>

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