<?php
// pages/api_login_settings.php — 로그인 화면 설정 AJAX API (debounce 자동 저장)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
requireLogin();

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

$user = currentUser();
$myRole = $_SESSION['user_role'] ?? '';
if (!in_array($myRole, ['sysadmin', 'ceo'])) {
    echo json_encode(['ok' => false, 'msg' => '권한 없음']);
    exit;
}

$db = (new Database())->getConnection();
$db->exec("CREATE TABLE IF NOT EXISTS policy_rule (rule_id INT AUTO_INCREMENT PRIMARY KEY, rule_key VARCHAR(50) UNIQUE, rule_value VARCHAR(200), description VARCHAR(200) DEFAULT '', updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");

// 로그인 영상 밝기
if (isset($_POST['login_video_dim'])) {
    $val = max(0, min(1, floatval($_POST['login_video_dim'])));
    $db->prepare("INSERT INTO policy_rule (rule_key, rule_value, description) VALUES('login_video_dim', ?, '로그인 영상 밝기') ON DUPLICATE KEY UPDATE rule_value=VALUES(rule_value)")
       ->execute([$val]);
    echo json_encode(['ok' => true, 'key' => 'login_video_dim', 'value' => $val]);
    exit;
}

// 로그인 카드 투명도
if (isset($_POST['login_card_opacity'])) {
    $val = max(0, min(1, floatval($_POST['login_card_opacity'])));
    $db->prepare("INSERT INTO policy_rule (rule_key, rule_value, description) VALUES('login_card_opacity', ?, '로그인 카드 투명도') ON DUPLICATE KEY UPDATE rule_value=VALUES(rule_value)")
       ->execute([$val]);
    echo json_encode(['ok' => true, 'key' => 'login_card_opacity', 'value' => $val]);
    exit;
}

echo json_encode(['ok' => false, 'msg' => '파라미터 없음']);
