<?php
// pages/policy.php — 규정안내 (표기 전용)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();

$rules = $db->query("SELECT * FROM policy_rule ORDER BY rule_id")->fetchAll();
$ruleMap = []; foreach ($rules as $r) $ruleMap[$r['rule_key']] = $r;

function formatPolicyValue($key, $val) {
    $moneyKeys = ['min_profit_threshold','revenue_target_monthly','profit_target_monthly'];
    if (in_array($key, $moneyKeys) && is_numeric($val)) return number_format((int)$val / 10000) . ' 만원';
    if (is_numeric($val) && (int)$val >= 10000 && !str_contains($key, 'weight') && !str_contains($key, 'rate')) return number_format((int)$val / 10000) . ' 만원';
    if (is_numeric($val) && (int)$val > 0 && !str_contains($key, 'weight') && !str_contains($key, 'rate') && !str_contains($key, 'day') && !str_contains($key, 'year')) return number_format((int)$val);
    return htmlspecialchars($val);
}

$policyGmList = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 AND TRIM(grade_name)!='' ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
$policyIrMap = []; try { foreach($db->query("SELECT * FROM incentive_rate WHERE COALESCE(is_active,1)=1")->fetchAll() as $ir) { $policyIrMap[$ir['grade']]=$ir; } } catch(Exception $e){}

$activePromos = [];
try { $activePromos = $db->query("SELECT * FROM promotion WHERE is_active=1 ORDER BY promo_month DESC")->fetchAll(); } catch(Exception $e) {}

$incKeys = ['min_profit_threshold','incentive_min_deals','incentive_cycle'];
$perfKeys = ['revenue_target_monthly','profit_target_monthly','deal_target_monthly','kpi_weight_revenue','kpi_weight_deal'];
$opsKeys = ['approval_required','approval_deadline_day','fiscal_year_start'];
$usedKeys = array_merge($incKeys, $perfKeys, $opsKeys);
$otherRules = array_filter($rules, fn($r) => !in_array($r['rule_key'], $usedKeys));
?>

<div class="page-header"><h2>📋 영업 규정 안내</h2><div class="breadcrumb">제도 시행 정보 (읽기 전용)</div></div>

<?php if ($activePromos): ?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>🎯 진행 중인 프로모션</h3></div>
    <?php foreach ($activePromos as $promo): ?>
    <div style="padding:0.5rem 0;border-bottom:1px solid rgba(255,255,255,0.04);display:flex;gap:0.75rem;align-items:center;">
        <span class="badge badge-info"><?= $promo['promo_month'] ?></span>
        <strong><?= htmlspecialchars($promo['title']) ?></strong>
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($promo['description']??'') ?></span>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- 인센티브 기준 (인센티브 + 실적 기준 통합, 가로 나란히) -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1rem;">
    <div class="card">
        <div class="card-header"><h3>💰 인센티브 기준</h3></div>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(10rem,1fr));gap:0.75rem;padding:0.5rem;">
        <?php foreach ($incKeys as $k): $r = $ruleMap[$k] ?? null; if(!$r) continue; ?>
            <div style="padding:0.75rem;border-radius:var(--radius-sm);background:rgba(255,255,255,0.02);">
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.25rem;"><?= htmlspecialchars($r['description']?:$r['rule_key']) ?></div>
                <div style="font-size:var(--fs-lg);font-weight:800;color:var(--accent-text);"><?= formatPolicyValue($r['rule_key'], $r['rule_value']) ?></div>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    <div class="card">
        <div class="card-header"><h3>📊 실적 기준</h3></div>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(10rem,1fr));gap:0.75rem;padding:0.5rem;">
        <?php foreach ($perfKeys as $k): $r = $ruleMap[$k] ?? null; if(!$r) continue; ?>
            <div style="padding:0.75rem;border-radius:var(--radius-sm);background:rgba(255,255,255,0.02);">
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.25rem;"><?= htmlspecialchars($r['description']?:$r['rule_key']) ?></div>
                <div style="font-size:var(--fs-lg);font-weight:800;color:var(--accent-text);"><?= formatPolicyValue($r['rule_key'], $r['rule_value']) ?></div>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>

<?php $opsRules = array_filter(array_map(fn($k)=>$ruleMap[$k]??null, $opsKeys)); if ($opsRules): ?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>📅 운영 기준</h3></div>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(12rem,1fr));gap:0.75rem;padding:0.5rem;">
    <?php foreach ($opsRules as $r): if(!$r) continue; ?>
        <div style="padding:0.75rem;border-radius:var(--radius-sm);background:rgba(255,255,255,0.02);">
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.25rem;"><?= htmlspecialchars($r['description']?:$r['rule_key']) ?></div>
            <div style="font-size:var(--fs-lg);font-weight:800;color:var(--accent-text);"><?= formatPolicyValue($r['rule_key'], $r['rule_value']) ?></div>
        </div>
    <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<?php if ($otherRules): ?>
<div class="card" style="margin-bottom:1rem;">
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(12rem,1fr));gap:0.75rem;padding:0.5rem;">
    <?php foreach ($otherRules as $r): ?>
        <div style="padding:0.75rem;border-radius:var(--radius-sm);background:rgba(255,255,255,0.02);">
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.25rem;"><?= htmlspecialchars($r['description']?:$r['rule_key']) ?></div>
            <div style="font-size:var(--fs-lg);font-weight:800;"><?= formatPolicyValue($r['rule_key'], $r['rule_value']) ?></div>
        </div>
    <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- 직급별 인센티브 비율표 (인센티브 비율 설정 연동) -->
<div class="card">
    <div class="card-header"><h3>💎 직급별 인센티브 산출 비율표</h3><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">인센티브 비율 설정 메뉴 연동</div></div>
    <div style="overflow-x:auto;"><table class="data-table">
        <thead><tr><th>직급</th><th>최소</th><th>최대</th><th>기준</th><th>비고</th></tr></thead>
        <tbody>
        <?php foreach ($policyGmList as $gn): $r = $policyIrMap[$gn] ?? null; if(!$r) continue; ?>
        <tr><td><span class="badge badge-info"><?= htmlspecialchars($gn) ?></span></td>
            <td><?= $r ? round($r['min_rate']*100,1) : 3 ?>%</td><td><?= $r ? round($r['max_rate']*100,1) : 8 ?>%</td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($r['basis'] ?? '순이익 기준') ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($r['memo'] ?? '') ?></td></tr>
        <?php endforeach; ?>
        <?php if (!$policyGmList): ?><tr><td colspan="5" class="text-muted">직급 데이터가 없습니다.</td></tr><?php endif; ?>
        </tbody>
    </table></div>
</div>
<?php require_once __DIR__.'/../includes/footer.php'; ?>
