<?php
// pages/evaluation.php — 인사평가 (3단계: 팀장→관리자→대표, 역할 자동 반영)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isLoggedIn()) { header('Location: '.BASE_URL.''); exit; }

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

// 알림 테이블
$db->exec("CREATE TABLE IF NOT EXISTS eval_notification (
    noti_id INT AUTO_INCREMENT PRIMARY KEY,
    target_evaluator_id INT NOT NULL,
    target_staff_id INT NOT NULL,
    eval_period VARCHAR(10) NOT NULL,
    eval_step TINYINT NOT NULL,
    message VARCHAR(200) DEFAULT '',
    is_read TINYINT DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_noti(target_evaluator_id, target_staff_id, eval_period, eval_step)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$db->exec("CREATE TABLE IF NOT EXISTS evaluation (
    eval_id       INT AUTO_INCREMENT PRIMARY KEY,
    target_staff_id INT NOT NULL,
    eval_period   VARCHAR(10) NOT NULL,
    evaluator_id  INT NOT NULL,
    evaluator_role VARCHAR(30) NOT NULL,
    eval_step     TINYINT DEFAULT 1 COMMENT '1=팀장,2=관리자,3=대표',
    score_quant   DECIMAL(5,1) DEFAULT 0,
    score_attitude DECIMAL(5,1) DEFAULT 0,
    score_collab  DECIMAL(5,1) DEFAULT 0,
    score_qual    DECIMAL(5,1) DEFAULT 0,
    total_score   DECIMAL(5,1) DEFAULT 0,
    eval_status   ENUM('작성중','팀장완료','관리자완료','확정') DEFAULT '작성중',
    comment       TEXT,
    created_at    DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at    DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_eval (target_staff_id, eval_period, eval_step)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
try { $db->query("SELECT eval_step FROM evaluation LIMIT 0"); } catch(Exception $e) {
    $db->exec("ALTER TABLE evaluation ADD COLUMN eval_step TINYINT DEFAULT 1 AFTER evaluator_role");
}

// 현재 사용자 역할 정보
$userRole = $_SESSION['user_role'] ?? 'staff';
$userStaffId = $_SESSION['user_id'] ?? 0;
$userStaff = $db->prepare("SELECT staff_id, name, team FROM staff WHERE staff_id=?");
$userStaff->execute([currentUser()['staff_id'] ?? 0]); $myStaff = $userStaff->fetch();
$myTeamName = $myStaff['team'] ?? '';

// 팀장/관리자/대표 ID 목록
$teamLeaders = $db->query("SELECT ua.staff_id, s.team FROM user_account ua JOIN staff s ON ua.staff_id=s.staff_id WHERE ua.user_role='team_leader' AND ua.is_active=1")->fetchAll();
$tlMap = []; foreach($teamLeaders as $tl) $tlMap[$tl['team']] = $tl['staff_id'];
$mgrIds = $db->query("SELECT staff_id FROM user_account WHERE user_role='manager' AND is_active=1")->fetchAll(PDO::FETCH_COLUMN);
$ceoIds = $db->query("SELECT staff_id FROM user_account WHERE user_role IN('ceo') AND is_active=1")->fetchAll(PDO::FETCH_COLUMN);

// POST: 평가 저장
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_eval') {
    $targetId = (int)$_POST['target_staff_id'];
    $period = $_POST['eval_period'];
    $sq = round((float)$_POST['score_quant'], 1);
    $sa = round((float)$_POST['score_attitude'], 1);
    $sc = round((float)$_POST['score_collab'], 1);
    $sl = round((float)$_POST['score_qual'], 1);
    $total = round(($sq + $sa + $sc + $sl) / 4, 1);
    $comment = trim($_POST['comment'] ?? '');

    $user = currentUser();
    $evalStaffId = $user['staff_id'];

    // 대상자 팀 조회
    $tgtS = $db->prepare("SELECT team FROM staff WHERE staff_id=?"); $tgtS->execute([$targetId]); $tgtTeam = $tgtS->fetchColumn();
    $tgtTeamLeaderId = $tlMap[$tgtTeam] ?? null;

    // 사용자 역할에 따라 자동으로 단계 결정
    $evalStep = 0; $status = '작성중'; $allowed = false;

    if ($userRole === 'sysadmin') {
        // 시스템관리자: 모든 평가 가능 — 현재 다음 단계 자동 결정
        $maxStep = (int)$db->prepare("SELECT COALESCE(MAX(eval_step),0) FROM evaluation WHERE target_staff_id=? AND eval_period=?")->execute([$targetId,$period]) ? 0 : 0;
        $ms = $db->prepare("SELECT COALESCE(MAX(eval_step),0) FROM evaluation WHERE target_staff_id=? AND eval_period=?");
        $ms->execute([$targetId,$period]); $maxStep = (int)$ms->fetchColumn();
        $evalStep = min($maxStep + 1, 3);
        if ($evalStep === 1) $status = '팀장완료';
        elseif ($evalStep === 2) $status = '관리자완료';
        else $status = '확정';
        $allowed = true;

    } elseif ($userRole === 'team_leader') {
        // 팀장: 1차만, 자기 팀만
        if ($tgtTeam === $myTeamName) {
            $exists1 = $db->prepare("SELECT eval_id FROM evaluation WHERE target_staff_id=? AND eval_period=? AND eval_step=1");
            $exists1->execute([$targetId,$period]);
            if (!$exists1->fetch()) { $evalStep = 1; $status = '팀장완료'; $allowed = true; }
        }

    } elseif ($userRole === 'manager') {
        // 관리자: 2차 (1차 완료 후)
        // 팀장과 관리자가 동일인이면 1차 패스하고 2차 바로 진행
        $exists1 = $db->prepare("SELECT eval_id FROM evaluation WHERE target_staff_id=? AND eval_period=? AND eval_step=1");
        $exists1->execute([$targetId,$period]);
        $has1 = $exists1->fetch();
        $isSameAsTL = ($tgtTeamLeaderId && in_array($tgtTeamLeaderId, $mgrIds));

        if ($has1 || $isSameAsTL || !$tgtTeamLeaderId) {
            $exists2 = $db->prepare("SELECT eval_id FROM evaluation WHERE target_staff_id=? AND eval_period=? AND eval_step=2");
            $exists2->execute([$targetId,$period]);
            if (!$exists2->fetch()) { $evalStep = 2; $status = '관리자완료'; $allowed = true; }
        }

    } elseif ($userRole === 'ceo') {
        // 대표: 3차 (2차 완료 후, 본인 차례만)
        $exists2 = $db->prepare("SELECT eval_id FROM evaluation WHERE target_staff_id=? AND eval_period=? AND eval_step=2");
        $exists2->execute([$targetId,$period]);
        $has2 = $exists2->fetch();
        // 관리자=팀장 동일인이고 1차 완료 시에도 대표 진행 가능
        $isSameAsTL = ($tgtTeamLeaderId && in_array($tgtTeamLeaderId, $mgrIds));
        $exists1 = $db->prepare("SELECT eval_id FROM evaluation WHERE target_staff_id=? AND eval_period=? AND eval_step=1");
        $exists1->execute([$targetId,$period]); $has1 = $exists1->fetch();

        if ($has2 || ($has1 && $isSameAsTL)) {
            $exists3 = $db->prepare("SELECT eval_id FROM evaluation WHERE target_staff_id=? AND eval_period=? AND eval_step=3");
            $exists3->execute([$targetId,$period]);
            if (!$exists3->fetch()) { $evalStep = 3; $status = '확정'; $allowed = true; }
        }
    }

    if ($allowed && $evalStep > 0) {
        $db->prepare("INSERT INTO evaluation (target_staff_id, eval_period, evaluator_id, evaluator_role, eval_step, score_quant, score_attitude, score_collab, score_qual, total_score, eval_status, comment)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
            ON DUPLICATE KEY UPDATE score_quant=VALUES(score_quant), score_attitude=VALUES(score_attitude), score_collab=VALUES(score_collab), score_qual=VALUES(score_qual), total_score=VALUES(total_score), eval_status=VALUES(eval_status), comment=VALUES(comment), evaluator_id=VALUES(evaluator_id)")
            ->execute([$targetId, $period, $evalStaffId, $userRole, $evalStep, $sq, $sa, $sc, $sl, $total, $status, $comment]);

        // 다음 단계 알림 생성
        if ($evalStep === 1) {
            // 1차 완료 → 2차(관리자) 알림
            foreach ($mgrIds as $mgrId) {
                $db->prepare("INSERT IGNORE INTO eval_notification (target_evaluator_id, target_staff_id, eval_period, eval_step, message) VALUES(?,?,?,?,?)")
                   ->execute([$mgrId, $targetId, $period, 2, $myStaff['name'].'님이 '.htmlspecialchars($db->prepare("SELECT name FROM staff WHERE staff_id=?")->execute([$targetId])?$db->query("SELECT name FROM staff WHERE staff_id=$targetId")->fetchColumn():'').' 1차 평가를 완료했습니다. 2차 평가를 진행해주세요.']);
            }
        } elseif ($evalStep === 2) {
            // 2차 완료 → 3차(대표) 알림
            foreach ($ceoIds as $ceoId) {
                $tgtName = $db->query("SELECT name FROM staff WHERE staff_id=$targetId")->fetchColumn();
                $db->prepare("INSERT IGNORE INTO eval_notification (target_evaluator_id, target_staff_id, eval_period, eval_step, message) VALUES(?,?,?,?,?)")
                   ->execute([$ceoId, $targetId, $period, 3, $myStaff['name'].'님이 '.$tgtName.' 2차 평가를 완료했습니다. 3차(최종) 평가를 진행해주세요.']);
            }
        }
    }
    header("Location: ".BASE_URL."pages/evaluation.php?period=" . urlencode($period) . ($allowed ? '&msg=평가가 저장되었습니다.' : '&msg=평가 권한이 없거나 이전 단계가 미완료입니다.')); exit;
}

// 알림 읽음 처리
if (isset($_GET['read_noti'])) {
    $db->prepare("UPDATE eval_notification SET is_read=1 WHERE noti_id=? AND target_evaluator_id=?")->execute([(int)$_GET['read_noti'], currentUser()['staff_id']]);
}

require_once __DIR__ . '/../includes/header.php';
$user = currentUser();
$canEdit = in_array($user['role'], ['ceo','sysadmin']);
$canEval = in_array($user['role'], ['team_leader','manager','ceo','sysadmin']);

$period = $_GET['period'] ?? date('Y-m');
$message = $_GET['msg'] ?? '';
$periods = [];
for ($i = 0; $i < 12; $i++) { $periods[] = date('Y-m', strtotime("-$i months")); }

$staffList = $db->query("SELECT s.staff_id, s.name, s.grade, s.team FROM staff s LEFT JOIN user_account ua ON s.staff_id=ua.staff_id WHERE s.is_active=1 AND (ua.user_role IS NULL OR ua.user_role NOT IN ('ceo','sysadmin','manager')) ORDER BY s.team, s.name")->fetchAll();

// 내 알림
$myNotis = $db->prepare("SELECT * FROM eval_notification WHERE target_evaluator_id=? AND is_read=0 ORDER BY created_at DESC LIMIT 10");
$myNotis->execute([$user['staff_id']]); $notifications = $myNotis->fetchAll();

// 평가 대상별 현재 진행 상태 맵
$progressMap = [];
$pmStmt = $db->prepare("SELECT target_staff_id, MAX(eval_step) AS max_step FROM evaluation WHERE eval_period=? GROUP BY target_staff_id");
$pmStmt->execute([$period]);
foreach ($pmStmt->fetchAll() as $pm) { $progressMap[$pm['target_staff_id']] = (int)$pm['max_step']; }

$evals = $db->prepare("SELECT e.*, s.name, s.grade, s.team, ev.name AS evaluator_name FROM evaluation e JOIN staff s ON e.target_staff_id=s.staff_id LEFT JOIN staff ev ON e.evaluator_id=ev.staff_id WHERE e.eval_period=? ORDER BY s.team, s.name, e.eval_step");
$evals->execute([$period]);
$evalData = $evals->fetchAll();

// 평가 데이터를 staff_id 기준으로 맵핑
$evalByStaff = [];
foreach ($evalData as $e) {
    $evalByStaff[$e['target_staff_id']][] = $e;
}

// 전체 직원 목록 기반으로 표시 데이터 생성 (경영진 제외, staffList 재활용)
$displayRows = [];
foreach ($staffList as $st) {
    $sid = $st['staff_id'];
    if (isset($evalByStaff[$sid])) {
        foreach ($evalByStaff[$sid] as $e) {
            $displayRows[] = $e;
        }
    } else {
        // 평가 미진행 인원
        $displayRows[] = [
            'target_staff_id' => $sid,
            'name' => $st['name'],
            'grade' => $st['grade'],
            'team' => $st['team'],
            'eval_period' => $period,
            'eval_step' => null,
            'evaluator_name' => null,
            'evaluator_role' => null,
            'score_quant' => '-',
            'score_attitude' => '-',
            'score_collab' => '-',
            'score_qual' => '-',
            'total_score' => '-',
            'eval_status' => '미평가',
            'comment' => '',
        ];
    }
}

// 페이지네이션
$totalCnt = count($displayRows);
$perPage = 20; $page = max(1,(int)($_GET['page']??1));
$totalPages = max(1, ceil($totalCnt / $perPage));
$evalPage = array_slice($displayRows, ($page-1)*$perPage, $perPage);

$stepLabels = [1=>'1차(팀장)', 2=>'2차(관리자)', 3=>'3차(대표)'];

// 현재 사용자가 평가할 수 있는 대상 필터링
$evalableTargets = [];
foreach ($staffList as $st) {
    $sid = $st['staff_id'];
    $curStep = $progressMap[$sid] ?? 0;
    $tgtTeam = $st['team'];
    $tgtTL = $tlMap[$tgtTeam] ?? null;
    $isSameAsTL = ($tgtTL && in_array($tgtTL, $mgrIds));
    $canDoThis = false; $nextStep = 0;

    if ($user['role'] === 'sysadmin') { $canDoThis = ($curStep < 3); $nextStep = $curStep + 1; }
    elseif ($user['role'] === 'team_leader' && $tgtTeam === $myTeamName && $curStep < 1) { $canDoThis = true; $nextStep = 1; }
    elseif ($user['role'] === 'manager' && $curStep >= 1 && $curStep < 2) { $canDoThis = true; $nextStep = 2; }
    elseif ($user['role'] === 'manager' && ($isSameAsTL || !$tgtTL) && $curStep < 2) { $canDoThis = true; $nextStep = 2; }
    elseif ($user['role'] === 'ceo' && $curStep >= 2 && $curStep < 3) { $canDoThis = true; $nextStep = 3; }
    elseif ($user['role'] === 'ceo' && $isSameAsTL && $curStep >= 1 && $curStep < 3) { $canDoThis = true; $nextStep = 3; }

    if ($canDoThis) $evalableTargets[] = array_merge($st, ['next_step' => $nextStep]);
}
?>
<div class="page-header"><h2>📝 인사평가</h2><div class="breadcrumb">평가 순서: 1차 팀장 → 2차 관리자(팀장 겸직 시 패스) → 3차 대표 · 시스템관리자: 전체 가능</div></div>

<?php if ($message): ?><div class="alert alert-success" style="margin-bottom:1rem;">✓ <?= htmlspecialchars($message) ?></div><?php endif; ?>

<?php if ($notifications): ?>
<div class="alert alert-warning" style="margin-bottom:1rem;">
    <strong>📬 평가 알림</strong>
    <?php foreach($notifications as $n): ?>
    <div style="font-size:var(--fs-xs);margin-top:0.25rem;display:flex;align-items:center;gap:0.5rem;">
        <span><?= htmlspecialchars($n['message']) ?></span>
        <a href="?period=<?= urlencode($n['eval_period']) ?>&read_noti=<?= $n['noti_id'] ?>" style="font-size:var(--fs-xs);color:var(--accent-text);">확인</a>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="card" style="margin-bottom:1rem;padding:0.75rem 1rem;">
    <form method="GET" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
        <select name="period" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <?php foreach ($periods as $p): ?><option value="<?= $p ?>" <?= $period===$p?'selected':'' ?>><?= $p ?></option><?php endforeach; ?>
        </select>
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">평가 항목: 정량 · 태도 · 협업 · 정성 (각 100점, 평균 = 종합)</span>
    </form>
</div>

<?php if ($canEval && $evalableTargets): ?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>✍️ 평가 입력 (<?= $stepLabels[$evalableTargets[0]['next_step'] ?? 1] ?? '' ?>)</h3></div>
    <form method="POST" style="padding:0.5rem 0;">
        <input type="hidden" name="action" value="save_eval">
        <input type="hidden" name="eval_period" value="<?= $period ?>">
        <div style="display:flex;gap:0.75rem;align-items:end;flex-wrap:wrap;">
            <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">대상자</label>
                <select name="target_staff_id" class="dash-filter" required>
                    <?php foreach ($evalableTargets as $et): ?>
                    <option value="<?= $et['staff_id'] ?>"><?= htmlspecialchars($et['name']) ?> (<?= $et['team'] ?>) — <?= $stepLabels[$et['next_step']] ?? '' ?></option>
                    <?php endforeach; ?>
                </select></div>
            <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">정량</label><input type="number" name="score_quant" min="0" max="100" step="0.5" value="0" class="dash-filter" style="width:5rem;" required></div>
            <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">태도</label><input type="number" name="score_attitude" min="0" max="100" step="0.5" value="0" class="dash-filter" style="width:5rem;" required></div>
            <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">협업</label><input type="number" name="score_collab" min="0" max="100" step="0.5" value="0" class="dash-filter" style="width:5rem;" required></div>
            <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">정성</label><input type="number" name="score_qual" min="0" max="100" step="0.5" value="0" class="dash-filter" style="width:5rem;" required></div>
            <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">코멘트</label><input type="text" name="comment" class="dash-filter" style="width:12rem;" placeholder="한줄 코멘트"></div>
            <button type="submit" class="btn btn-primary" style="padding:0.375rem 1rem;font-size:var(--fs-xs);">저장</button>
        </div>
    </form>
</div>
<?php elseif ($canEval): ?>
<div class="card" style="margin-bottom:1rem;padding:1rem;">
    <div style="color:var(--text-tertiary);font-size:var(--fs-sm);">현재 평가 가능한 대상이 없습니다. (이전 단계 미완료 또는 이미 완료)</div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><h3>📊 평가 현황 (<?= $period ?>)</h3></div>
    <div class="table-wrap"><table>
        <thead><tr><th>No</th><th>년</th><th>월</th><th>이름</th><th>직급</th><th>팀</th><th>단계</th><th>평가자</th><th>정량</th><th>태도</th><th>협업</th><th>정성</th><th>종합</th><th>상태</th>
        <?php if ($canEdit): ?><th>코멘트</th><?php endif; ?></tr></thead>
        <tbody>
        <?php if ($evalPage): $idx=($page-1)*$perPage; foreach ($evalPage as $e): $idx++; ?>
        <tr>
            <td><?= $idx ?></td>
            <td style="font-size:var(--fs-xs);"><?= substr($e['eval_period'],0,4) ?></td>
            <td style="font-size:var(--fs-xs);"><?= substr($e['eval_period'],5,2) ?></td>
            <td><strong><?= htmlspecialchars($e['name']) ?></strong></td>
            <td><span class="badge badge-info"><?= $e['grade'] ?></span></td>
            <td><?= htmlspecialchars($e['team']) ?></td>
            <td><span class="badge <?= ($e['eval_step']??0)==3?'badge-success':(($e['eval_step']??0)==2?'badge-warning':(($e['eval_step']??0)==1?'badge-info':'badge-gray')) ?>" style="font-size:var(--fs-xs);"><?= $e['eval_step'] ? ($stepLabels[$e['eval_step']] ?? '-') : '미평가' ?></span></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $e['evaluator_name'] ? htmlspecialchars($e['evaluator_name']) : ($e['evaluator_role'] ? getRoleLabel($e['evaluator_role']) : '-') ?></td>
            <td><?= $e['score_quant'] ?></td>
            <td><?= $e['score_attitude'] ?></td>
            <td><?= $e['score_collab'] ?></td>
            <td><?= $e['score_qual'] ?></td>
            <td><strong style="color:var(--accent-text);"><?= $e['total_score'] ?></strong></td>
            <td><span class="badge <?= ($e['eval_status']??'')==='확정'?'badge-success':(($e['eval_status']??'')==='작성중'?'badge-gray':(($e['eval_status']??'')==='미평가'?'badge-danger':'badge-warning')) ?>"><?= $e['eval_status'] ?></span></td>
            <?php if ($canEdit): ?>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars(mb_strimwidth($e['comment']??'',0,20,'...')) ?></td>
            <?php endif; ?>
        </tr>
        <?php endforeach; else: ?>
        <tr><td colspan="<?= $canEdit?15:14 ?>" style="padding:2rem;color:var(--text-tertiary);">평가 데이터가 없습니다.</td></tr>
        <?php endif; ?>
        </tbody>
    </table></div>
    <?php if ($totalCnt > 0): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:0.5rem;padding:1rem;">
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 <?= $totalCnt ?>건 (<?= $page ?>/<?= $totalPages ?>)</span>
        <?php if ($totalPages > 1): ?>
        <?php if ($page>1): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">‹ 이전</a><?php endif; ?>
        <?php for($p=max(1,$page-2);$p<=min($totalPages,$page+2);$p++): ?>
        <a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);border-radius:4px;text-decoration:none;<?= $p===$page?'background:var(--accent);color:var(--bg-color);font-weight:700;':'color:var(--text-secondary);' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if ($page<$totalPages): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">다음 ›</a><?php endif; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
