<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_post();
require_admin_api();
$config = load_config();
$frameId = (int)($_POST['frame_id'] ?? 0);
if ($frameId < 1) json_response(['ok' => false, 'message' => 'Invalid frame id.'], 422);
if (empty($_FILES['frame_file']['tmp_name'])) json_response(['ok' => false, 'message' => 'No frame file uploaded.'], 422);
$file = $_FILES['frame_file'];
$mime = mime_content_type($file['tmp_name']) ?: '';
$ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
if ($mime !== 'image/png' && $ext !== 'png') json_response(['ok' => false, 'message' => 'Only PNG frame files are allowed.'], 422);
$targetFile = FRAME_DIR . '/frame' . $frameId . '.png';
if (!move_uploaded_file($file['tmp_name'], $targetFile)) json_response(['ok' => false, 'message' => 'Frame upload failed.'], 500);
foreach (($config['frames'] ?? []) as &$frame) {
    if ((int)$frame['id'] === $frameId) $frame['file'] = 'frame' . $frameId . '.png';
}
unset($frame);
save_config($config);
json_response(['ok' => true, 'message' => 'Frame uploaded successfully.']);
