<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/layout.php';
require_once dirname(__DIR__) . '/includes/policies.php';

requirePermission('settings_manage');

$definitions = policyPageDefinitions();
$message = trim((string)($_GET['message'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'success'));
$activeType = policyAllowedType($_GET['type'] ?? 'terms');

function policyAdminRedirect($status, $message, $type = 'terms') {
    header('Location: policies.php?status=' . urlencode($status) . '&message=' . urlencode($message) . '&type=' . urlencode(policyAllowedType($type)));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $type = policyAllowedType($_POST['policy_type'] ?? 'terms');
    try {
        policySaveContent($type, $_POST['policy_body'] ?? '');
        writeAuditLog('policy_updated', 'Policy text updated: ' . $type, 'success', 'info', 'policy', null);
        writeAppLog('info', 'policy', 'Policy text updated', ['type' => $type]);
        policyAdminRedirect('success', '정책 문구를 저장했습니다.', $type);
    } catch (Throwable $e) {
        writeAppLog('error', 'policy_error', 'Policy text save failed', [
            'type' => $type,
            'error' => policySafeAdminError($e),
        ]);
        policyAdminRedirect('error', policySafeAdminError($e), $type);
    }
}

renderHeader('정책 문구 관리', 'settings');
?>
<div class="admin-dashboard policy-admin-page">
    <div class="page-title-section">
        <h1 class="page-main-title">정책 문구 관리</h1>
        <p class="page-subtitle">사용자에게 표시할 서비스 이용 안내, 개인정보 안내, 저작권 안내 문구를 관리합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="alert-box <?php echo $status === 'error' ? 'alert-danger' : 'alert-info'; ?>">
            <div class="alert-icon"><i class="fas fa-circle-info"></i></div>
            <div class="alert-content"><p><?php echo h($message); ?></p></div>
        </div>
    <?php endif; ?>

    <div class="policy-admin-layout">
        <aside class="settings-card policy-admin-nav">
            <h2>정책 유형</h2>
            <div class="policy-admin-tabs">
                <?php foreach ($definitions as $type => $policy): ?>
                    <a class="policy-admin-tab <?php echo $activeType === $type ? 'is-active' : ''; ?>" href="policies.php?type=<?php echo h($type); ?>">
                        <i class="<?php echo h($policy['icon']); ?>"></i>
                        <span><?php echo h($policy['short_title']); ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
            <a class="btn btn-secondary btn-sm" href="../policies.php?type=<?php echo h($activeType); ?>"><i class="fa-solid fa-eye"></i> 사용자 화면 보기</a>
        </aside>

        <section class="settings-card policy-editor-card">
            <?php $activePolicy = $definitions[$activeType]; ?>
            <div class="section-heading-row">
                <h2><?php echo h($activePolicy['title']); ?></h2>
                <span class="settings-muted">HTML은 저장하지 않습니다.</span>
            </div>
            <form method="POST" class="settings-form policy-editor-form">
                <?php echo csrfInput(); ?>
                <input type="hidden" name="policy_type" value="<?php echo h($activeType); ?>">
                <label for="policy_body">정책 문구</label>
                <textarea id="policy_body" name="policy_body" rows="18" maxlength="8000" required><?php echo h(policyGetContent($activeType)); ?></textarea>
                <p class="settings-muted">내부 서버 경로나 실제 파일 경로가 포함되면 저장 전에 마스킹됩니다. 문구 자체는 감사 로그에 남기지 않습니다.</p>
                <div class="policy-editor-actions">
                    <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> 저장</button>
                    <a class="btn btn-secondary" href="../policies.php?type=<?php echo h($activeType); ?>"><i class="fa-solid fa-arrow-up-right-from-square"></i> 미리보기</a>
                </div>
            </form>
        </section>
    </div>
</div>
<?php renderFooter(); ?>

