<?php
// pages/api_theme.php — 테마 설정 API (AJAX)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
requireLogin();

header('Content-Type: application/json');

$user = currentUser();
$db = (new Database())->getConnection();

// 테이블 자동 생성 (setup.php 스키마와 동일)
$db->exec("CREATE TABLE IF NOT EXISTS user_theme (
    theme_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL UNIQUE,
    accent_color VARCHAR(20) DEFAULT '#E53935', icon_color VARCHAR(20) DEFAULT '#E53935',
    glass_bg VARCHAR(50) DEFAULT 'rgba(12,12,16,0.75)', card_bg_color VARCHAR(20) DEFAULT '#0C0C10',
    text_color VARCHAR(20) DEFAULT '#EAEAEA', sidebar_bg VARCHAR(50) DEFAULT 'rgba(10,10,14,0.82)',
    form_line_color VARCHAR(20) DEFAULT '#333338', form_placeholder VARCHAR(20) DEFAULT '#555560',
    video_opacity DECIMAL(3,2) DEFAULT 0.65, video_url VARCHAR(500) DEFAULT '',
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $db->prepare("SELECT accent_color, icon_color, glass_bg, card_bg_color, text_color, sidebar_bg, form_line_color, form_placeholder, video_opacity, video_url FROM user_theme WHERE user_id = ?");
    $stmt->execute([$user['user_id']]);
    $theme = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$theme) {
        $theme = [
            'accent_color'      => '#E53935',
            'icon_color'        => '#E53935',
            'glass_bg'          => 'rgba(12,12,16,0.75)',
            'card_bg_color'     => '#0C0C10',
            'text_color'        => '#EAEAEA',
            'sidebar_bg'        => 'rgba(10,10,14,0.82)',
            'form_line_color'   => '#333338',
            'form_placeholder'  => '#555560',
            'video_opacity'     => 0.65,
            'video_url'         => ''
        ];
    }
    echo json_encode(['ok' => true, 'theme' => $theme]);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $accent   = $data['accent_color']      ?? '#E53935';
    $glassBg  = $data['glass_bg']          ?? 'rgba(12,12,16,0.75)';
    $cardBg   = $data['card_bg_color']     ?? '#0C0C10';
    $textCol  = $data['text_color']        ?? '#EAEAEA';
    $sidebarBg= $data['sidebar_bg']        ?? 'rgba(10,10,14,0.82)';
    $formLine = $data['form_line_color']   ?? '#333338';
    $formPH   = $data['form_placeholder']  ?? '#555560';
    $vidOp    = floatval($data['video_opacity'] ?? 0.65);

    // video_url은 JS 테마저장에서 보내지 않음 — 기존값 유지
    $vidUrl = null;
    if (isset($data['video_url'])) {
        $vidUrl = trim($data['video_url']);
        if (strlen($vidUrl) > 500) $vidUrl = '';
    } else {
        // 기존 DB값 보존
        $existStmt = $db->prepare("SELECT video_url FROM user_theme WHERE user_id=?");
        $existStmt->execute([$user['user_id']]);
        $vidUrl = $existStmt->fetchColumn() ?: '';
    }

    if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $accent)) $accent = '#E53935';
    if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $cardBg)) $cardBg = '#0C0C10';
    if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $textCol)) $textCol = '#EAEAEA';
    if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $formLine)) $formLine = '#333338';
    if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $formPH)) $formPH = '#555560';
    if ($vidOp < 0 || $vidOp > 1) $vidOp = 0.65;

    $iconCol = $data['icon_color'] ?? '';
    if (!preg_match('/^#[0-9a-fA-F]{6}$/', $iconCol)) $iconCol = '';

    $stmt = $db->prepare("INSERT INTO user_theme (user_id, accent_color, icon_color, glass_bg, card_bg_color, text_color, sidebar_bg, form_line_color, form_placeholder, video_opacity, video_url)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE accent_color=VALUES(accent_color), icon_color=VALUES(icon_color), glass_bg=VALUES(glass_bg),
            card_bg_color=VALUES(card_bg_color), text_color=VALUES(text_color), sidebar_bg=VALUES(sidebar_bg),
            form_line_color=VALUES(form_line_color), form_placeholder=VALUES(form_placeholder), video_opacity=VALUES(video_opacity), video_url=VALUES(video_url)");
    $stmt->execute([$user['user_id'], $accent, $iconCol, $glassBg, $cardBg, $textCol, $sidebarBg, $formLine, $formPH, $vidOp, $vidUrl]);

    echo json_encode(['ok' => true]);
}
