<?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/service_status.php';

requirePermission('service_status_manage');

$message = trim((string)($_GET['message'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'success'));

function serviceStatusAdminRedirect($status, $message) {
    header('Location: service_status.php?status=' . urlencode($status) . '&message=' . urlencode($message));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    try {
        $enabled = !empty($_POST['service_maintenance_enabled']) ? '1' : '0';
        $title = trim(maskInternalPathText(ensureUtf8String($_POST['service_maintenance_title'] ?? '')));
        $body = trim(maskInternalPathText(ensureUtf8String($_POST['service_maintenance_message'] ?? '')));
        if ($title === '') $title = '서비스 점검 안내';
        if (function_exists('mb_substr')) {
            $title = mb_substr($title, 0, 160, 'UTF-8');
            $body = mb_substr($body, 0, 3000, 'UTF-8');
        } else {
            $title = substr($title, 0, 160);
            $body = substr($body, 0, 3000);
        }

        setSetting('service_maintenance_enabled', $enabled, 'service_status');
        setSetting('service_maintenance_title', $title, 'service_status');
        setSetting('service_maintenance_message', $body, 'service_status');
        setSetting('service_maintenance_updated_at', date('Y-m-d H:i:s'), 'service_status');
        writeAuditLog($enabled === '1' ? 'service_maintenance_enabled' : 'service_maintenance_disabled', 'Service maintenance notice updated', 'success', 'info', 'service_status');
        if (function_exists('writeAppLog')) {
            writeAppLog('info', 'service_status', 'Service maintenance notice updated', ['enabled' => $enabled === '1']);
        }
        serviceStatusAdminRedirect('success', '점검 안내를 저장했습니다.');
    } catch (Throwable $e) {
        if (function_exists('writeAppLog')) {
            writeAppLog('error', 'service_status_error', 'Service status save failed', ['error' => limitLogText($e->getMessage(), 300)]);
        }
        serviceStatusAdminRedirect('error', '점검 안내 저장 중 오류가 발생했습니다.');
    }
}

$summary = getServiceStatusSummary(true);
$maintenance = $summary['maintenance'];

renderHeader('서비스 상태 관리', 'service_status_admin');
?>
<div class="admin-dashboard service-status-admin-page">
    <div class="page-title-section">
        <h1 class="page-main-title">서비스 상태 관리</h1>
        <p class="page-subtitle">점검 안내를 관리하고 재생 실패, 스캔 오류, 백업, PWA 상태를 요약해서 확인합니다.</p>
    </div>

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

    <section class="service-status-hero status-<?php echo h(serviceStatusClass($summary['overall'])); ?>">
        <div>
            <span class="service-status-kicker">운영 상태 요약</span>
            <h2><?php echo h(serviceStatusLabel($summary['overall'])); ?></h2>
            <p>사용자 화면에는 민감정보 없이 정상 / 점검 중 / 일부 오류만 표시됩니다.</p>
        </div>
        <a class="btn btn-secondary" href="../status.php"><i class="fa-solid fa-eye"></i> 사용자 화면 보기</a>
    </section>

    <section class="settings-card service-maintenance-editor">
        <div class="section-heading-row">
            <h2 class="section-title">점검 안내</h2>
            <span class="service-status-pill status-<?php echo $maintenance['enabled'] ? 'maintenance' : 'ok'; ?>"><?php echo $maintenance['enabled'] ? '표시 중' : '숨김'; ?></span>
        </div>
        <form method="POST" class="settings-form service-maintenance-form">
            <?php echo csrfInput(); ?>
            <label class="check-row"><input type="checkbox" name="service_maintenance_enabled" value="1" <?php echo $maintenance['enabled'] ? 'checked' : ''; ?>> 사용자 화면에 점검 안내 표시</label>
            <div class="form-group">
                <label for="service_maintenance_title">제목</label>
                <input type="text" id="service_maintenance_title" name="service_maintenance_title" maxlength="160" value="<?php echo h($maintenance['title']); ?>">
            </div>
            <div class="form-group">
                <label for="service_maintenance_message">안내 내용</label>
                <textarea id="service_maintenance_message" name="service_maintenance_message" rows="5" placeholder="점검 시간, 영향 범위, 안내 문구를 입력하세요."><?php echo h($maintenance['message']); ?></textarea>
            </div>
            <div class="section-heading-row service-maintenance-footer">
                <p class="settings-muted">HTML은 실행되지 않으며, 내부 경로는 저장 전 마스킹됩니다.</p>
                <button class="btn btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> 저장</button>
            </div>
        </form>
    </section>

    <section class="service-status-grid service-status-admin-grid">
        <?php foreach ($summary['items'] as $item): ?>
            <article class="service-status-card status-<?php echo h(serviceStatusClass($item['status'])); ?>">
                <div class="service-status-card-icon status-<?php echo h(serviceStatusClass($item['status'])); ?>"><i class="fa-solid fa-circle-info"></i></div>
                <div>
                    <span><?php echo h(serviceStatusLabel($item['status'])); ?></span>
                    <h2><?php echo h($item['label']); ?></h2>
                    <p><?php echo h($item['admin_detail']); ?></p>
                </div>
            </article>
        <?php endforeach; ?>
    </section>
</div>
<?php renderFooter(); ?>
