<?php
// pages/incentive_rate.php — 인센티브 비율 설정 (대표/시스템관리자 전용)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();

$msg = '';

// POST: 비율 저장
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_rates') {
    $grades = $_POST['grades'] ?? [];
    foreach ($grades as $gradeName => $vals) {
        $gradeName = trim($gradeName);
        if ($gradeName === '') continue;
        $minR = floatval($vals['min_rate'] ?? 3) / 100;
        $maxR = floatval($vals['max_rate'] ?? 8) / 100;
        $basis = trim($vals['basis'] ?? '순이익 기준');
        $memo = trim($vals['memo'] ?? '');
        $isActive = isset($vals['is_active']) ? 1 : 0;
        try {
            $db->prepare("INSERT INTO incentive_rate (grade, min_rate, max_rate, basis, memo, is_active) VALUES(?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE min_rate=VALUES(min_rate), max_rate=VALUES(max_rate), basis=VALUES(basis), memo=VALUES(memo), is_active=VALUES(is_active)")
               ->execute([$gradeName, $minR, $maxR, $basis, $memo, $isActive]);
        } catch(Exception $e) {}
    }
    $msg = '인센티브 비율이 저장되었습니다.';
}

// ── grade_master 직급 목록 (원본 그대로) ──
$gmList = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 AND grade_name IS NOT NULL AND TRIM(grade_name) != '' ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);

// ── incentive_rate 기존 데이터 맵 ──
$irMap = [];
try {
    $irAll = $db->query("SELECT * FROM incentive_rate")->fetchAll();
    foreach ($irAll as $ir) { $irMap[$ir['grade']] = $ir; }
} catch(Exception $e) {}

// UNIQUE KEY 보장
try { $db->exec("ALTER TABLE incentive_rate ADD UNIQUE KEY uk_grade (grade)"); } catch(Exception $e) {}
// is_active 컬럼 보장
try { $db->exec("ALTER TABLE incentive_rate ADD COLUMN is_active TINYINT(1) DEFAULT 1"); } catch(Exception $e) {}
?>

<div class="page-header"><h2>💎 인센티브 비율 설정</h2><div class="breadcrumb">대표 / 시스템 관리자 전용</div></div>

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

<form method="POST">
<input type="hidden" name="action" value="save_rates">
<div class="card">
    <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
        <h3>📊 직급별 인센티브 비율 (<?= count($gmList) ?>개 직급)</h3>
        <button type="submit" class="btn btn-primary" style="font-size:var(--fs-sm);">💾 전체 저장</button>
    </div>
    <div style="overflow-x:auto;">
    <table class="data-table">
        <thead><tr><th>No</th><th>직급</th><th>활성화</th><th>최소 (%)</th><th>최대 (%)</th><th>산출 기준</th><th>비고</th></tr></thead>
        <tbody>
        <?php if ($gmList): foreach ($gmList as $idx => $gn):
            $existing = $irMap[$gn] ?? null;
            $minV = $existing ? round($existing['min_rate'] * 100, 2) : 3;
            $maxV = $existing ? round($existing['max_rate'] * 100, 2) : 8;
            $basisV = $existing ? $existing['basis'] : '순이익 기준';
            $memoV = $existing ? ($existing['memo'] ?? '') : '';
            $isActiveV = $existing ? (int)($existing['is_active'] ?? 1) : 1;
        ?>
        <tr style="<?= !$isActiveV ? 'opacity:0.45;' : '' ?>" id="row_<?= $idx ?>">
            <td style="color:var(--text-tertiary);"><?= $idx + 1 ?></td>
            <td><span class="badge <?= $isActiveV ? 'badge-info' : 'badge-gray' ?>"><?= htmlspecialchars($gn) ?></span></td>
            <td style="">
                <label style="position:relative;display:inline-block;width:44px;height:24px;cursor:pointer;">
                    <input type="checkbox" name="grades[<?= htmlspecialchars($gn) ?>][is_active]" value="1" <?= $isActiveV ? 'checked' : '' ?>
                        onchange="this.closest('tr').style.opacity=this.checked?'1':'0.45'; this.closest('tr').querySelector('.badge').className=this.checked?'badge badge-info':'badge badge-gray';"
                        style="opacity:0;width:0;height:0;position:absolute;">
                    <span style="position:absolute;inset:0;background:<?= $isActiveV ? 'var(--accent)' : '#555' ?>;border-radius:24px;transition:all .3s;"
                        class="toggle-track"></span>
                    <span style="position:absolute;top:2px;left:<?= $isActiveV ? '22px' : '2px' ?>;width:20px;height:20px;background:#fff;border-radius:50%;transition:all .3s;"
                        class="toggle-thumb"></span>
                </label>
            </td>
            <td><input type="number" name="grades[<?= htmlspecialchars($gn) ?>][min_rate]" value="<?= $minV ?>" step="0.1" style="width:5rem;font-size:var(--fs-sm);">%</td>
            <td><input type="number" name="grades[<?= htmlspecialchars($gn) ?>][max_rate]" value="<?= $maxV ?>" step="0.1" style="width:5rem;font-size:var(--fs-sm);">%</td>
            <td><input type="text" name="grades[<?= htmlspecialchars($gn) ?>][basis]" value="<?= htmlspecialchars($basisV) ?>" style="font-size:var(--fs-sm);width:12rem;"></td>
            <td><input type="text" name="grades[<?= htmlspecialchars($gn) ?>][memo]" value="<?= htmlspecialchars($memoV) ?>" style="font-size:var(--fs-sm);width:10rem;" placeholder="비고"></td>
        </tr>
        <?php endforeach; else: ?>
        <tr><td colspan="7" style="padding:2rem;color:var(--text-tertiary);">직급이 등록되지 않았습니다. 인사관리 > 직급관리에서 직급을 추가해주세요.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>
</form>

<style>
input[type="checkbox"]:checked + .toggle-track { background: var(--accent) !important; }
input[type="checkbox"]:not(:checked) + .toggle-track { background: #555 !important; }
input[type="checkbox"]:checked + .toggle-track + .toggle-thumb { left: 22px !important; }
input[type="checkbox"]:not(:checked) + .toggle-track + .toggle-thumb { left: 2px !important; }
</style>

<div class="card" style="margin-top:1rem;padding:1rem;">
    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">
        <strong>안내:</strong> 비율은 순이익 대비 인센티브 지급 범위입니다. 예) 5% = 순이익 1,000만원 → 인센티브 50만원<br>
        최종 지급액은 평가 점수, KPI 달성률 등을 반영하여 최소~최대 범위 내에서 산출됩니다.<br>
        직급 목록은 <a href="<?=BASE_URL?>pages/admin_teams.php" style="color:var(--accent);">인사관리 > 직급관리</a>에서 관리됩니다.
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
