<?php
// File: modules/create-blog-post.php
if ( ! defined('ABSPATH') ) { exit; }

require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/create-blog-post', [
        'methods'  => WP_REST_Server::CREATABLE, // POST
        'callback' => 'myaio_sac_create_blog_post_with_image',
        // keep output unchanged (Unauthorized handled in callback)
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_create_blog_post_with_image(WP_REST_Request $request) {

    // ✅ Consistent auth across all modules (same output)
    $auth = function_exists('myaio_sac_require_api_key_or_401') ? myaio_sac_require_api_key_or_401($request) : null;
    if ($auth !== true) {
        return $auth instanceof WP_REST_Response ? $auth : new WP_REST_Response(['error' => 'Unauthorized'], 401);
    }

    // Support both form-data/query params and JSON body
    $json = $request->get_json_params();
    $get_param = function($key) use ($request, $json) {
        if (is_array($json) && array_key_exists($key, $json)) return $json[$key];
        return $request->get_param($key);
    };

    $title   = sanitize_text_field($get_param('title'));
    $content = wp_kses_post($get_param('content'));
    $status  = sanitize_text_field($get_param('status') ?: 'draft');

    $categories = $get_param('categories') ?: [];
    $tags       = $get_param('tags') ?: [];
    $image_url  = esc_url_raw($get_param('image_url'));

    if (empty($title) || empty($content)) {
        return new WP_REST_Response(['error' => 'Title and content are required.'], 400);
    }

    // Normalize categories
    if (is_string($categories)) {
        $categories = array_filter(array_map('trim', explode(',', $categories)));
    }
    if (!is_array($categories)) {
        $categories = [];
    }
    $categories = array_values(array_filter(array_map('absint', $categories)));

    // Normalize tags
    if (is_string($tags)) {
        $tags = array_filter(array_map('trim', explode(',', $tags)));
    }
    if (!is_array($tags)) {
        $tags = [];
    }
    $tags = array_values(array_filter(array_map('sanitize_text_field', $tags)));

    // Restrict status to safe set (prevents unexpected statuses)
    $allowed_status = ['draft', 'publish', 'pending', 'private'];
    if (!in_array($status, $allowed_status, true)) {
        $status = 'draft';
    }

    // Create post
    $post_id = wp_insert_post([
        'post_title'    => $title,
        'post_content'  => $content,
        'post_status'   => $status,
        'post_type'     => 'post',
        'post_category' => $categories,
        'tags_input'    => $tags,
    ], true);

    if (is_wp_error($post_id) || empty($post_id)) {
        return new WP_REST_Response(['error' => 'Post creation failed.'], 500);
    }

    // Handle featured image if image_url provided
    if (!empty($image_url)) {
        // Allow only http/https
        $scheme = wp_parse_url($image_url, PHP_URL_SCHEME);
        if (!in_array($scheme, ['http', 'https'], true)) {
            return new WP_REST_Response(['error' => 'Image download failed.'], 500);
        }

        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';

        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) {
            return new WP_REST_Response(['error' => 'Image download failed.'], 500);
        }

        $file_array = [
            'name'     => wp_basename($image_url),
            'tmp_name' => $tmp
        ];

        $attachment_id = media_handle_sideload($file_array, $post_id);

        if (is_wp_error($attachment_id)) {
            wp_delete_file($tmp); // ✅ safely remove temp file
            return new WP_REST_Response(['error' => 'Failed to attach image.'], 500);
        }

        set_post_thumbnail($post_id, $attachment_id);
    }

    return rest_ensure_response([
        'success'  => true,
        'post_id'  => $post_id,
        'view_url' => get_permalink($post_id),
        'edit_url' => get_edit_post_link($post_id),
    ]);
}
