<?php
// Variables available: $admins, $unreadTotal, $announcements, $upcomingMeetings, $deletionAudit
// Session: $_SESSION['admin_id'], $_SESSION['admin_role']
$currentAdminId = (int)$_SESSION['admin_id'];
$isManager = in_array($_SESSION['admin_role'] ?? '', ['owner','manager'], true);
$csrfToken = \Core\System\Csrf::token();

include __DIR__ . '/../header.php';
?>
<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold"><i class="bi bi-chat-dots-fill me-2 text-primary"></i><?= __('sidebar.team_communication','Communication') ?></h3>
        <p class="text-muted mb-0 small"><?= __('team_comm.page_subtitle','Send direct messages and view team announcements') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="/admin/team" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-people me-1"></i><?= __('sidebar.team_members','Team Members') ?>
        </a>
        <a href="/admin/team/meetings" class="btn btn-outline-info btn-sm">
            <i class="bi bi-calendar-event me-1"></i><?= __('sidebar.team_meetings','Meetings') ?>
        </a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100" style="background:linear-gradient(135deg,#0d6efd,#3b82f6);color:#fff">
            <div class="card-body">
                <div class="small opacity-75 mb-2"><?= __('team_comm.inbox_overview','Inbox overview') ?></div>
                <div class="d-flex align-items-end justify-content-between">
                    <div>
                        <div class="display-6 fw-bold mb-0"><?= (int)$unreadTotal ?></div>
                        <div class="small"><?= __('team_comm.unread_messages','Unread messages') ?></div>
                    </div>
                    <i class="bi bi-chat-left-text-fill fs-1 opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="small text-muted mb-2"><?= __('team_comm.active_conversations','Active conversations') ?></div>
                <div class="d-flex align-items-end justify-content-between">
                    <div>
                        <div class="display-6 fw-bold mb-0"><?= count($admins ?? []) ?></div>
                        <div class="small text-muted"><?= __('team_comm.team_members_available','Team members available for direct chat') ?></div>
                    </div>
                    <i class="bi bi-people-fill fs-1 text-primary opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="small text-muted mb-2"><?= __('team_comm.team_schedule','Team schedule') ?></div>
                <div class="d-flex align-items-end justify-content-between">
                    <div>
                        <div class="display-6 fw-bold mb-0"><?= count($upcomingMeetings ?? []) ?></div>
                        <div class="small text-muted"><?= __('team_comm.upcoming_sessions','Upcoming meetings and sessions') ?></div>
                    </div>
                    <i class="bi bi-calendar2-week-fill fs-1 text-info opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">

        <!-- LEFT: Conversations list -->
        <div class="col-lg-4">
            <!-- Search -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header bg-primary text-white d-flex align-items-center justify-content-between py-2">
                    <span class="fw-semibold"><i class="bi bi-chat-dots-fill me-2"></i><?= __('team_comm.direct_messages','Direct Messages') ?></span>
                    <?php if ($unreadTotal > 0): ?>
                    <span class="badge bg-danger"><?= min(99, $unreadTotal) ?></span>
                    <?php endif; ?>
                </div>
                <div class="card-body p-2">
                    <input type="text" class="form-control form-control-sm" id="searchMembers"
                           placeholder="<?= htmlspecialchars(__('team_comm.search_members','Search members...'), ENT_QUOTES) ?>">
                </div>
            </div>

            <div class="list-group shadow-sm" id="membersList">
                <?php foreach ($admins as $admin): ?>
                <?php
                    $isOnline = !empty($admin['last_seen_at']) && (strtotime($admin['last_seen_at']) >= time() - 300);
                    $unread   = (int)($admin['unread_count'] ?? 0);
                    $lastMsgAt = !empty($admin['last_message_at']) ? app_format_datetime($admin['last_message_at']) : __('team_comm.no_messages_yet','No messages yet');
                ?>
                <a href="/admin/team/communication/<?= $admin['id'] ?>"
                   class="list-group-item list-group-item-action d-flex align-items-center gap-2 py-2 member-item"
                   data-name="<?= htmlspecialchars(strtolower($admin['username']), ENT_QUOTES) ?>">
                    <div class="position-relative flex-shrink-0">
                        <img src="<?= htmlspecialchars(!empty($admin['avatar']) ? $admin['avatar'] : '/admin/assets/adminlte-assets/img/avatar.png', ENT_QUOTES) ?>"
                             class="rounded-circle" width="40" height="40" style="object-fit:cover" alt="">
                        <span class="position-absolute bottom-0 end-0 rounded-circle border border-white"
                              style="width:10px;height:10px;background:<?= $isOnline ? '#28a745' : '#adb5bd' ?>"></span>
                    </div>
                    <div class="flex-grow-1 min-width-0">
                        <div class="fw-semibold text-truncate small"><?= htmlspecialchars($admin['username']) ?></div>
                        <div class="text-muted" style="font-size:0.72rem"><?= __('team.role_'.$admin['role'], $admin['role']) ?></div>
                        <div class="text-muted text-truncate" style="font-size:0.68rem"><?= htmlspecialchars($lastMsgAt) ?></div>
                    </div>
                    <?php if ($unread > 0): ?>
                    <span class="badge bg-danger rounded-pill"><?= $unread ?></span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
                <?php if (empty($admins)): ?>
                <div class="list-group-item text-muted text-center small py-3">
                    <?= __('team_comm.no_members','No other team members') ?>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- RIGHT: Announcements + Upcoming Meetings -->
        <div class="col-lg-8">

            <!-- Announcements -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header bg-white border-bottom d-flex align-items-center justify-content-between py-2">
                    <span class="fw-semibold"><i class="bi bi-megaphone-fill me-2 text-warning"></i><?= __('team_comm.announcements','Announcements') ?></span>
                    <?php if ($isManager): ?>
                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#newAnnouncementModal">
                        <i class="bi bi-plus-lg me-1"></i><?= __('team_comm.new_announcement','New Announcement') ?>
                    </button>
                    <?php endif; ?>
                </div>
                <div class="card-body p-0" id="announcementsList">
                    <?php if (empty($announcements)): ?>
                    <div class="text-center text-muted py-4 small">
                        <i class="bi bi-megaphone fs-3 d-block mb-2 opacity-50"></i>
                        <?= __('team_comm.no_announcements','No announcements yet') ?>
                    </div>
                    <?php else: ?>
                    <?php foreach ($announcements as $ann): ?>
                    <div class="d-flex gap-2 p-3 border-bottom announcement-item" data-id="<?= $ann['id'] ?>">
                        <?php if ($ann['is_pinned']): ?>
                        <i class="bi bi-pin-angle-fill text-warning flex-shrink-0 mt-1"></i>
                        <?php else: ?>
                        <i class="bi bi-bell text-muted flex-shrink-0 mt-1"></i>
                        <?php endif; ?>
                        <div class="flex-grow-1">
                            <div class="fw-semibold small"><?= htmlspecialchars($ann['title']) ?></div>
                            <div class="text-muted small mt-1"><?= nl2br(htmlspecialchars($ann['content'])) ?></div>
                            <div class="text-muted mt-1" style="font-size:0.7rem">
                                <?= htmlspecialchars($ann['author_name'] ?? '') ?> &bull;
                                <?= app_format_datetime($ann['created_at']) ?>
                            </div>
                        </div>
                        <?php if ($isManager): ?>
                        <div class="flex-shrink-0 d-flex gap-1">
                            <button class="btn btn-sm btn-light btn-pin-ann" data-id="<?= $ann['id'] ?>" title="<?= __('team_comm.pin','Pin/Unpin') ?>">
                                <i class="bi bi-pin<?= $ann['is_pinned'] ? '-angle-fill' : '' ?>"></i>
                            </button>
                            <button class="btn btn-sm btn-light text-danger btn-del-ann" data-id="<?= $ann['id'] ?>" title="<?= __('team_comm.delete','Delete') ?>">
                                <i class="bi bi-trash3"></i>
                            </button>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Upcoming Meetings Widget -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom d-flex align-items-center justify-content-between py-2">
                    <span class="fw-semibold"><i class="bi bi-calendar-event-fill me-2 text-info"></i><?= __('team_comm.upcoming_meetings','Upcoming Meetings') ?></span>
                    <a href="/admin/team/meetings" class="btn btn-sm btn-outline-info"><?= __('team_comm.view_all','View All') ?></a>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($upcomingMeetings)): ?>
                    <div class="text-center text-muted py-4 small">
                        <i class="bi bi-calendar-x fs-3 d-block mb-2 opacity-50"></i>
                        <?= __('team_comm.no_upcoming_meetings','No upcoming meetings') ?>
                    </div>
                    <?php else: ?>
                    <?php foreach ($upcomingMeetings as $m): ?>
                    <div class="d-flex align-items-center gap-3 p-3 border-bottom">
                        <div class="text-center flex-shrink-0" style="width:42px">
                            <div class="fw-bold text-primary" style="font-size:1.1rem"><?= app_format_datetime($m['scheduled_at'], 'd') ?></div>
                            <div class="text-muted" style="font-size:0.65rem;text-transform:uppercase"><?= app_format_datetime($m['scheduled_at'], 'M') ?></div>
                        </div>
                        <div class="flex-grow-1">
                            <div class="fw-semibold small"><?= htmlspecialchars($m['title']) ?></div>
                            <div class="text-muted" style="font-size:0.72rem">
                                <i class="bi bi-clock me-1"></i><?= app_format_datetime($m['scheduled_at'], 'H:i') ?>
                                &bull; <?= (int)$m['duration_minutes'] ?> <?= __('team_comm.minutes','min') ?>
                                <?php if ($m['accepted_count'] > 0): ?>
                                &bull; <i class="bi bi-people me-1"></i><?= (int)$m['accepted_count'] ?> <?= __('team_comm.accepted','accepted') ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <span class="badge bg-<?= ['standup'=>'info','review'=>'primary','training'=>'success','planning'=>'warning'][$m['meeting_type']] ?? 'secondary' ?> rounded-pill">
                            <?= __('team_meeting.type_'.$m['meeting_type'], $m['meeting_type']) ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($isManager): ?>
            <div class="card border-0 shadow-sm mt-3">
                <div class="card-header bg-white border-bottom d-flex align-items-center justify-content-between py-2">
                    <span class="fw-semibold"><i class="bi bi-shield-lock-fill me-2 text-danger"></i><?= __('team_comm.deleted_messages_audit','Deleted messages audit') ?></span>
                    <span class="badge bg-danger-subtle text-danger border border-danger-subtle"><?= count($deletionAudit ?? []) ?></span>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($deletionAudit)): ?>
                    <div class="text-center text-muted py-4 small">
                        <i class="bi bi-trash3 fs-3 d-block mb-2 opacity-50"></i>
                        <?= __('team_comm.no_deleted_messages','No deleted messages recorded') ?>
                    </div>
                    <?php else: ?>
                    <?php foreach ($deletionAudit as $item): ?>
                    <?php
                        $snapshot = json_decode((string)($item['deleted_snapshot'] ?? ''), true) ?: [];
                        $original = trim((string)($snapshot['content'] ?? $item['content'] ?? ''));
                        $attachmentName = (string)($snapshot['attachment_name'] ?? $item['attachment_name'] ?? '');
                    ?>
                    <div class="p-3 border-bottom">
                        <div class="d-flex justify-content-between align-items-start gap-3">
                            <div>
                                <div class="fw-semibold small">
                                    <?= htmlspecialchars((string)($item['sender_name'] ?? '')) ?>
                                    <i class="bi bi-arrow-left-right mx-1 text-muted"></i>
                                    <?= htmlspecialchars((string)($item['receiver_name'] ?? '')) ?>
                                </div>
                                <div class="text-muted" style="font-size:.72rem">
                                    <?= __('team_comm.deleted_by','Deleted by') ?>:
                                    <?= htmlspecialchars((string)($item['deleted_by_name'] ?? '')) ?>
                                    &bull; <?= app_format_datetime((string)($item['deleted_at'] ?? '')) ?>
                                </div>
                            </div>
                            <span class="badge bg-danger-subtle text-danger border border-danger-subtle"><?= __('team_comm.deleted','Deleted') ?></span>
                        </div>
                        <?php if ($original !== ''): ?>
                        <div class="mt-2 small rounded p-2" style="background:#fff5f5;border:1px dashed #f1aeb5"><?= nl2br(htmlspecialchars($original)) ?></div>
                        <?php endif; ?>
                        <?php if ($attachmentName !== ''): ?>
                        <div class="mt-2 text-muted" style="font-size:.72rem">
                            <i class="bi bi-paperclip me-1"></i><?= htmlspecialchars($attachmentName) ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

        </div>
    </div>

</div>
</section>
</div>

<?php if ($isManager): ?>
<!-- New Announcement Modal -->
<div class="modal fade" id="newAnnouncementModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?= __('team_comm.new_announcement','New Announcement') ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label small fw-semibold"><?= __('team_comm.announcement_title','Title') ?> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control form-control-sm" id="annTitle" maxlength="255">
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-semibold"><?= __('team_comm.announcement_content','Content') ?> <span class="text-danger">*</span></label>
                    <textarea class="form-control form-control-sm" id="annContent" rows="4"></textarea>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="annPinned">
                    <label class="form-check-label small" for="annPinned"><?= __('team_comm.pin_announcement','Pin this announcement') ?></label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal"><?= __('team_comm.cancel','Cancel') ?></button>
                <button type="button" class="btn btn-primary btn-sm" id="submitAnnouncement">
                    <i class="bi bi-send me-1"></i><?= __('team_comm.post','Post') ?>
                </button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
const CSRF = <?= json_encode($csrfToken) ?>;
const IS_MANAGER = <?= $isManager ? 'true' : 'false' ?>;

// Member search filter
document.getElementById('searchMembers').addEventListener('input', function () {
    const q = this.value.toLowerCase();
    document.querySelectorAll('.member-item').forEach(el => {
        el.style.display = el.dataset.name.includes(q) ? '' : 'none';
    });
});

// Announcement – post
<?php if ($isManager): ?>
document.getElementById('submitAnnouncement').addEventListener('click', function () {
    const title   = document.getElementById('annTitle').value.trim();
    const content = document.getElementById('annContent').value.trim();
    const pinned  = document.getElementById('annPinned').checked ? '1' : '0';
    if (!title || !content) return;
    const btn = this;
    btn.disabled = true;
    fetch('/admin/team/announcements/store', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `_csrf=${encodeURIComponent(CSRF)}&title=${encodeURIComponent(title)}&content=${encodeURIComponent(content)}&is_pinned=${pinned}`
    })
    .then(r => r.json())
    .then(d => {
        if (d.success) location.reload();
    })
    .finally(() => { btn.disabled = false; });
});

// Pin/Unpin announcement
document.querySelectorAll('.btn-pin-ann').forEach(btn => {
    btn.addEventListener('click', function () {
        const id = this.dataset.id;
        fetch(`/admin/team/announcements/pin/${id}`, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `_csrf=${encodeURIComponent(CSRF)}`
        }).then(() => location.reload());
    });
});

// Delete announcement
document.querySelectorAll('.btn-del-ann').forEach(btn => {
    btn.addEventListener('click', function () {
        if (!confirm('<?= addslashes(__('team_comm.confirm_delete','Confirm delete?')) ?>')) return;
        const id = this.dataset.id;
        fetch(`/admin/team/announcements/delete/${id}`, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `_csrf=${encodeURIComponent(CSRF)}`
        }).then(() => {
            const item = document.querySelector(`.announcement-item[data-id="${id}"]`);
            if (item) item.remove();
        });
    });
});
<?php endif; ?>
</script>

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