<?php
// blog-maker.php (ENTRY FILE) — keep top-level behavior here
defined('ABSPATH') || exit;

if (!defined('BLOG_MAKER_DIR')) {
    define('BLOG_MAKER_DIR', __DIR__);
}

if (!defined('BLOG_MAKER_URL')) {
    // points to the folder containing blog-maker.php
    define('BLOG_MAKER_URL', plugin_dir_url(__FILE__));
}

require_once BLOG_MAKER_DIR . '/includes/constants.php';
require_once BLOG_MAKER_DIR . '/includes/logging.php';
require_once BLOG_MAKER_DIR . '/includes/limits.php';

require_once BLOG_MAKER_DIR . '/includes/destination-scan.php';
require_once BLOG_MAKER_DIR . '/includes/taxonomy.php';

require_once BLOG_MAKER_DIR . '/includes/importer.php';
require_once BLOG_MAKER_DIR . '/includes/replacements.php';
require_once BLOG_MAKER_DIR . '/includes/media.php';
require_once BLOG_MAKER_DIR . '/includes/beaver-builder.php';
require_once BLOG_MAKER_DIR . '/includes/cleanup.php';

require_once BLOG_MAKER_DIR . '/includes/actions/preview.php';
require_once BLOG_MAKER_DIR . '/includes/actions/submit.php';

require_once BLOG_MAKER_DIR . '/includes/image-library/master-image-library.php';

// 2) Keep the request routing EXACTLY like today (same order, same exits)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['preview'])) {
    blog_maker_preview_action();
    exit;
}

if (isset($_POST['action']) && $_POST['action'] === 'blog-maker') {
    blog_maker_action();
}

add_action('wp_ajax_blog_maker_master_image_search', function () {
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'Forbidden'], 403);
    }

    check_ajax_referer('blog_maker_nonce', 'nonce');

    $q = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : '';
    $results = blog_maker_search_master_images($q, 60);

    wp_send_json_success(['results' => $results]);
});


// 3) Render page (markup + inline scripts can be included as partials)
require BLOG_MAKER_DIR . '/templates/admin-page.php';
