<?php

namespace WPAICG\ContentWriter\Ajax\Template;

use WPAICG\ContentWriter\Ajax\AIPKit_Content_Writer_Template_Ajax_Handler;
use WP_Error;

if (!defined('ABSPATH')) {
    exit;
}

/**
* Handles the logic for loading a single template.
*
* @param AIPKit_Content_Writer_Template_Ajax_Handler $handler
* @return void
*/
function ajax_load_template_logic(AIPKit_Content_Writer_Template_Ajax_Handler $handler): void
{
    // Permission check done in caller
    if (!$handler->get_template_manager()) {
        $handler->send_wp_error(new WP_Error('manager_missing', 'Template manager unavailable.'), 500);
        return;
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is checked in the calling handler method.
    $template_id = isset($_POST['template_id']) ? absint($_POST['template_id']) : 0;
    if (empty($template_id)) {
        $handler->send_wp_error(new WP_Error('missing_id', 'Template ID is required.'), 400);
        return;
    }

    $template = $handler->get_template_manager()->get_template($template_id);
    if (is_wp_error($template)) {
        $handler->send_wp_error($template);
    } else {
        wp_send_json_success(['template' => $template]);
    }
}
