<?php
// =============================================================================
// /api/webview/frames.php — Framed View configuration.
//
// GET   ?action=get           → { layout, slots, use_as_backdrop }
// POST  action=save           → { layout, slots, use_as_backdrop }
// =============================================================================
require_once __DIR__ . '/../_common.php';
require_csrf_unless_get();

list($action, $body) = read_action();

if ($action === 'get' || ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === '')) {
    $layout = (int)(db_one('SELECT value FROM webview_settings WHERE key=?', ['frameview_layout'])['value'] ?? 0);
    $rows = db_all('SELECT slot_index, embedded_url FROM webview_frames
                    WHERE layout = ? ORDER BY slot_index ASC', [$layout]);
    $slots = [];
    foreach ($rows as $r) $slots[(int)$r['slot_index']] = (string)$r['embedded_url'];
    $src = db_one('SELECT value FROM webview_settings WHERE key=?', ['home_backdrop_source']);
    $use_as_backdrop = (($src['value'] ?? 'tmdb') === 'frameview') ? 1 : 0;
    json_response(['layout' => $layout, 'slots' => $slots, 'use_as_backdrop' => $use_as_backdrop]);
}

require_method('POST');
if ($action !== 'save') json_error('unknown action', 400);

$layout = (int)($body['layout'] ?? 0);
if ($layout < 0 || $layout > 5) json_error('layout must be 0..5', 400);
$use_as_backdrop = !empty($body['use_as_backdrop']) ? 1 : 0;
$slots = $body['slots'] ?? [];
if (!is_array($slots)) json_error('slots required', 400);

// Slot URLs end up in iframe src= on the WebView side. The UI sends either
// a fully-qualified http(s):// URL or a panel-relative path (api/webview/...).
// Reject explicit dangerous schemes (javascript:, data:, vbscript:, file:, jar:,
// blob:) so a hand-rolled API call can't plant a stored-XSS in the frame view.
foreach ($slots as $idx => $url) {
    $url = trim((string)$url);
    if ($url === '') continue;
    if (preg_match('#^(javascript|data|vbscript|file|jar|blob)\s*:#i', $url)) {
        json_error('Slot URL uses a disallowed scheme.', 400);
    }
    if (strlen($url) > 1024) {
        json_error('Slot URL is too long (max 1024 characters).', 400);
    }
}

$now = time();
db_exec('INSERT INTO webview_settings (key, value, updated_at) VALUES (?, ?, ?)
         ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at',
        ['frameview_layout', (string)$layout, $now]);
// Home-backdrop source flag: `frameview` routes /auth home_url1 through
// api/webview/frameview.php on the next auth. `tmdb` restores the default.
db_exec('INSERT INTO webview_settings (key, value, updated_at) VALUES (?, ?, ?)
         ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at',
        ['home_backdrop_source', $use_as_backdrop ? 'frameview' : 'tmdb', $now]);

// Replace this layout's slot rows. Simpler than diffing — keeps the table small.
db_exec('DELETE FROM webview_frames WHERE layout = ?', [$layout]);
foreach ($slots as $idx => $url) {
    $idx = (int)$idx;
    $url = trim((string)$url);
    if ($url === '') continue;
    db_exec(
        'INSERT INTO webview_frames (layout, slot_index, embedded_url, scale_mode, sort, updated_at)
         VALUES (?, ?, ?, ?, ?, ?)',
        [$layout, $idx, $url, 'fit', $idx, $now]
    );
}
json_response(['ok' => true]);
