<?php
// pages/performance.php — 평가 점수 (인센티브 산출 + 인사평가 연동)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();
$user = currentUser();
$perm = getMenuPerm($db, 'performance', $user['role']);
$isAdmin = in_array($user['role'], ['manager','ceo','sysadmin']);

// 필터
$filterYear = $_GET['year'] ?? date('Y');
$filterMonth = $_GET['month'] ?? '';
$filterStaff = $_GET['staff_id'] ?? '';
$filterGrade = $_GET['grade'] ?? '';
$filterTeam = $_GET['team'] ?? '';

// 연도/월 목록
$availYears = $db->query("SELECT DISTINCT LEFT(sale_month,4) FROM v_profit_by_person ORDER BY 1 DESC")->fetchAll(PDO::FETCH_COLUMN);
if (!$availYears) $availYears = [date('Y')];
$monthList = [];
try {
    $mStmt = $db->prepare("SELECT DISTINCT sale_month FROM v_profit_by_person WHERE LEFT(sale_month,4)=? ORDER BY sale_month DESC");
    $mStmt->execute([$filterYear]); $monthList = $mStmt->fetchAll(PDO::FETCH_COLUMN);
} catch(Exception $e) {}

$grades = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 AND grade_name NOT IN('대표') ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
$teamList = $db->query("SELECT team_name FROM team_master WHERE is_active=1 AND team_name NOT IN('경영진','경영지원','오너','시스템') ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
$staffOpts = $db->query("SELECT s.staff_id, s.name 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.name")->fetchAll();

// ── 인센티브 산출 데이터 (매출/건수/순이익) ──
try { $profitTargetMonthly = (int)str_replace(',', '', $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='profit_target_monthly'")->fetchColumn()); } catch(Exception $e) { $profitTargetMonthly = 0; }
$incSql = "SELECT ic.staff_id, ic.name, ic.grade, ic.team, ic.sale_month,
    ic.deal_count, ic.target_deals, ic.total_revenue, ic.total_net_profit, ic.target_amount
    FROM v_incentive_calc ic WHERE LEFT(ic.sale_month,4) = ?";
$incParams = [$filterYear];
if ($filterMonth) { $incSql .= " AND ic.sale_month = ?"; $incParams[] = $filterMonth; }
if ($filterGrade) { $incSql .= " AND ic.grade = ?"; $incParams[] = $filterGrade; }
if ($filterStaff) { $incSql .= " AND ic.staff_id = ?"; $incParams[] = $filterStaff; }
if ($filterTeam) { $incSql .= " AND ic.team = ?"; $incParams[] = $filterTeam; }
if (!$isAdmin) { $incSql .= " AND ic.staff_id = ?"; $incParams[] = $user['staff_id']; }
// user_role 제외
$incSql .= " AND ic.staff_id NOT IN (SELECT staff_id FROM user_account WHERE user_role IN('ceo','sysadmin') AND is_active=1)";
$incSql .= " ORDER BY ic.total_revenue DESC";
$incStmt = $db->prepare($incSql); $incStmt->execute($incParams);
$incRows = $incStmt->fetchAll();

// staff_id 기준 그룹 (월별 합산 or 최신)
$incMap = [];
foreach ($incRows as $r) {
    $sid = $r['staff_id'];
    if (!isset($incMap[$sid])) {
        $incMap[$sid] = [
            'staff_id' => $sid, 'name' => $r['name'], 'grade' => $r['grade'], 'team' => $r['team'],
            'deal_count' => 0, 'target_deals' => (int)$r['target_deals'],
            'total_revenue' => 0, 'total_net_profit' => 0,
            'target_amount' => $profitTargetMonthly ?: (int)$r['target_amount'],
            'months' => 0
        ];
    }
    $incMap[$sid]['deal_count'] += (int)$r['deal_count'];
    $incMap[$sid]['total_revenue'] += (int)$r['total_revenue'];
    $incMap[$sid]['total_net_profit'] += (int)($r['total_net_profit'] ?? 0);
    $incMap[$sid]['months']++;
    // 목표는 월수 곱
    $incMap[$sid]['target_deals_total'] = $incMap[$sid]['target_deals'] * $incMap[$sid]['months'];
    $incMap[$sid]['target_amount_total'] = $incMap[$sid]['target_amount'] * $incMap[$sid]['months'];
}

// ── 인사평가 데이터 (정량/태도/협업/정성) ──
$evalPeriodFilter = $filterMonth ?: $filterYear . '-%';
$evalSql = "SELECT e.target_staff_id, 
    ROUND(AVG(e.score_quant),1) AS avg_quant,
    ROUND(AVG(e.score_attitude),1) AS avg_attitude,
    ROUND(AVG(e.score_collab),1) AS avg_collab,
    ROUND(AVG(e.score_qual),1) AS avg_qual
    FROM evaluation e WHERE e.eval_period LIKE ? GROUP BY e.target_staff_id";
try {
    $evalStmt = $db->prepare($evalSql);
    $evalStmt->execute([$evalPeriodFilter]);
    $evalMap = [];
    foreach ($evalStmt->fetchAll() as $ev) { $evalMap[$ev['target_staff_id']] = $ev; }
} catch(Exception $e) { $evalMap = []; }

// ── 매출 기여도 (전체 매출 대비 개인 비율) ──
$totalAllRev = array_sum(array_column($incRows, 'total_revenue'));

// ── 종합 데이터 빌드 ──
$scores = [];
foreach ($incMap as $sid => $inc) {
    $ev = $evalMap[$sid] ?? null;
    $revRate = ($inc['target_amount_total'] ?? 0) > 0 ? round(($inc['total_net_profit'] ?? 0) / $inc['target_amount_total'] * 100, 1) : 0;
    $dealRate = ($inc['target_deals_total'] ?? 0) > 0 ? round($inc['deal_count'] / $inc['target_deals_total'] * 100, 1) : 0;
    $contribPct = $totalAllRev > 0 ? round($inc['total_revenue'] / $totalAllRev * 100, 1) : 0;

    $quant = $ev ? (float)$ev['avg_quant'] : 0;
    $attitude = $ev ? (float)$ev['avg_attitude'] : 0;
    $collab = $ev ? (float)$ev['avg_collab'] : 0;
    $qual = $ev ? (float)$ev['avg_qual'] : 0;

    // 종합: 정량(매출+건수 평균)*0.6 + 정성(태도+협업+정성 평균)/100*40
    $quantScore = round((($revRate + $dealRate) / 2) * 0.6, 1);
    $qualScore = ($quant + $attitude + $collab + $qual) > 0 ? round(($quant + $attitude + $collab + $qual) / 4 / 100 * 40, 1) : 0;
    $totalScore = round($quantScore + $qualScore, 1);

    $scores[] = [
        'staff_id' => $sid, 'name' => $inc['name'], 'grade' => $inc['grade'], 'team' => $inc['team'],
        'revenue_rate' => $revRate, 'deal_rate' => $dealRate, 'contrib_pct' => $contribPct,
        'quant' => $quant, 'attitude' => $attitude, 'collab' => $collab, 'qual' => $qual,
        'quant_score' => $quantScore, 'qual_score' => $qualScore, 'total_score' => $totalScore,
    ];
}

// 종합 점수 내림차순
usort($scores, fn($a, $b) => $b['total_score'] <=> $a['total_score']);

$periodLabel = $filterMonth ?: ($filterYear . '년 평균');

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

$top10 = array_slice($scores, 0, 10);
$maxVal = $scores ? $scores[0]['total_score'] : 0;
$minVal = $scores ? end($scores)['total_score'] : 0; reset($scores);
$maxPersons = array_filter($scores, fn($s) => $s['total_score'] == $maxVal);
$minPersons = array_filter($scores, fn($s) => $s['total_score'] == $minVal);

function getStaffProfileUrl2($db, $staffId) {
    $uid = $db->prepare("SELECT user_id FROM user_account WHERE staff_id=?"); $uid->execute([$staffId]); $userId = $uid->fetchColumn();
    if ($userId) { $g = glob(__DIR__ . '/../assets/theme/' . $userId . '/profile.*'); if ($g) return BASE_URL.'assets/theme/' . $userId . '/' . basename($g[0]); }
    return BASE_URL.'assets/empty.png';
}
?>

<div class="page-header"><h2>⭐ 평가 점수</h2><div class="breadcrumb"><?= $periodLabel ?> · 매출/건수: 인센티브 산출 연동 · 정량/태도/협업/정성: 인사평가 연동</div></div>

<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="year" onchange="this.form.submit()" class="dash-filter" style="width:7rem;">
            <?php foreach ($availYears as $y): ?><option value="<?= $y ?>" <?= $filterYear==$y?'selected':'' ?>><?= $y ?>년</option><?php endforeach; ?>
        </select>
        <select name="month" onchange="this.form.submit()" class="dash-filter" style="width:9rem;">
            <option value="">연 평균</option>
            <?php foreach ($monthList as $m): ?><option value="<?= $m ?>" <?= $filterMonth===$m?'selected':'' ?>><?= $m ?></option><?php endforeach; ?>
        </select>
        <?php if ($isAdmin): ?>
        <select name="grade" onchange="this.form.submit()" class="dash-filter" style="width:7rem;">
            <option value="">직급 전체</option>
            <?php foreach($grades as $g): ?><option value="<?= $g ?>" <?= $filterGrade===$g?'selected':'' ?>><?= $g ?></option><?php endforeach; ?>
        </select>
        <select name="team" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">팀 전체</option>
            <?php foreach($teamList as $t): ?><option value="<?= $t ?>" <?= $filterTeam===$t?'selected':'' ?>><?= htmlspecialchars($t) ?></option><?php endforeach; ?>
        </select>
        <select name="staff_id" onchange="this.form.submit()" class="dash-filter" style="width:9rem;">
            <option value="">담당자 전체</option>
            <?php foreach($staffOpts as $s): ?><option value="<?= $s['staff_id'] ?>" <?= $filterStaff==$s['staff_id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option><?php endforeach; ?>
        </select>
        <?php endif; ?>
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-left:auto;"><?= $totalCnt ?>명</span>
    </form>
</div>

<?php if ($scores && $isAdmin): ?>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1rem;">
    <div class="card" style="padding:1rem;">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
            <div style="">
                <div style="font-size:1.25rem;margin-bottom:0.25rem;">🏆</div>
                <?php $mpFirst = reset($maxPersons); $mpPhoto = getStaffProfileUrl2($db, $mpFirst['staff_id']); ?>
                <div style="width:5rem;height:5rem;border-radius:50%;overflow:hidden;margin:0 auto 0.5rem;border:2px solid rgba(var(--accent-rgb),0.3);"><img src="<?= $mpPhoto ?>" alt="" style="width:100%;height:100%;object-fit:cover;"></div>
                <?php foreach($maxPersons as $mp): ?><div style="font-size:var(--fs-sm);font-weight:700;"><?= htmlspecialchars($mp['name']) ?></div><?php endforeach; ?>
                <div style="font-size:var(--fs-xl);font-weight:800;color:var(--accent-text);margin-top:0.25rem;"><?= $maxVal ?></div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">최고 점수</div>
            </div>
            <div style="">
                <div style="font-size:1.25rem;margin-bottom:0.25rem;">📉</div>
                <?php $mnFirst = reset($minPersons); $mnPhoto = getStaffProfileUrl2($db, $mnFirst['staff_id']); ?>
                <div style="width:5rem;height:5rem;border-radius:50%;overflow:hidden;margin:0 auto 0.5rem;border:2px solid rgba(255,255,255,0.08);"><img src="<?= $mnPhoto ?>" alt="" style="width:100%;height:100%;object-fit:cover;"></div>
                <?php foreach($minPersons as $mp): ?><div style="font-size:var(--fs-sm);font-weight:700;color:var(--text-secondary);"><?= htmlspecialchars($mp['name']) ?></div><?php endforeach; ?>
                <div style="font-size:var(--fs-xl);font-weight:800;color:var(--text-tertiary);margin-top:0.25rem;"><?= $minVal ?></div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">최저 점수</div>
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" style="padding:0.5rem 1rem;"><h3>🏅 TOP 10</h3></div>
        <div style="max-height:10rem;overflow-y:auto;">
        <?php foreach($top10 as $i=>$t): ?>
        <div style="padding:0.35rem 1rem;display:flex;align-items:center;gap:0.5rem;border-bottom:1px solid var(--border);">
            <span style="font-weight:800;color:<?= $i<3?'var(--accent-text)':'var(--text-tertiary)' ?>;width:1.25rem;"><?= $i+1 ?></span>
            <span style="flex:1;font-size:var(--fs-sm);"><?= htmlspecialchars($t['name']) ?> <span class="badge badge-info" style="font-size:var(--fs-xs);"><?= $t['grade'] ?></span></span>
            <strong style="color:var(--accent-text);font-size:var(--fs-sm);"><?= $t['total_score'] ?></strong>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><h3>종합 평가</h3></div>
    <div style="padding:0.75rem 1rem;border-bottom:1px solid var(--border);font-size:var(--fs-xs);color:var(--text-secondary);line-height:1.7;">
        <strong style="color:var(--text-primary);">📐 평가 산출 기준</strong><br>
        <strong>종합점수</strong> = 정량점수(60%) + 정성점수(40%)<br>
        <strong>정량점수</strong> = (매출 달성률 + 건수 달성률) ÷ 2 × 0.6 &nbsp;—&nbsp; 매출 달성률: 매출 ÷ 목표매출 × 100, 건수 달성률: 성사건수 ÷ 목표건수 × 100<br>
        <strong>정성점수</strong> = (정량 + 태도 + 협업 + 정성 평균) ÷ 100 × 40 &nbsp;—&nbsp; 인사평가에서 등록된 점수 기반 (각 항목 0~100점)<br>
        <strong>기여도</strong> = 개인 매출 ÷ 전체 매출 × 100
    </div>
    <div style="overflow-x:auto;"><table class="data-table">
        <thead><tr>
            <th>#</th><th>이름</th><th>직급</th><th>팀</th>
            <?php if($isAdmin):?><th>매출</th><th>건수</th><th>기여도</th><th>정량</th><th>태도</th><th>협업</th><th>정성</th><?php endif;?>
            <th>종합</th>
        </tr></thead>
        <tbody>
        <?php if($scoresPage): foreach($scoresPage as $i=>$s): $idx=($page-1)*$perPage+$i; ?>
        <tr<?= $s['staff_id']==$user['staff_id']?' style="background:rgba(var(--accent-rgb),0.06);"':'' ?>>
            <td style="font-weight:700;color:<?= $idx<3?'var(--accent-text)':'var(--text-tertiary)' ?>;"><?= $idx+1 ?></td>
            <td><strong><?= htmlspecialchars($s['name']) ?></strong></td>
            <td><span class="badge badge-info"><?= $s['grade'] ?></span></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($s['team']) ?></td>
            <?php if($isAdmin):?>
            <td style="color:<?= $s['revenue_rate']>=100?'var(--success)':'inherit' ?>;"><?= $s['revenue_rate'] ?>%</td>
            <td style="color:<?= $s['deal_rate']>=100?'var(--success)':'inherit' ?>;"><?= $s['deal_rate'] ?>%</td>
            <td><?= $s['contrib_pct'] ?>%</td>
            <td><?= $s['quant'] ?></td>
            <td><?= $s['attitude'] ?></td>
            <td><?= $s['collab'] ?></td>
            <td><?= $s['qual'] ?></td>
            <?php endif;?>
            <td><strong style="color:var(--accent-text);"><?= $s['total_score'] ?></strong></td>
        </tr>
        <?php endforeach; else: ?>
        <tr><td colspan="<?= $isAdmin?12:5 ?>" 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'; ?>
