<?php
/**
 * AP One 사내 메신저
 * - 1:1 개인 채팅, 팀 채팅 (team_master 연동), 경영진 그룹
 */
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
requireLogin();
require_once __DIR__ . '/../includes/header.php';

$db = (new Database())->getConnection();
$user = currentUser();
$userId   = $user['user_id'];
$userRole = $user['role'];
$userName = $user['name'];
$myTeam   = $user['team'] ?? '';
$isExec   = in_array($userRole, ['sysadmin','ceo','manager']);

// DB 테이블 자동 생성
$db->exec("CREATE TABLE IF NOT EXISTS messenger_messages (
    msg_id BIGINT AUTO_INCREMENT PRIMARY KEY,
    channel_type ENUM('dm','team','exec') NOT NULL,
    channel_id INT NOT NULL DEFAULT 0,
    sender_id INT NOT NULL,
    message TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_channel (channel_type, channel_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

$db->exec("CREATE TABLE IF NOT EXISTS messenger_dm_pairs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user1_id INT NOT NULL,
    user2_id INT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_pair (user1_id, user2_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

$db->exec("CREATE TABLE IF NOT EXISTS messenger_read_status (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    channel_type ENUM('dm','team','exec') NOT NULL,
    channel_id INT NOT NULL,
    last_read_id BIGINT DEFAULT 0,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_user_channel (user_id, channel_type, channel_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

// 사용자 목록 (본인 제외)
$userList = $db->prepare("SELECT ua.user_id, ua.staff_id, s.name, s.team, s.grade, ua.user_role AS role 
    FROM user_account ua JOIN staff s ON ua.staff_id=s.staff_id 
    WHERE ua.is_active=1 AND ua.user_id!=? ORDER BY s.name");
$userList->execute([$userId]);
$userList = $userList->fetchAll();

// 팀 목록
$teams = $db->query("SELECT team_name FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);

function msgRoleLabel($r) {
    $m = ['sysadmin'=>'시스템관리자','ceo'=>'대표','manager'=>'관리자','team_leader'=>'팀장','staff'=>'직원'];
    return $m[$r] ?? $r;
}
?>
<style>
.msg-wrap{display:flex;height:calc(100vh - 70px);background:var(--bg-primary);border-radius:8px;overflow:hidden;border:1px solid rgba(255,255,255,0.06);}
.msg-sidebar{width:280px;min-width:280px;border-right:1px solid rgba(255,255,255,0.06);display:flex;flex-direction:column;background:rgba(0,0,0,0.15);}
.msg-side-head{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;gap:8px;}
.msg-side-head h3{margin:0;font-size:1rem;flex:1;}
.msg-btn-new{background:var(--accent);color:#fff;border:none;border-radius:50%;width:28px;height:28px;font-size:1rem;cursor:pointer;display:flex;align-items:center;justify-content:center;}
.msg-search{width:100%;padding:6px 10px;border-radius:6px;border:1px solid rgba(255,255,255,0.1);background:rgba(255,255,255,0.04);color:var(--text-primary);font-size:var(--fs-xs);outline:none;box-sizing:border-box;}
.msg-tabs{display:flex;border-bottom:1px solid rgba(255,255,255,0.06);padding:0 8px;}
.msg-tab{padding:8px 10px;font-size:0.75rem;cursor:pointer;color:var(--text-tertiary);border-bottom:2px solid transparent;transition:0.2s;}
.msg-tab.active{color:var(--accent);border-bottom-color:var(--accent);}
.msg-channels{flex:1;overflow-y:auto;padding:4px 0;}
.msg-ch{display:flex;align-items:center;gap:10px;padding:10px 14px;cursor:pointer;transition:0.15s;}
.msg-ch:hover,.msg-ch.active{background:rgba(255,255,255,0.05);}
.msg-ch-avatar{width:36px;height:36px;border-radius:50%;background:var(--accent);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:0.85rem;color:#fff;flex-shrink:0;}
.msg-ch-info{flex:1;min-width:0;}
.msg-ch-name{font-size:0.82rem;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.msg-ch-last{font-size:0.7rem;color:var(--text-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.msg-ch-meta{text-align:right;flex-shrink:0;}
.msg-ch-time{font-size:0.65rem;color:var(--text-tertiary);}
.msg-badge{background:var(--accent);color:#fff;font-size:0.6rem;padding:1px 5px;border-radius:8px;margin-top:2px;display:inline-block;}
.msg-main{flex:1;display:flex;flex-direction:column;}
.msg-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;color:var(--text-tertiary);}
.msg-empty-icon{font-size:3rem;margin-bottom:8px;}
.msg-header{padding:12px 20px;border-bottom:1px solid rgba(255,255,255,0.06);font-weight:600;font-size:0.95rem;}
.msg-body{flex:1;overflow-y:auto;padding:16px 20px;display:flex;flex-direction:column;gap:4px;}
.msg-date-sep{text-align:center;color:var(--text-tertiary);font-size:0.7rem;margin:8px 0;position:relative;}
.msg-date-sep span{background:var(--bg-primary);padding:0 10px;position:relative;z-index:1;}
.msg-date-sep::before{content:'';position:absolute;left:0;right:0;top:50%;border-top:1px solid rgba(255,255,255,0.06);}
.msg-bubble-wrap{display:flex;gap:8px;max-width:70%;}
.msg-bubble-wrap.me{margin-left:auto;flex-direction:row-reverse;}
.msg-bubble{padding:8px 12px;border-radius:12px;font-size:0.82rem;line-height:1.5;word-break:break-word;}
.msg-bubble-wrap:not(.me) .msg-bubble{background:rgba(255,255,255,0.08);border-top-left-radius:2px;}
.msg-bubble-wrap.me .msg-bubble{background:var(--accent);color:#fff;border-top-right-radius:2px;}
.msg-sender{font-size:0.7rem;font-weight:600;color:var(--text-secondary);margin-bottom:2px;}
.msg-time{font-size:0.6rem;color:var(--text-tertiary);align-self:flex-end;flex-shrink:0;}
.msg-input-wrap{padding:12px 16px;border-top:1px solid rgba(255,255,255,0.06);display:flex;gap:8px;}
.msg-input{flex:1;padding:8px 12px;border-radius:20px;border:1px solid rgba(255,255,255,0.1);background:rgba(255,255,255,0.04);color:var(--text-primary);font-size:0.85rem;outline:none;}
.msg-send{background:var(--accent);color:#fff;border:none;border-radius:50%;width:36px;height:36px;font-size:1.1rem;cursor:pointer;display:flex;align-items:center;justify-content:center;}
.msg-modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:9999;display:flex;align-items:center;justify-content:center;}
.msg-modal{background:var(--bg-card);border-radius:12px;width:360px;max-height:70vh;display:flex;flex-direction:column;border:1px solid rgba(255,255,255,0.1);}
.msg-modal-header{display:flex;align-items:center;justify-content:space-between;padding:14px 20px;border-bottom:1px solid rgba(255,255,255,0.06);}
.msg-modal-header h4{margin:0;font-size:0.95rem;}
.msg-modal-close{background:none;border:none;color:var(--text-tertiary);font-size:1.3rem;cursor:pointer;}
.msg-modal-body{overflow-y:auto;padding:8px 0;flex:1;}
.msg-modal-user{display:flex;align-items:center;gap:10px;padding:8px 20px;cursor:pointer;transition:0.15s;}
.msg-modal-user:hover{background:rgba(255,255,255,0.05);}
.msg-modal-user-avatar{width:32px;height:32px;border-radius:50%;background:var(--accent);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:0.8rem;color:#fff;}
.msg-modal-user-name{font-size:0.82rem;font-weight:600;}
.msg-modal-user-detail{font-size:0.7rem;color:var(--text-tertiary);}
</style>

<div class="msg-wrap">
    <div class="msg-sidebar">
        <div class="msg-side-head">
            <h3>💬 메신저</h3>
            <button class="msg-btn-new" onclick="openNewChat()" title="새 대화">+</button>
        </div>
        <div style="padding:8px 12px;">
            <input type="text" class="msg-search" placeholder="대화 검색..." id="msgSearch" oninput="filterChannels()">
        </div>
        <div class="msg-tabs">
            <div class="msg-tab active" data-tab="all" onclick="switchTab('all')">전체</div>
            <div class="msg-tab" data-tab="dm" onclick="switchTab('dm')">1:1</div>
            <div class="msg-tab" data-tab="team" onclick="switchTab('team')">팀</div>
            <?php if($isExec): ?>
            <div class="msg-tab" data-tab="exec" onclick="switchTab('exec')">경영진</div>
            <?php endif; ?>
        </div>
        <div class="msg-channels" id="channelList"></div>
    </div>
    <div class="msg-main" id="msgMain">
        <div class="msg-empty" id="msgEmpty">
            <div class="msg-empty-icon">💬</div>
            <div class="msg-empty-text">대화를 선택하세요</div>
        </div>
    </div>
</div>

<div class="msg-modal-overlay" id="newChatModal" style="display:none;" onclick="if(event.target===this)closeNewChat()">
    <div class="msg-modal">
        <div class="msg-modal-header"><h4>새 대화</h4><button class="msg-modal-close" onclick="closeNewChat()">&times;</button></div>
        <div style="padding:12px 20px 0;"><input type="text" class="msg-search" placeholder="이름 검색..." id="modalSearch" oninput="filterModalUsers()"></div>
        <div class="msg-modal-body" id="modalUserList">
            <?php foreach($userList as $u): ?>
            <div class="msg-modal-user" data-name="<?=htmlspecialchars($u['name'])?>" onclick="startDM(<?=$u['user_id']?>,'<?=htmlspecialchars($u['name'],ENT_QUOTES)?>')">
                <div class="msg-modal-user-avatar"><?=mb_substr($u['name'],0,1)?></div>
                <div><div class="msg-modal-user-name"><?=htmlspecialchars($u['name'])?></div>
                <div class="msg-modal-user-detail"><?=htmlspecialchars($u['team']?:'-')?> · <?=msgRoleLabel($u['role'])?><?=$u['grade']?' · '.$u['grade']:''?></div></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
const ME={id:<?=$userId?>,name:'<?=htmlspecialchars($userName,ENT_QUOTES)?>',role:'<?=$userRole?>',team:'<?=htmlspecialchars($myTeam,ENT_QUOTES)?>'};
const IS_EXEC=<?=$isExec?'true':'false'?>;
const API='<?=BASE_URL?>pages/messenger_api.php';
let curTab='all', curChannel=null, pollTimer=null, lastMsgId=0;

function switchTab(t){curTab=t;document.querySelectorAll('.msg-tab').forEach(e=>e.classList.toggle('active',e.dataset.tab===t));loadChannels();}
function openNewChat(){document.getElementById('newChatModal').style.display='flex';}
function closeNewChat(){document.getElementById('newChatModal').style.display='none';}
function filterChannels(){let q=document.getElementById('msgSearch').value.toLowerCase();document.querySelectorAll('.msg-ch').forEach(e=>e.style.display=e.dataset.name.toLowerCase().includes(q)?'':'none');}
function filterModalUsers(){let q=document.getElementById('modalSearch').value.toLowerCase();document.querySelectorAll('.msg-modal-user').forEach(e=>e.style.display=e.dataset.name.toLowerCase().includes(q)?'':'none');}

async function api(params){
    let fd=new FormData();for(let k in params)fd.append(k,params[k]);
    let r=await fetch(API,{method:'POST',body:fd});return r.json();
}

async function loadChannels(){
    let d=await api({action:'channels',tab:curTab});
    let el=document.getElementById('channelList');
    if(!d.channels||!d.channels.length){el.innerHTML='<div style="padding:20px;text-align:center;color:var(--text-tertiary);font-size:var(--fs-xs);">대화가 없습니다</div>';return;}
    el.innerHTML=d.channels.map(c=>{
        let active=curChannel&&curChannel.type===c.type&&curChannel.id===c.id?' active':'';
        let badge=c.unread>0?'<div><span class="msg-badge">'+c.unread+'</span></div>':'';
        let icon=c.type==='dm'?'👤':c.type==='team'?'👥':'👔';
        return '<div class="msg-ch'+active+'" data-name="'+c.name+'" onclick="openChannel(\''+c.type+'\','+c.id+',\''+c.name.replace(/'/g,"\\'")+'\')"><div class="msg-ch-avatar">'+icon+'</div><div class="msg-ch-info"><div class="msg-ch-name">'+c.name+'</div><div class="msg-ch-last">'+(c.last_msg||'')+'</div></div><div class="msg-ch-meta"><div class="msg-ch-time">'+(c.last_time||'')+'</div>'+badge+'</div></div>';
    }).join('');
    filterChannels();
}

async function openChannel(type,id,name){
    curChannel={type,id,name};lastMsgId=0;
    if(pollTimer)clearInterval(pollTimer);
    document.querySelectorAll('.msg-ch').forEach(e=>e.classList.remove('active'));
    document.querySelectorAll('.msg-ch').forEach(e=>{if(e.onclick&&e.onclick.toString().includes("'"+type+"',"+id))e.classList.add('active');});
    document.getElementById('msgMain').innerHTML='<div class="msg-header">'+name+'</div><div class="msg-body" id="msgBody"></div><div class="msg-input-wrap"><input class="msg-input" id="msgInput" placeholder="메시지 입력..." onkeydown="if(event.key===\'Enter\')sendMsg()"><button class="msg-send" onclick="sendMsg()">➤</button></div>';
    await loadMessages();
    pollTimer=setInterval(loadMessages,3000);
    await api({action:'mark_read',channel_type:type,channel_id:id});
    loadChannels();
}

async function loadMessages(){
    if(!curChannel)return;
    let d=await api({action:'messages',channel_type:curChannel.type,channel_id:curChannel.id,after:lastMsgId});
    if(!d.messages||!d.messages.length)return;
    let body=document.getElementById('msgBody');if(!body)return;
    let prevDate='';
    d.messages.forEach(m=>{
        let dt=m.created_at.substring(0,10);
        if(dt!==prevDate){
            // 기존 날짜 구분선이 있는지 확인
            if(!body.querySelector('[data-date="'+dt+'"]')){
                let sep=document.createElement('div');sep.className='msg-date-sep';sep.dataset.date=dt;sep.innerHTML='<span>'+dt+'</span>';body.appendChild(sep);
            }
            prevDate=dt;
        }
        let isMe=m.sender_id==ME.id;
        let w=document.createElement('div');w.className='msg-bubble-wrap'+(isMe?' me':'');
        let time=m.created_at.substring(11,16);
        w.innerHTML=(isMe?'':'<div><div class="msg-sender">'+m.sender_name+'</div>')+'<div class="msg-bubble">'+escHtml(m.message)+'</div>'+(isMe?'':'</div>')+'<div class="msg-time">'+time+'</div>';
        body.appendChild(w);
        lastMsgId=Math.max(lastMsgId,m.msg_id);
    });
    body.scrollTop=body.scrollHeight;
    if(d.messages.length>0)await api({action:'mark_read',channel_type:curChannel.type,channel_id:curChannel.id});
}

async function sendMsg(){
    let inp=document.getElementById('msgInput');if(!inp)return;
    let msg=inp.value.trim();if(!msg)return;
    inp.value='';
    await api({action:'send',channel_type:curChannel.type,channel_id:curChannel.id,message:msg});
    await loadMessages();
    loadChannels();
}

async function startDM(uid,name){
    closeNewChat();
    let d=await api({action:'start_dm',target_user_id:uid});
    if(d.dm_id)openChannel('dm',d.dm_id,name);
}

function escHtml(t){let d=document.createElement('div');d.textContent=t;return d.innerHTML;}

loadChannels();
setInterval(()=>{if(!curChannel)loadChannels();},5000);
</script>
