<?php
/**
 * AP One 메신저 API
 */
session_start();
if (!isset($_SESSION['user_id'])) { echo json_encode(['error'=>'auth']); exit; }

require_once __DIR__ . '/../config/database.php';
$db = (new Database())->getConnection();
$userId = $_SESSION['user_id'];
$userRole = $_SESSION['user_role'] ?? 'staff';
$staffId = $_SESSION['staff_id'] ?? 0;
$isExec = in_array($userRole, ['sysadmin','ceo','manager']);

// 사용자 팀 조회
$myTeam = '';
try { $t = $db->prepare("SELECT team FROM staff WHERE staff_id=?"); $t->execute([$staffId]); $myTeam = $t->fetchColumn() ?: ''; } catch(Exception $e) {}

$action = $_POST['action'] ?? '';
header('Content-Type: application/json; charset=utf-8');

// ── 채널 목록 ──
if ($action === 'channels') {
    $tab = $_POST['tab'] ?? 'all';
    $channels = [];

    // DM 채널
    if ($tab === 'all' || $tab === 'dm') {
        $dms = $db->prepare("SELECT dp.id, dp.user1_id, dp.user2_id,
            (SELECT message FROM messenger_messages WHERE channel_type='dm' AND channel_id=dp.id ORDER BY msg_id DESC LIMIT 1) AS last_msg,
            (SELECT created_at FROM messenger_messages WHERE channel_type='dm' AND channel_id=dp.id ORDER BY msg_id DESC LIMIT 1) AS last_time,
            (SELECT MAX(msg_id) FROM messenger_messages WHERE channel_type='dm' AND channel_id=dp.id) AS max_msg,
            COALESCE((SELECT last_read_id FROM messenger_read_status WHERE user_id=? AND channel_type='dm' AND channel_id=dp.id),0) AS my_read
        FROM messenger_dm_pairs dp WHERE dp.user1_id=? OR dp.user2_id=? ORDER BY last_time DESC");
        $dms->execute([$userId, $userId, $userId]);
        foreach ($dms->fetchAll() as $dm) {
            $otherId = $dm['user1_id'] == $userId ? $dm['user2_id'] : $dm['user1_id'];
            $otherName = '';
            try { $n = $db->prepare("SELECT s.name FROM user_account ua JOIN staff s ON ua.staff_id=s.staff_id WHERE ua.user_id=?"); $n->execute([$otherId]); $otherName = $n->fetchColumn() ?: '사용자'; } catch(Exception $e) { $otherName = '사용자'; }
            $unread = max(0, ($dm['max_msg'] ?? 0) - ($dm['my_read'] ?? 0));
            $channels[] = ['type'=>'dm','id'=>(int)$dm['id'],'name'=>$otherName,'last_msg'=>mb_substr($dm['last_msg']??'',0,30),'last_time'=>$dm['last_time']?date('H:i',strtotime($dm['last_time'])):'','unread'=>$unread];
        }
    }

    // 팀 채널
    if ($tab === 'all' || $tab === 'team') {
        $teams = $db->query("SELECT team_id, team_name FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll();
        foreach ($teams as $tm) {
            // 본인 팀이 아니면 스킵 (관리자/대표/시스템관리자는 전체 볼 수 있음)
            if (!$isExec && $myTeam !== $tm['team_name']) continue;
            $tid = $tm['team_id'];
            $last = $db->prepare("SELECT message, created_at FROM messenger_messages WHERE channel_type='team' AND channel_id=? ORDER BY msg_id DESC LIMIT 1");
            $last->execute([$tid]); $lr = $last->fetch();
            $maxId = $db->prepare("SELECT MAX(msg_id) FROM messenger_messages WHERE channel_type='team' AND channel_id=?"); $maxId->execute([$tid]); $mx = (int)$maxId->fetchColumn();
            $readId = $db->prepare("SELECT last_read_id FROM messenger_read_status WHERE user_id=? AND channel_type='team' AND channel_id=?"); $readId->execute([$userId,$tid]); $rd = (int)$readId->fetchColumn();
            $channels[] = ['type'=>'team','id'=>$tid,'name'=>'🏢 '.$tm['team_name'],'last_msg'=>mb_substr($lr['message']??'',0,30),'last_time'=>$lr?date('H:i',strtotime($lr['created_at'])):'','unread'=>max(0,$mx-$rd)];
        }
    }

    // 경영진 채널
    if ($isExec && ($tab === 'all' || $tab === 'exec')) {
        $last = $db->prepare("SELECT message, created_at FROM messenger_messages WHERE channel_type='exec' AND channel_id=0 ORDER BY msg_id DESC LIMIT 1");
        $last->execute(); $lr = $last->fetch();
        $maxId = (int)$db->query("SELECT COALESCE(MAX(msg_id),0) FROM messenger_messages WHERE channel_type='exec' AND channel_id=0")->fetchColumn();
        $readId = $db->prepare("SELECT last_read_id FROM messenger_read_status WHERE user_id=? AND channel_type='exec' AND channel_id=0"); $readId->execute([$userId]); $rd = (int)$readId->fetchColumn();
        $channels[] = ['type'=>'exec','id'=>0,'name'=>'👔 경영진','last_msg'=>mb_substr($lr['message']??'',0,30),'last_time'=>$lr?date('H:i',strtotime($lr['created_at'])):'','unread'=>max(0,$maxId-$rd)];
    }

    echo json_encode(['channels'=>$channels]); exit;
}

// ── 메시지 로드 ──
if ($action === 'messages') {
    $type = $_POST['channel_type'] ?? '';
    $chId = (int)($_POST['channel_id'] ?? 0);
    $after = (int)($_POST['after'] ?? 0);

    // 권한 체크
    if ($type === 'exec' && !$isExec) { echo json_encode(['messages'=>[]]); exit; }
    if ($type === 'dm') {
        $ck = $db->prepare("SELECT id FROM messenger_dm_pairs WHERE id=? AND (user1_id=? OR user2_id=?)");
        $ck->execute([$chId, $userId, $userId]);
        if (!$ck->fetchColumn()) { echo json_encode(['messages'=>[]]); exit; }
    }

    $q = $db->prepare("SELECT mm.msg_id, mm.sender_id, mm.message, mm.created_at, s.name AS sender_name
        FROM messenger_messages mm
        JOIN user_account ua ON mm.sender_id=ua.user_id
        JOIN staff s ON ua.staff_id=s.staff_id
        WHERE mm.channel_type=? AND mm.channel_id=? AND mm.msg_id>?
        ORDER BY mm.msg_id ASC LIMIT 200");
    $q->execute([$type, $chId, $after]);
    echo json_encode(['messages'=>$q->fetchAll(PDO::FETCH_ASSOC)]); exit;
}

// ── 메시지 전송 ──
if ($action === 'send') {
    $type = $_POST['channel_type'] ?? '';
    $chId = (int)($_POST['channel_id'] ?? 0);
    $msg = trim($_POST['message'] ?? '');
    if (!$msg) { echo json_encode(['error'=>'empty']); exit; }
    if ($type === 'exec' && !$isExec) { echo json_encode(['error'=>'perm']); exit; }

    $ins = $db->prepare("INSERT INTO messenger_messages (channel_type, channel_id, sender_id, message) VALUES(?,?,?,?)");
    $ins->execute([$type, $chId, $userId, $msg]);
    $newId = $db->lastInsertId();

    // 본인 읽음 처리
    $db->prepare("INSERT INTO messenger_read_status (user_id, channel_type, channel_id, last_read_id) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE last_read_id=?")->execute([$userId, $type, $chId, $newId, $newId]);

    echo json_encode(['ok'=>true,'msg_id'=>$newId]); exit;
}

// ── DM 시작 ──
if ($action === 'start_dm') {
    $targetId = (int)($_POST['target_user_id'] ?? 0);
    if (!$targetId || $targetId == $userId) { echo json_encode(['error'=>'invalid']); exit; }
    $u1 = min($userId, $targetId); $u2 = max($userId, $targetId);
    $db->prepare("INSERT IGNORE INTO messenger_dm_pairs (user1_id, user2_id) VALUES(?,?)")->execute([$u1, $u2]);
    $did = $db->prepare("SELECT id FROM messenger_dm_pairs WHERE user1_id=? AND user2_id=?"); $did->execute([$u1, $u2]);
    echo json_encode(['dm_id'=>(int)$did->fetchColumn()]); exit;
}

// ── 읽음 처리 ──
if ($action === 'mark_read') {
    $type = $_POST['channel_type'] ?? '';
    $chId = (int)($_POST['channel_id'] ?? 0);
    $maxId = (int)$db->prepare("SELECT COALESCE(MAX(msg_id),0) FROM messenger_messages WHERE channel_type=? AND channel_id=?")->execute([$type,$chId]) ? $db->query("SELECT FOUND_ROWS()")->fetchColumn() : 0;
    // 정확한 max 가져오기
    $mx = $db->prepare("SELECT COALESCE(MAX(msg_id),0) FROM messenger_messages WHERE channel_type=? AND channel_id=?"); $mx->execute([$type,$chId]); $maxId = (int)$mx->fetchColumn();
    $db->prepare("INSERT INTO messenger_read_status (user_id, channel_type, channel_id, last_read_id) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE last_read_id=GREATEST(last_read_id,?)")->execute([$userId, $type, $chId, $maxId, $maxId]);
    echo json_encode(['ok'=>true]); exit;
}

echo json_encode(['error'=>'unknown']);
