<?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);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}
require_csrf();
$contentId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$returnQuery = isset($_POST['return_query']) ? (string)$_POST['return_query'] : '';
if ($contentId <= 0) {
    redirect(build_content_redirect_target($returnQuery, array('delete_status' => 'missing')));
}

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

    $title = isset($content['title']) ? (string)$content['title'] : '';
    delete_content($contentId);
    log_admin_action('content_delete', '删除内容 ID:' . $contentId . ' 标题:' . $title);
    redirect(build_content_redirect_target($returnQuery, array('delete_status' => 'success', 'deleted_title' => $title)));
} catch (Exception $e) {
    redirect(build_content_redirect_target($returnQuery, array('delete_status' => 'error')));
}
