<?php
// pages/policy_settings.php — 정책 설정 (대표/시스템관리자 전용 편집)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'update_rule') {
        $ruleVal = str_replace(',', '', trim($_POST['rule_value']));
        $db->prepare("UPDATE policy_rule SET rule_value=?, description=? WHERE rule_id=?")->execute([$ruleVal, trim($_POST['description']??''), (int)$_POST['rule_id']]);
        $msg = '설정이 저장되었습니다.';
    }
    if ($action === 'add_rule') {
        $key = trim($_POST['rule_key'] ?? '');
        $val = str_replace(',', '', trim($_POST['rule_value'] ?? ''));
        $desc = trim($_POST['description'] ?? '');
        if ($key && $val) {
            try {
                $db->prepare("INSERT INTO policy_rule (rule_key, rule_value, description) VALUES(?,?,?) ON DUPLICATE KEY UPDATE rule_value=VALUES(rule_value), description=VALUES(description)")->execute([$key, $val, $desc]);
                $msg = '정책 항목이 저장되었습니다.';
            } catch(Exception $e) { $msg = '오류: ' . $e->getMessage(); }
        }
    }
    if ($action === 'delete_rule') {
        $db->prepare("DELETE FROM policy_rule WHERE rule_id=?")->execute([(int)$_POST['rule_id']]);
        $msg = '항목이 삭제되었습니다.';
    }
}

// 필수 정책 항목 자동 생성
$requiredRules = [
    'profit_target_monthly' => ['45000000', '월간 1인당 이익 목표'],
    'revenue_target_monthly' => ['200000000', '월간 1인당 매출 목표'],
    'deal_target_monthly' => ['5', '월간 1인당 성사 목표'],
    'incentive_min_deals' => ['3', '인센티브 최소 성사건수'],
];
foreach ($requiredRules as $rk => $rv) {
    try { $db->prepare("INSERT IGNORE INTO policy_rule (rule_key, rule_value, description) VALUES(?,?,?)")->execute([$rk, $rv[0], $rv[1]]); } catch(Exception $e) {}
}

$rules = $db->query("SELECT * FROM policy_rule ORDER BY rule_id")->fetchAll();
$rates = $db->query("SELECT * FROM incentive_rate ir LEFT JOIN grade_master gm ON ir.grade=gm.grade_name ORDER BY gm.sort_order, ir.grade")->fetchAll();

// 그룹핑
$moneyKeys = ['min_profit_threshold','revenue_target_monthly','profit_target_monthly'];
$groups = [
    '💰 인센티브 기준' => ['min_profit_threshold','incentive_min_deals','incentive_cycle'],
    '📊 실적 기준' => ['revenue_target_monthly','profit_target_monthly','deal_target_monthly','kpi_weight_revenue','kpi_weight_deal'],
    '📅 운영 기준' => ['approval_required','approval_deadline_day','fiscal_year_start'],
];
$ruleMap = [];
foreach ($rules as $r) $ruleMap[$r['rule_key']] = $r;
$usedKeys = array_merge(...(array_values($groups)?:[[]]));
$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 ($msg): ?><div class="alert alert-success" style="margin-bottom:1rem;">✓ <?= htmlspecialchars($msg) ?></div><?php endif; ?>

<?php foreach ($groups as $gLabel => $gKeys):
    $gRules = array_filter(array_map(fn($k) => $ruleMap[$k] ?? null, $gKeys));
    if (!$gRules) continue;
?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3><?= $gLabel ?></h3></div>
    <table class="data-table">
        <thead><tr><th style="width:14rem;">키</th><th style="width:10rem;">값</th><th>설명</th><th style="width:5rem;">저장</th></tr></thead>
        <tbody>
        <?php foreach ($gRules as $r): if(!$r) continue; ?>
        <tr><form method="POST"><input type="hidden" name="action" value="update_rule"><input type="hidden" name="rule_id" value="<?= $r['rule_id'] ?>">
            <td style="font-family:monospace;font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($r['rule_key']) ?></td>
            <td><input type="text" name="rule_value" value="<?= htmlspecialchars($r['rule_value']) ?>" <?= in_array($r['rule_key'], $moneyKeys) ? 'data-money inputmode="numeric"' : '' ?> style="font-size:var(--fs-sm);width:100%;"></td>
            <td><input type="text" name="description" value="<?= htmlspecialchars($r['description']) ?>" style="font-size:var(--fs-xs);width:100%;"></td>
            <td><button type="submit" class="btn btn-sm btn-primary" style="font-size:var(--fs-xs);">저장</button></td>
        </form></tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endforeach; ?>

<?php if ($otherRules): ?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>⚙️ 기타 설정</h3></div>
    <table class="data-table">
        <thead><tr><th style="width:14rem;">키</th><th style="width:10rem;">값</th><th>설명</th><th style="width:5rem;">저장</th><th style="width:4rem;">삭제</th></tr></thead>
        <tbody>
        <?php foreach ($otherRules as $r): ?>
        <tr><form method="POST"><input type="hidden" name="action" value="update_rule"><input type="hidden" name="rule_id" value="<?= $r['rule_id'] ?>">
            <td style="font-family:monospace;font-size:var(--fs-xs);"><?= htmlspecialchars($r['rule_key']) ?></td>
            <td><input type="text" name="rule_value" value="<?= htmlspecialchars($r['rule_value']) ?>" <?= in_array($r['rule_key'], $moneyKeys) ? 'data-money inputmode="numeric"' : '' ?> style="font-size:var(--fs-sm);width:100%;"></td>
            <td><input type="text" name="description" value="<?= htmlspecialchars($r['description']) ?>" style="font-size:var(--fs-xs);width:100%;"></td>
            <td><button type="submit" class="btn btn-sm btn-primary" style="font-size:var(--fs-xs);">저장</button></td>
        </form>
            <td><form method="POST" style="display:inline;" onsubmit="return confirm('삭제?')"><input type="hidden" name="action" value="delete_rule"><input type="hidden" name="rule_id" value="<?= $r['rule_id'] ?>"><button type="submit" class="btn btn-sm" style="color:var(--accent);font-size:var(--fs-xs);">🗑️</button></form></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<!-- 새 정책 추가 -->
<div class="card">
    <div class="card-header"><h3>➕ 새 정책 항목 추가</h3></div>
    <form method="POST" style="display:flex;gap:0.75rem;align-items:end;flex-wrap:wrap;padding:0.5rem 0;">
        <input type="hidden" name="action" value="add_rule">
        <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">키</label><input type="text" name="rule_key" required placeholder="예: new_policy_key" style="font-size:var(--fs-sm);width:10rem;"></div>
        <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">값</label><input type="text" name="rule_value" required placeholder="값" style="font-size:var(--fs-sm);width:8rem;"></div>
        <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">설명</label><input type="text" name="description" placeholder="설명" style="font-size:var(--fs-sm);width:14rem;"></div>
        <button type="submit" class="btn btn-primary">추가</button>
    </form>
</div>
<?php require_once __DIR__.'/../includes/footer.php'; ?>
