<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

function build_content_redirect_target($returnQuery, $extraParams)
{
    $returnQuery = trim((string)$returnQuery);
    $returnQuery = preg_replace('/^content\.php\??/i', '', $returnQuery);
    $base = '/admin/content/list.php';
    $query = $returnQuery !== '' ? $returnQuery . '&' : '';
    return $base . '?' . $query . http_build_query($extraParams);
}

$contentId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$returnQuery = isset($_GET['return_query']) ? (string)$_GET['return_query'] : '';
if ($contentId <= 0) {
    redirect(build_content_redirect_target($returnQuery, array('static_status' => 'missing')));
}

try {
    $content = find_content_by_id($contentId);
    if (!$content) {
        redirect(build_content_redirect_target($returnQuery, array('static_status' => 'missing')));
    }

    $title = isset($content['title']) ? (string)$content['title'] : '';
    publish_content_static($contentId);
    redirect(build_content_redirect_target($returnQuery, array('static_status' => 'success', 'static_title' => $title)));
} catch (Exception $e) {
    redirect(build_content_redirect_target($returnQuery, array('static_status' => 'error')));
}
