<?php
// pages/theme_settings.php — 테마 설정 (그룹핑 + 비디오 업로드)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
if (session_status()===PHP_SESSION_NONE) session_start();
if (!isLoggedIn()) { header('Location: '.BASE_URL.''); exit; }
$db = (new Database())->getConnection();
$userId = $_SESSION['user_id'];
$myRole = $_SESSION['user_role'] ?? '';
$isSysadmin = in_array($myRole, ['sysadmin', 'ceo']);

$db->exec("CREATE TABLE IF NOT EXISTS user_images (
    img_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, filename VARCHAR(255),
    sort_order INT DEFAULT 0, uploaded_at DATETIME DEFAULT CURRENT_TIMESTAMP, INDEX idx_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

$_uploadMsg = '';

// 이미지/비디오 업로드 (개인 슬라이드)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['slide_images'])) {
    $files = $_FILES['slide_images'];
    $uploaded = 0; $errors = [];
    $hasFile = false;
    for ($i = 0; $i < count($files['name']); $i++) {
        if ($files['error'][$i] === 0 && $files['size'][$i] > 0) { $hasFile = true; break; }
    }
    if (!$hasFile) { $_uploadMsg = 'no_file'; }
    else {
        // 현재 등록된 이미지 개수 확인
        $currentCount = $db->prepare("SELECT COUNT(*) FROM user_images WHERE user_id=?");
        $currentCount->execute([$userId]);
        $currentImgCount = (int)$currentCount->fetchColumn();
        $newFileCount = 0;
        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] === 0 && $files['size'][$i] > 0) $newFileCount++;
        }
        if ($currentImgCount + $newFileCount > 10) {
            $_uploadMsg = 'max_limit';
            header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
        }
        $uploadDir = __DIR__ . '/../assets/theme/' . $userId . '/slides/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        $maxSort = $db->prepare("SELECT COALESCE(MAX(sort_order),0) FROM user_images WHERE user_id=?");
        $maxSort->execute([$userId]); $sort = (int)$maxSort->fetchColumn();
        $imgExts = ['jpg','jpeg','png','gif','webp'];
        $vidExts = ['mp4','webm'];
        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] !== 0 || $files['size'][$i] === 0) continue;
            $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
            $isImg = in_array($ext, $imgExts); $isVid = in_array($ext, $vidExts);
            if (!$isImg && !$isVid) { $errors[] = $files['name'][$i].' — 지원하지 않는 형식'; continue; }
            if ($isImg && $files['size'][$i] > 1*1024*1024) { $errors[] = $files['name'][$i].' — 이미지 1MB 초과'; continue; }
            if ($isVid && $files['size'][$i] > 3*1024*1024) { $errors[] = $files['name'][$i].' — 동영상 3MB 초과'; continue; }
            $fname = uniqid('slide_') . '.' . $ext;
            if (move_uploaded_file($files['tmp_name'][$i], $uploadDir . $fname)) {
                $sort++; $db->prepare("INSERT INTO user_images (user_id,filename,sort_order) VALUES(?,?,?)")->execute([$userId,$fname,$sort]); $uploaded++;
            }
        }
        $_uploadMsg = $uploaded > 0 ? 'uploaded' : 'fail';
        if ($errors) $_uploadMsg .= '&err=' . urlencode(implode(', ', $errors));
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
}

// 배경 동영상 업로드 (개인용 — theme/userId/)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['bg_video_file']) && $_FILES['bg_video_file']['size'] > 0) {
    $vf = $_FILES['bg_video_file'];
    if ($vf['size'] > 3*1024*1024) { $_uploadMsg = 'video_too_large'; }
    else {
        $ext = strtolower(pathinfo($vf['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['mp4','webm'])) { $_uploadMsg = 'video_bad_fmt'; }
        else {
            $vDir = __DIR__ . '/../assets/theme/' . $userId . '/';
            if (!is_dir($vDir)) mkdir($vDir, 0755, true);
            // 기존 파일 삭제
            foreach (glob($vDir . 'bg_video.*') as $old) @unlink($old);
            $vName = 'bg_video.' . $ext;
            if (move_uploaded_file($vf['tmp_name'], $vDir . $vName)) {
                $vUrl = BASE_URL.'assets/theme/' . $userId . '/' . $vName;
                $db->prepare("INSERT INTO user_theme (user_id, video_url) VALUES(?,?) ON DUPLICATE KEY UPDATE video_url=?")->execute([$userId, $vUrl, $vUrl]);
                $_uploadMsg = 'video_ok';
            } else { $_uploadMsg = 'video_fail'; }
        }
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
}

// 사이드바 로고 업로드 (sysadmin 전용)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSysadmin && isset($_FILES['logo_file']) && $_FILES['logo_file']['size'] > 0) {
    $lf = $_FILES['logo_file'];
    if ($lf['size'] > 1*1024*1024) { $_uploadMsg = 'logo_large'; }
    else {
        $ext = strtolower(pathinfo($lf['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg','svg'])) { $_uploadMsg = 'logo_fmt'; }
        else {
            foreach (glob(__DIR__ . '/../assets/logo.*') as $old) @unlink($old);
            $dest = __DIR__ . '/../assets/logo.' . $ext;
            if (move_uploaded_file($lf['tmp_name'], $dest)) { $_uploadMsg = 'logo_ok'; }
            else { $_uploadMsg = 'logo_fail'; }
        }
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
}
// 로그인 화면 로고 업로드 (sysadmin 전용)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSysadmin && isset($_FILES['logo_login_file']) && $_FILES['logo_login_file']['size'] > 0) {
    $lf = $_FILES['logo_login_file'];
    if ($lf['size'] > 1*1024*1024) { $_uploadMsg = 'logo_login_large'; }
    else {
        $ext = strtolower(pathinfo($lf['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg','svg'])) { $_uploadMsg = 'logo_login_fmt'; }
        else {
            foreach (glob(__DIR__ . '/../assets/logo_login.*') as $old) @unlink($old);
            $dest = __DIR__ . '/../assets/logo_login.' . $ext;
            if (move_uploaded_file($lf['tmp_name'], $dest)) { $_uploadMsg = 'logo_login_ok'; }
            else { $_uploadMsg = 'logo_login_fail'; }
        }
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
}

// 파비콘 업로드 (sysadmin 전용)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSysadmin && isset($_FILES['favicon_file']) && $_FILES['favicon_file']['size'] > 0) {
    $ff = $_FILES['favicon_file'];
    if ($ff['size'] > 512*1024) { $_uploadMsg = 'favicon_large'; }
    else {
        $ext = strtolower(pathinfo($ff['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','ico'])) { $_uploadMsg = 'favicon_fmt'; }
        else {
            foreach (glob(__DIR__ . '/../assets/favicon.*') as $old) @unlink($old);
            $dest = __DIR__ . '/../assets/favicon.' . $ext;
            if (move_uploaded_file($ff['tmp_name'], $dest)) { $_uploadMsg = 'favicon_ok'; }
            else { $_uploadMsg = 'favicon_fail'; }
        }
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
}

// 로그인 배경 동영상 업로드 (sysadmin 전용)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSysadmin && isset($_FILES['login_video_file']) && $_FILES['login_video_file']['size'] > 0) {
    $vf = $_FILES['login_video_file'];
    if ($vf['size'] > 3*1024*1024) { $_uploadMsg = 'login_video_large'; }
    else {
        $ext = strtolower(pathinfo($vf['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['mp4','webm'])) { $_uploadMsg = 'login_video_fmt'; }
        else {
            $dest = __DIR__ . '/../assets/login_bg.' . $ext;
            // 기존 login_bg 파일 삭제
            foreach (glob(__DIR__ . '/../assets/login_bg.*') as $old) @unlink($old);
            if (move_uploaded_file($vf['tmp_name'], $dest)) {
                $_uploadMsg = 'login_video_ok';
            } else { $_uploadMsg = 'login_video_fail'; }
        }
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=" . $_uploadMsg); exit;
}

// 이미지 삭제
if (isset($_GET['delete_img'])) {
    $imgId = (int)$_GET['delete_img'];
    $stmt = $db->prepare("SELECT filename FROM user_images WHERE img_id=? AND user_id=?"); $stmt->execute([$imgId, $userId]); $img = $stmt->fetch();
    if ($img) {
        $path = __DIR__ . '/../assets/theme/' . $userId . '/slides/' . $img['filename'];
        if (file_exists($path)) unlink($path);
        $db->prepare("DELETE FROM user_images WHERE img_id=?")->execute([$imgId]);
    }
    header("Location: ".BASE_URL."pages/theme_settings.php?msg=deleted"); exit;
}

require_once __DIR__ . '/../includes/header.php';
$user = currentUser();
$imgStmt = $db->prepare("SELECT * FROM user_images WHERE user_id=? ORDER BY sort_order"); $imgStmt->execute([$userId]);
$userImages = $imgStmt->fetchAll(PDO::FETCH_ASSOC);

$msgMap = ['uploaded'=>'✓ 파일이 업로드되었습니다.','deleted'=>'✓ 삭제되었습니다.','no_file'=>'⚠ 파일을 선택해주세요.',
    'max_limit'=>'⚠ 미디어 이미지는 최대 10개까지 등록 가능합니다.',
    'fail'=>'⚠ 업로드 실패 (이미지 3MB 이하)','video_ok'=>'✓ 배경 동영상이 설정되었습니다.',
    'video_too_large'=>'⚠ 동영상 3MB 초과','video_bad_fmt'=>'⚠ MP4/WebM만 지원','video_fail'=>'⚠ 업로드 실패',
    'login_video_ok'=>'✓ 로그인 배경이 설정되었습니다.','login_video_large'=>'⚠ 동영상 3MB 초과','login_video_fmt'=>'⚠ MP4/WebM만 지원','login_video_fail'=>'⚠ 업로드 실패',
    'logo_ok'=>'✓ 사이드바 로고가 변경되었습니다.','logo_large'=>'⚠ 로고 이미지 1MB 초과','logo_fmt'=>'⚠ PNG/JPG/SVG만 지원','logo_fail'=>'⚠ 로고 업로드 실패',
    'logo_login_ok'=>'✓ 로그인 화면 로고가 변경되었습니다.','logo_login_large'=>'⚠ 로고 이미지 1MB 초과','logo_login_fmt'=>'⚠ PNG/JPG/SVG만 지원','logo_login_fail'=>'⚠ 로고 업로드 실패',
    'favicon_ok'=>'✓ 파비콘이 변경되었습니다.','favicon_large'=>'⚠ 파비콘 512KB 초과','favicon_fmt'=>'⚠ PNG/ICO만 지원','favicon_fail'=>'⚠ 파비콘 업로드 실패',
    'profile_ok'=>'✓ 프로필 이미지가 변경되었습니다.','profile_large'=>'⚠ 프로필 이미지 3MB 초과','profile_fmt'=>'⚠ JPG/PNG/GIF만 지원','profile_fail'=>'⚠ 업로드 실패',
    'login_opacity_ok'=>'✓ 로그인 카드 투명도가 변경되었습니다.',
    'login_dim_ok'=>'✓ 로그인 영상 밝기가 변경되었습니다.'];
?>

<div class="page-header" style="display:flex;justify-content:space-between;align-items:center;"><h2>🎨 테마 설정</h2><button onclick="resetTheme();saveAllTheme();" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.3rem 0.75rem;">🔄 기본 테마로 초기화</button></div>

<?php $m = $_GET['msg'] ?? ''; if ($m && isset($msgMap[explode('&',$m)[0]])): ?>
<div class="alert <?= str_starts_with($m,'⚠')||str_contains($m,'fail')||str_contains($m,'large')?'alert-warning':'alert-success' ?>" style="margin-bottom:1rem;"><?= $msgMap[explode('&',$m)[0]] ?><?php if(isset($_GET['err'])):?><br><span style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($_GET['err']) ?></span><?php endif; ?></div>
<?php endif; ?>

<!-- ═══ 로고 설정 (시스템관리자 전용) ═══ -->
<?php if ($isSysadmin): ?>
<div class="card" style="margin-bottom:1rem;border:1px solid rgba(var(--accent-rgb),0.15);">
    <div class="card-header" style="background:rgba(var(--accent-rgb),0.06);"><h3>🏷️ 로고 & 파비콘 설정</h3></div>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1.5rem;">
        <!-- 사이드바 로고 (로그인 후) -->
        <div>
            <div style="font-size:var(--fs-xs);font-weight:700;color:var(--text-secondary);margin-bottom:0.5rem;">📺 사이드바 로고 (로그인 후)</div>
            <p style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.5rem;">PNG/JPG/SVG · 1MB 이하</p>
            <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                <label class="file-upload-btn" style="font-size:var(--fs-xs);">🏷️ 파일 선택
                    <input type="file" name="logo_file" accept="image/png,image/jpeg,image/svg+xml" style="display:none;" onchange="document.getElementById('logoFileName').textContent=this.files[0]?.name||''">
                </label>
                <span id="logoFileName" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
                <button type="submit" class="btn btn-primary" style="font-size:var(--fs-xs);">업로드</button>
            </form>
            <?php $logoFile = glob(__DIR__ . '/../assets/logo.*');
            if ($logoFile): ?>
            <div style="margin-top:0.5rem;display:flex;align-items:center;gap:0.75rem;">
                <img src="<?=BASE_URL?>assets/<?= basename($logoFile[0]) ?>?v=<?= filemtime($logoFile[0]) ?>" style="max-height:2rem;max-width:8rem;object-fit:contain;" alt="사이드바 로고">
                <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">현재: <?= basename($logoFile[0]) ?></span>
            </div>
            <?php endif; ?>
        </div>
        <!-- 로그인 화면 로고 -->
        <div>
            <div style="font-size:var(--fs-xs);font-weight:700;color:var(--text-secondary);margin-bottom:0.5rem;">🔐 로그인 화면 로고</div>
            <p style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.5rem;">PNG/JPG/SVG · 1MB 이하</p>
            <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                <label class="file-upload-btn" style="font-size:var(--fs-xs);">🔐 파일 선택
                    <input type="file" name="logo_login_file" accept="image/png,image/jpeg,image/svg+xml" style="display:none;" onchange="document.getElementById('logoLoginFileName').textContent=this.files[0]?.name||''">
                </label>
                <span id="logoLoginFileName" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
                <button type="submit" class="btn btn-primary" style="font-size:var(--fs-xs);">업로드</button>
            </form>
            <?php $logoLoginFile = glob(__DIR__ . '/../assets/logo_login.*');
            if ($logoLoginFile): ?>
            <div style="margin-top:0.5rem;display:flex;align-items:center;gap:0.75rem;">
                <img src="<?=BASE_URL?>assets/<?= basename($logoLoginFile[0]) ?>?v=<?= filemtime($logoLoginFile[0]) ?>" style="max-height:2rem;max-width:8rem;object-fit:contain;" alt="로그인 로고">
                <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">현재: <?= basename($logoLoginFile[0]) ?></span>
            </div>
            <?php else: ?>
            <div style="margin-top:0.5rem;font-size:var(--fs-xs);color:var(--text-tertiary);">미설정 (사이드바 로고 또는 기본 텍스트 사용)</div>
            <?php endif; ?>
        </div>
        <!-- 파비콘 -->
        <div>
            <div style="font-size:var(--fs-xs);font-weight:700;color:var(--text-secondary);margin-bottom:0.5rem;">⭐ 파비콘 (브라우저 탭 아이콘)</div>
            <p style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.5rem;">PNG/ICO · 512KB 이하 · 32×32px 권장</p>
            <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                <label class="file-upload-btn" style="font-size:var(--fs-xs);">⭐ 파일 선택
                    <input type="file" name="favicon_file" accept="image/png,image/x-icon,image/vnd.microsoft.icon" style="display:none;" onchange="document.getElementById('faviconFileName').textContent=this.files[0]?.name||''">
                </label>
                <span id="faviconFileName" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
                <button type="submit" class="btn btn-primary" style="font-size:var(--fs-xs);">업로드</button>
            </form>
            <?php $faviconFile = glob(__DIR__ . '/../assets/favicon.*');
            $hasFavicon = false;
            foreach ($faviconFile as $fv) {
                $fvExt = strtolower(pathinfo($fv, PATHINFO_EXTENSION));
                if (in_array($fvExt, ['png','ico'])) { $hasFavicon = true; break; }
            }
            if ($hasFavicon): ?>
            <div style="margin-top:0.5rem;display:flex;align-items:center;gap:0.75rem;">
                <?php if ($fvExt === 'png'): ?>
                <img src="<?=BASE_URL?>assets/<?= basename($fv) ?>?v=<?= filemtime($fv) ?>" style="width:32px;height:32px;object-fit:contain;image-rendering:pixelated;border:1px solid var(--border);border-radius:4px;padding:2px;" alt="파비콘">
                <?php else: ?>
                <div style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;border:1px solid var(--border);border-radius:4px;font-size:var(--fs-xs);">ICO</div>
                <?php endif; ?>
                <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">현재: <?= basename($fv) ?></span>
            </div>
            <?php else: ?>
            <div style="margin-top:0.5rem;font-size:var(--fs-xs);color:var(--text-tertiary);">미설정 (기본 파비콘 사용)</div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>


<!-- ═══ 1. 컬러 설정 ═══ -->
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>🎨 컬러 설정</h3></div>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(13rem,1fr));gap:1.25rem;padding:0.5rem 0;">
        <div class="theme-item"><label>포인트 컬러</label><div class="theme-picker"><div class="theme-preview" id="accentPreview"></div><input type="color" id="accentCustom"><code id="accentHex"></code></div></div>
        <div class="theme-item"><label>카드 배경</label><div class="theme-picker"><div class="theme-preview" id="cardBgPreview"></div><input type="color" id="cardBgCustom"><code id="cardBgHex"></code></div></div>
        <div class="theme-item"><label>텍스트 색상</label><div class="theme-picker"><div class="theme-preview" id="textColorPreview"></div><input type="color" id="textColorCustom"><code id="textColorHex"></code></div></div>
        <div class="theme-item"><label>사이드바 배경</label><div class="theme-picker"><div class="theme-preview" id="sidebarBgPreview"></div><input type="color" id="sidebarBgCustom"><code id="sidebarBgHex"></code></div></div>
        <div class="theme-item"><label>폼 라인</label><div class="theme-picker"><div class="theme-preview" id="formLinePreview"></div><input type="color" id="formLineCustom"><code id="formLineHex"></code></div></div>
        <div class="theme-item"><label>플레이스홀더</label><div class="theme-picker"><div class="theme-preview" id="placeholderPreview"></div><input type="color" id="placeholderCustom"><code id="placeholderHex"></code></div></div>
    </div>
</div>

<!-- ═══ 2. 투명도 & 밝기 ═══ -->
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>🔲 투명도 & 밝기</h3></div>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(14rem,1fr));gap:1.25rem;padding:0.5rem 0;">
        <div class="theme-item"><label>카드 투명도</label><input type="range" id="glassBgOpacity" min="0" max="1" step="0.01" value="0.75" class="theme-range"><div class="theme-range-labels"><span>투명</span><span id="glassBgLabel">0.75</span><span>불투명</span></div><span id="glassBgSaveMsg" style="font-size:var(--fs-xs);color:var(--success);opacity:0;transition:opacity 0.3s;"></span></div>
        <div class="theme-item"><label>사이드바 투명도</label><input type="range" id="sidebarOpacity" min="0" max="1" step="0.01" value="0.82" class="theme-range"><div class="theme-range-labels"><span>투명</span><span id="sidebarOpLabel">0.82</span><span>불투명</span></div><span id="sidebarOpSaveMsg" style="font-size:var(--fs-xs);color:var(--success);opacity:0;transition:opacity 0.3s;"></span></div>
    </div>
</div>

<!-- ═══ 3. 배경 동영상 설정 ═══ -->
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>🎬 배경 동영상 설정</h3></div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;">
        <!-- 로그인 후 -->
        <div>
            <div style="font-size:var(--fs-xs);font-weight:700;color:var(--text-secondary);margin-bottom:0.5rem;">📺 로그인 후 (개인 배경)</div>
            <div class="theme-item" style="margin-bottom:0.5rem;"><label>영상 밝기</label><input type="range" id="videoDim" min="0" max="1" step="0.01" value="0.65" class="theme-range"><div class="theme-range-labels"><span>밝음</span><span id="videoDimLabel">0.65</span><span>어두움</span></div><span id="videoDimSaveMsg" style="font-size:var(--fs-xs);color:var(--success);opacity:0;transition:opacity 0.3s;"></span></div>
            <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                <label class="file-upload-btn" style="font-size:var(--fs-xs);">🎬 동영상 선택
                    <input type="file" name="bg_video_file" accept="video/mp4,video/webm" style="display:none;" onchange="document.getElementById('vfName').textContent=this.files[0]?.name||''">
                </label>
                <span id="vfName" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
                <button type="submit" class="btn btn-primary" style="font-size:var(--fs-xs);">업로드</button>
            </form>
            <?php $curVid = $theme['video_url'] ?? '';
            if ($curVid): ?><div style="margin-top:0.5rem;font-size:var(--fs-xs);color:var(--text-secondary);">현재: <code style="font-size:var(--fs-xs);"><?= htmlspecialchars($curVid) ?></code></div>
            <?php else: ?><div style="margin-top:0.5rem;font-size:var(--fs-xs);color:var(--text-tertiary);">기본 동영상 사용 중 (업로드하면 변경됩니다)</div><?php endif; ?>
        </div>
        <!-- 로그인 전 (시스템관리자) -->
        <div>
            <div style="font-size:var(--fs-xs);font-weight:700;color:var(--text-secondary);margin-bottom:0.5rem;">🔐 로그인 화면 <?= $isSysadmin ? '' : '(관리자 전용)' ?></div>
            <?php if ($isSysadmin): ?>
            <?php
            $curLoginDim = 0.65;
            try { $dimR = $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='login_video_dim'"); if($dimR){$dv=$dimR->fetchColumn();if($dv!==false)$curLoginDim=floatval($dv);} } catch(Exception $e){}
            ?>
            <div style="margin-bottom:0.75rem;">
                <div class="theme-item">
                    <label>로그인 영상 밝기</label>
                    <input type="range" id="loginVideoDimRange" min="0" max="1" step="0.01" value="<?= $curLoginDim ?>" class="theme-range">
                    <div class="theme-range-labels"><span>밝음</span><span id="loginVideoDimLabel"><?= number_format($curLoginDim, 2) ?></span><span>어두움</span></div>
                    <span id="loginDimSaveMsg" style="font-size:var(--fs-xs);color:var(--success);opacity:0;transition:opacity 0.3s;"></span>
                </div>
            </div>
            <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                <label class="file-upload-btn" style="font-size:var(--fs-xs);">🔐 로그인 배경 선택
                    <input type="file" name="login_video_file" accept="video/mp4,video/webm" style="display:none;" onchange="document.getElementById('lvfName').textContent=this.files[0]?.name||''">
                </label>
                <span id="lvfName" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
                <button type="submit" class="btn btn-primary" style="font-size:var(--fs-xs);">업로드</button>
            </form>
            <?php $loginBg = glob(__DIR__ . '/../assets/login_bg.*');
            if ($loginBg): ?><div style="margin-top:0.5rem;font-size:var(--fs-xs);color:var(--text-secondary);">현재: <?= basename($loginBg[0]) ?></div><?php endif; ?>

            <!-- 로그인 카드 투명도 -->
            <?php
            $curOpacity = 0.78;
            try { $opR = $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='login_card_opacity'"); if($opR){$v=$opR->fetchColumn();if($v!==false)$curOpacity=floatval($v);} } catch(Exception $e){}
            ?>
            <div style="margin-top:1rem;padding-top:0.75rem;border-top:1px solid var(--border);">
                <div style="font-size:var(--fs-xs);font-weight:700;color:var(--text-secondary);margin-bottom:0.5rem;">🃏 로그인 카드 투명도</div>
                <div style="display:flex;align-items:center;gap:0.75rem;flex-wrap:wrap;">
                    <input type="range" id="loginCardOpacityRange" min="0" max="1" step="0.01" value="<?= $curOpacity ?>"
                        style="flex:1;min-width:8rem;accent-color:var(--accent);">
                    <span id="opacityVal" style="font-size:var(--fs-sm);font-weight:600;min-width:2.5rem;text-align:center;"><?= $curOpacity ?></span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:2px;">
                    <span>투명 (0)</span><span>불투명 (1)</span>
                </div>
                <span id="loginOpacitySaveMsg" style="font-size:var(--fs-xs);color:var(--success);opacity:0;transition:opacity 0.3s;"></span>
                <div style="margin-top:0.5rem;">
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:4px;">미리보기:</div>
                    <div id="opacityPreview" style="background:rgba(14,14,18,<?= $curOpacity ?>);backdrop-filter:blur(20px);border-radius:8px;padding:0.75rem 1rem;border:1px solid rgba(255,255,255,0.08);">
                        <div style="font-size:var(--fs-xs);color:rgba(255,255,255,0.8);">로그인 카드 샘플</div>
                        <div style="font-size:var(--fs-xs);color:rgba(255,255,255,0.4);margin-top:2px;">투명도: <span id="opacityPreviewVal"><?= $curOpacity ?></span></div>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);padding:1rem 0;">시스템 관리자만 로그인 화면 배경을 변경할 수 있습니다.</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- ═══ 4. 개인 공간 이미지/미디어 ═══ -->
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>🖼️ 개인 공간 미디어</h3></div>
    <div style="padding:0.25rem 0;">
        <p style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.75rem;">홈 프로필 슬라이드에 표시됩니다. JPG/PNG 1MB 이하 · <strong style="color:var(--accent-text);">최대 10개</strong>까지 등록 가능 (현재 <?= count($userImages ?? []) ?>개)</p>
        <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;margin-bottom:1rem;">
            <label class="file-upload-btn">📁 파일 선택
                <input type="file" name="slide_images[]" multiple accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm" style="display:none;" onchange="document.getElementById('fileCount').textContent=this.files.length+'개 선택됨'">
            </label>
            <span id="fileCount" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
            <button type="submit" class="btn btn-primary" style="font-size:var(--fs-sm);">업로드</button>
        </form>
        <?php if ($userImages): ?>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(8rem,1fr));gap:0.75rem;">
            <?php foreach ($userImages as $img):
                $ext = strtolower(pathinfo($img['filename'], PATHINFO_EXTENSION));
                $isVid = in_array($ext, ['mp4','webm']);
            ?>
            <div style="position:relative;border-radius:var(--radius-sm);overflow:hidden;aspect-ratio:16/10;">
                <?php if ($isVid): ?>
                <video src="<?=BASE_URL?>assets/theme/<?= $userId ?>/slides/<?= htmlspecialchars($img['filename']) ?>" style="width:100%;height:100%;object-fit:cover;" muted></video>
                <div style="position:absolute;bottom:4px;left:4px;background:rgba(0,0,0,0.6);color:#fff;font-size:var(--fs-xs);padding:2px 6px;border-radius:2px;">🎬</div>
                <?php else: ?>
                <img src="<?=BASE_URL?>assets/theme/<?= $userId ?>/slides/<?= htmlspecialchars($img['filename']) ?>" style="width:100%;height:100%;object-fit:cover;">
                <?php endif; ?>
                <a href="?delete_img=<?= $img['img_id'] ?>" onclick="return confirm('삭제?')" style="position:absolute;top:4px;right:4px;background:rgba(0,0,0,0.6);color:#fff;width:1.5rem;height:1.5rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:0.75rem;text-decoration:none;">✕</a>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div style="text-align:center;padding:1.5rem;color:var(--text-tertiary);font-size:var(--fs-sm);">등록된 미디어 없음</div>
        <?php endif; ?>
    </div>
</div>

<!-- 저장 버튼 -->
<div style="display:flex;gap:0.75rem;margin-bottom:1.25rem;align-items:center;">
    <button onclick="saveTheme()" class="btn btn-primary">테마 저장</button>
    <button onclick="resetTheme()" class="btn btn-outline">초기화</button>
    <span id="themeSaveMsg" style="font-size:var(--fs-xs);color:var(--success);opacity:0;transition:opacity 0.3s;"></span>
</div>

<style>
.theme-item label { font-size:var(--fs-sm);font-weight:600;color:var(--text-secondary);display:block;margin-bottom:0.5rem; }
.theme-picker { display:flex;align-items:center;gap:0.75rem; }
.theme-preview { width:2.5rem;height:2.5rem;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.3),inset 0 1px 0 rgba(255,255,255,0.15);transition:all 0.3s;flex-shrink:0;cursor:pointer; }
.theme-picker input[type="color"] { width:0;height:0;padding:0;border:none;opacity:0;position:absolute; }
.theme-preview:hover { box-shadow:0 2px 16px rgba(var(--accent-rgb),0.4);transform:scale(1.08); }
.theme-picker code { font-size:var(--fs-xs);color:var(--text-tertiary);font-family:'SF Mono',Consolas,monospace; }
.theme-range { width:100%;accent-color:var(--accent); }
.theme-range-labels { display:flex;justify-content:space-between;font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:0.25rem; }
.file-upload-btn { display:inline-flex;align-items:center;gap:0.5rem;padding:0.5rem 1rem;border:1px dashed var(--form-line-color);border-radius:var(--radius-sm);cursor:pointer;font-size:var(--fs-sm);color:var(--text-secondary);transition:all 0.2s; }
.file-upload-btn:hover { border-color:var(--accent);color:var(--accent); }
</style>

<script>
(function() {
    const B='<?=BASE_URL?>';
    const root=document.documentElement.style;
    const cs=k=>getComputedStyle(document.documentElement).getPropertyValue(k).trim();
    const items=[
        {id:'accent',preview:'accentPreview',input:'accentCustom',hex:'accentHex',apply:applyAccent,init:cs('--accent')||'#E53935'},
        {id:'cardBg',preview:'cardBgPreview',input:'cardBgCustom',hex:'cardBgHex',apply:applyCardBg,init:rgbToHex(cs('--card-bg-rgb')||'12,12,16')},
        {id:'textColor',preview:'textColorPreview',input:'textColorCustom',hex:'textColorHex',apply:applyTextColor,init:cs('--text-primary')||'#EAEAEA'},
        {id:'sidebarBg',preview:'sidebarBgPreview',input:'sidebarBgCustom',hex:'sidebarBgHex',apply:applySidebarBg,init:rgbaToHex(cs('--sidebar-bg')||'rgba(10,10,14,0.82)')},
        {id:'formLine',preview:'formLinePreview',input:'formLineCustom',hex:'formLineHex',apply:applyFormLine,init:cs('--form-line-color')||'#333338'},
        {id:'placeholder',preview:'placeholderPreview',input:'placeholderCustom',hex:'placeholderHex',apply:applyPlaceholder,init:cs('--form-placeholder')||'#555560'},
    ];
    function rgbToHex(rgb){return '#'+rgb.split(',').map(s=>parseInt(s.trim()).toString(16).padStart(2,'0')).join('');}
    function rgbaToHex(rgba){const m=rgba.match(/(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return m?'#'+[m[1],m[2],m[3]].map(v=>parseInt(v).toString(16).padStart(2,'0')).join(''):'#0A0A0E';}
    // debounce 유틸
    function debounce(fn,ms){let t;return function(...a){clearTimeout(t);t=setTimeout(()=>fn.apply(this,a),ms);};}

    // 공통 테마 자동 저장 (user_theme)
    function showSaveMsg(id,txt){const m=document.getElementById(id);if(!m)return;m.textContent=txt||'✓ 저장됨';m.style.opacity=1;setTimeout(()=>m.style.opacity=0,1500);}
    async function autoSaveTheme(msgId){
        const a=document.getElementById('accentCustom').value,cb=document.getElementById('cardBgCustom').value,tc=document.getElementById('textColorCustom').value,sb=document.getElementById('sidebarBgCustom').value,fl=document.getElementById('formLineCustom').value,fp=document.getElementById('placeholderCustom').value,go=parseFloat(document.getElementById('glassBgOpacity').value),so=parseFloat(document.getElementById('sidebarOpacity').value),vv=parseFloat(document.getElementById('videoDim').value);
        const h2r=h=>[parseInt(h.slice(1,3),16),parseInt(h.slice(3,5),16),parseInt(h.slice(5,7),16)];
        const[cR,cG,cB]=h2r(cb),[sR,sG,sB]=h2r(sb);
        try{const res=await fetch(B+'pages/api_theme.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({accent_color:a,icon_color:a,glass_bg:`rgba(${cR},${cG},${cB},${go})`,card_bg_color:cb,text_color:tc,sidebar_bg:`rgba(${sR},${sG},${sB},${so})`,form_line_color:fl,form_placeholder:fp,video_opacity:vv})});
        const d=await res.json();if(d.ok&&msgId)showSaveMsg(msgId);}catch(e){}
    }
    const debouncedAutoSave=debounce((msgId)=>{autoSaveTheme(msgId);},600);

    items.forEach(item=>{
        const pv=document.getElementById(item.preview),inp=document.getElementById(item.input),hx=document.getElementById(item.hex);
        pv.style.backgroundColor=item.init;inp.value=item.init;hx.textContent=item.init.toUpperCase();
        pv.addEventListener('click',()=>inp.click());
        inp.addEventListener('input',e=>{const h=e.target.value;pv.style.backgroundColor=h;hx.textContent=h.toUpperCase();item.apply(h);debouncedAutoSave('themeSaveMsg');});
    });
    const gBg=cs('--glass-card-bg')||'rgba(12,12,16,0.75)',oM=gBg.match(/([\d.]+)\)$/);
    document.getElementById('glassBgOpacity').value=oM?parseFloat(oM[1]):0.75;document.getElementById('glassBgLabel').textContent=(oM?parseFloat(oM[1]):0.75).toFixed(2);
    const sbOp=parseFloat(cs('--sidebar-opacity'))||0.82;document.getElementById('sidebarOpacity').value=sbOp;document.getElementById('sidebarOpLabel').textContent=sbOp.toFixed(2);
    const vd=parseFloat(cs('--video-dim'))||0.65;document.getElementById('videoDim').value=vd;document.getElementById('videoDimLabel').textContent=vd.toFixed(2);
    document.getElementById('glassBgOpacity').addEventListener('input',e=>{const v=parseFloat(e.target.value);document.getElementById('glassBgLabel').textContent=v.toFixed(2);root.setProperty('--glass-card-bg',`rgba(${cs('--card-bg-rgb')||'12,12,16'},${v})`);});
    document.getElementById('glassBgOpacity').addEventListener('input',debounce(()=>{autoSaveTheme('glassBgSaveMsg');},600));
    document.getElementById('sidebarOpacity').addEventListener('input',e=>{const v=parseFloat(e.target.value);document.getElementById('sidebarOpLabel').textContent=v.toFixed(2);const h=document.getElementById('sidebarBgCustom').value;const r=parseInt(h.slice(1,3),16),g=parseInt(h.slice(3,5),16),b=parseInt(h.slice(5,7),16);root.setProperty('--sidebar-bg',`rgba(${r},${g},${b},${v})`);root.setProperty('--sidebar-opacity',v);});
    document.getElementById('sidebarOpacity').addEventListener('input',debounce(()=>{autoSaveTheme('sidebarOpSaveMsg');},600));
    document.getElementById('videoDim').addEventListener('input',e=>{const v=parseFloat(e.target.value);document.getElementById('videoDimLabel').textContent=v.toFixed(2);root.setProperty('--video-dim',v);});
    document.getElementById('videoDim').addEventListener('input',debounce(()=>{autoSaveTheme('videoDimSaveMsg');},600));

    function applyAccent(hex){const r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);root.setProperty('--accent',hex);root.setProperty('--accent-rgb',`${r},${g},${b}`);root.setProperty('--accent-light',`rgba(${r},${g},${b},0.15)`);root.setProperty('--accent-glow',`rgba(${r},${g},${b},0.3)`);root.setProperty('--accent-text',hex);}
    function applyCardBg(hex){const r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);const op=parseFloat(document.getElementById('glassBgOpacity').value);root.setProperty('--card-bg-rgb',`${r},${g},${b}`);root.setProperty('--glass-card-bg',`rgba(${r},${g},${b},${op})`);}
    function applyTextColor(hex){const r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);root.setProperty('--text-primary',hex);root.setProperty('--text-secondary',`rgba(${r},${g},${b},0.6)`);root.setProperty('--text-tertiary',`rgba(${r},${g},${b},0.38)`);}
    function applySidebarBg(hex){const r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);const op=parseFloat(document.getElementById('sidebarOpacity').value);root.setProperty('--sidebar-bg',`rgba(${r},${g},${b},${op})`);}
    function applyFormLine(hex){root.setProperty('--form-line-color',hex);}
    function applyPlaceholder(hex){root.setProperty('--form-placeholder',hex);}

    // 테마 저장 (수동 버튼용)
    window.saveTheme=async function(){
        await autoSaveTheme('themeSaveMsg');
    };

    // 로그인 영상 밝기 — debounce 자동 저장
    const dimEl=document.getElementById('loginVideoDimRange');
    if(dimEl){
        const saveDimDebounced=debounce(async function(val){
            const fd=new FormData();fd.append('login_video_dim',val);
            try{const res=await fetch(B+'pages/api_login_settings.php',{method:'POST',body:fd});
            const d=await res.json();if(d.ok)showSaveMsg('loginDimSaveMsg');}catch(e){}
        },500);
        dimEl.addEventListener('input',e=>{document.getElementById('loginVideoDimLabel').textContent=parseFloat(e.target.value).toFixed(2);saveDimDebounced(e.target.value);});
    }

    // 로그인 카드 투명도 — debounce 자동 저장
    const opEl=document.getElementById('loginCardOpacityRange');
    if(opEl){
        const saveOpDebounced=debounce(async function(val){
            const fd=new FormData();fd.append('login_card_opacity',val);
            try{const res=await fetch(B+'pages/api_login_settings.php',{method:'POST',body:fd});
            const d=await res.json();if(d.ok)showSaveMsg('loginOpacitySaveMsg');}catch(e){}
        },500);
        opEl.addEventListener('input',e=>{
            const v=e.target.value;
            document.getElementById('opacityVal').textContent=v;
            document.getElementById('opacityPreview').style.background='rgba(14,14,18,'+v+')';
            document.getElementById('opacityPreviewVal').textContent=v;
            saveOpDebounced(v);
        });
    }

    <?php
    $defAccent = $theme['accent_color'] ?? '#E53935';
    $defCardBg = $theme['card_bg_color'] ?? '#0C0C10';
    $defText = $theme['text_color'] ?? '#EAEAEA';
    $defFormLine = $theme['form_line_color'] ?? '#333338';
    $defPlaceholder = $theme['form_placeholder'] ?? '#555560';
    $defSidebarHex = '#0A0A0E'; $defSidebarOp = 0.82;
    if (preg_match('/rgba?\((\d+),\s*(\d+),\s*(\d+)/', $theme['sidebar_bg'] ?? '', $sbM)) {
        $defSidebarHex = sprintf('#%02X%02X%02X', (int)$sbM[1], (int)$sbM[2], (int)$sbM[3]);
    }
    if (preg_match('/([\d.]+)\)\s*$/', $theme['sidebar_bg'] ?? '', $sbO)) { $defSidebarOp = floatval($sbO[1]); }
    $defGlassOp = $glassOpacity ?? 0.75;
    $defVideoOp = $theme['video_opacity'] ?? 0.65;
    ?>
    window.resetTheme=function(){const d={accent:'<?= $defAccent ?>',cardBg:'<?= $defCardBg ?>',textColor:'<?= $defText ?>',sidebarBg:'<?= $defSidebarHex ?>',formLine:'<?= $defFormLine ?>',placeholder:'<?= $defPlaceholder ?>'};applyAccent(d.accent);applyCardBg(d.cardBg);applyTextColor(d.textColor);applySidebarBg(d.sidebarBg);applyFormLine(d.formLine);applyPlaceholder(d.placeholder);items.forEach((item,i)=>{const vals=[d.accent,d.cardBg,d.textColor,d.sidebarBg,d.formLine,d.placeholder];document.getElementById(item.preview).style.backgroundColor=vals[i];document.getElementById(item.input).value=vals[i];document.getElementById(item.hex).textContent=vals[i].toUpperCase();});document.getElementById('glassBgOpacity').value=<?= $defGlassOp ?>;document.getElementById('glassBgLabel').textContent='<?= $defGlassOp ?>';document.getElementById('sidebarOpacity').value=<?= $defSidebarOp ?>;document.getElementById('sidebarOpLabel').textContent='<?= $defSidebarOp ?>';document.getElementById('videoDim').value=<?= $defVideoOp ?>;document.getElementById('videoDimLabel').textContent='<?= $defVideoOp ?>';};
    window.saveAllTheme=async function(){resetTheme();setTimeout(async()=>{await saveTheme();const m=document.getElementById('themeSaveMsg');m.textContent='✓ 기본 테마로 초기화되었습니다';m.style.opacity=1;setTimeout(()=>m.style.opacity=0,2500);},200);};
})();
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
