<?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';

if (!isAdminSetupRequired()) {
    header('Location: ../login.php');
    exit;
}

$message = '';
$status = 'error';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $username = trim((string)($_POST['username'] ?? ''));
    $displayName = trim((string)($_POST['display_name'] ?? ''));
    $password = (string)($_POST['password'] ?? '');
    $passwordConfirm = (string)($_POST['password_confirm'] ?? '');

    if (!preg_match('/^[a-zA-Z0-9_.-]{3,100}$/', $username)) {
        $message = '아이디는 3자 이상 영문, 숫자, 점, 밑줄, 하이픈만 사용할 수 있습니다.';
    } elseif (strlen($password) < 8) {
        $message = '비밀번호는 8자 이상으로 입력하세요.';
    } elseif ($password !== $passwordConfirm) {
        $message = '비밀번호 확인이 일치하지 않습니다.';
    } else {
        try {
            $pdo = getDBConnection();
            $stmt = $pdo->prepare("
                INSERT INTO admin_users (username, password_hash, display_name, role, is_active)
                VALUES (:username, :password_hash, :display_name, 'admin', 1)
            ");
            $stmt->execute([
                ':username' => $username,
                ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                ':display_name' => $displayName === '' ? null : $displayName,
            ]);
            logAdminAction('admin_setup_created', 'Initial admin user created: ' . $username, (int)$pdo->lastInsertId());
            header('Location: ../login.php?message=' . urlencode('관리자 계정이 생성되었습니다. 로그인하세요.'));
            exit;
        } catch (Exception $e) {
            $message = '관리자 계정 생성 중 오류가 발생했습니다.';
        }
    }
}

renderHeader('초기 관리자 생성', 'setup_admin', ['show_player' => false]);
?>
<div class="auth-page">
    <section class="auth-card">
        <div class="auth-heading">
            <i class="fa-solid fa-user-shield"></i>
            <h1>초기 관리자 생성</h1>
            <p>활성 관리자 계정이 없을 때만 한 번 열리는 화면입니다.</p>
        </div>
        <?php if ($message !== ''): ?>
            <div class="alert-box alert-danger"><div class="alert-content"><p><?php echo h($message); ?></p></div></div>
        <?php endif; ?>
        <form method="POST" class="auth-form">
            <?php echo csrfInput(); ?>
            <label>아이디<input type="text" name="username" required autocomplete="username"></label>
            <label>표시 이름<input type="text" name="display_name" autocomplete="name"></label>
            <label>비밀번호<input type="password" name="password" required autocomplete="new-password"></label>
            <label>비밀번호 확인<input type="password" name="password_confirm" required autocomplete="new-password"></label>
            <button type="submit" class="btn btn-primary auth-submit">관리자 계정 생성</button>
        </form>
    </section>
</div>
<?php renderFooter(); ?>
