<?php
/**
 * ONE-TIME IMPORT SCRIPT
 * Recreates the 5 static blog posts (same titles/excerpts/images/dates as the
 * old blog.php + blogdetails.php) as real WordPress posts.
 *
 * HOW TO USE:
 * 1. Upload this file into the WordPress root folder, i.e. next to wp-load.php
 *    (same folder as wp-config.php) — e.g. Globinex/blog/import-posts.php
 * 2. Visit it once in the browser: https://yourdomain.com/Globinex/blog/import-posts.php
 * 3. It will print what it created. Then DELETE this file from the server —
 *    it should never be left publicly accessible after use.
 */

require_once __DIR__ . '/wp-load.php';

if (!current_user_can('manage_options')) {
    // Basic guard: must be logged in as an admin in this browser for this to run.
    wp_die('Please log in to wp-admin in this browser first, then reload this page.');
}

// Path to the main PHP site's images folder (one level up from /blog).
$main_images_dir = dirname(__DIR__) . '/images/';

/**
 * Sideload a local image file into the Media Library and return the attachment ID.
 */
function gx_attach_local_image($path, $post_id, $desc) {
    if (!file_exists($path)) {
        echo "&nbsp;&nbsp;⚠️ Image not found, skipped: " . esc_html($path) . "<br>";
        return 0;
    }
    require_once ABSPATH . 'wp-admin/includes/image.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';

    $filename = basename($path);
    $upload   = wp_upload_bits($filename, null, file_get_contents($path));
    if ($upload['error']) {
        echo "&nbsp;&nbsp;⚠️ Upload failed for $filename: " . esc_html($upload['error']) . "<br>";
        return 0;
    }

    $filetype   = wp_check_filetype($upload['file'], null);
    $attachment = [
        'post_mime_type' => $filetype['type'],
        'post_title'     => $desc,
        'post_content'   => '',
        'post_status'    => 'inherit',
    ];
    $attach_id   = wp_insert_attachment($attachment, $upload['file'], $post_id);
    $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
    wp_update_attachment_metadata($attach_id, $attach_data);
    return $attach_id;
}

// The 5 posts exactly as they appeared in the old static blog.php
$posts = [
    [
        'title'   => 'How to Leverage Market Research for Business Growth',
        'excerpt' => 'Learn how structured market research can identify opportunities, understand customer behavior, and drive strategic business decisions.',
        'image'   => 'blogimg1.png',
        'date'    => '2026-07-21 09:00:00',
        // Full article body, taken from the old blogdetails.php
        'content' => '<p>In today\'s fast-paced business environment, staying ahead of competitors and understanding your customers\' evolving needs is crucial. Market research provides the insights necessary to make informed decisions, reduce risk, and identify growth opportunities. For businesses looking to expand, innovate, or optimize operations, leveraging market research is not just an option—it is a strategic imperative.</p>
<blockquote>Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model search for evolved over sometimes by accident, sometimes on purpose.</blockquote>
<h3>Understanding Market Research</h3>
<p>Market research is the process of gathering, analyzing, and interpreting information about a market, including insights about potential customers, competitors, and industry trends. It encompasses both quantitative research, which focuses on measurable data like surveys and statistical analyses.</p>
<h4>Identifying Growth Opportunities</h4>
<p>A primary benefit of market research is uncovering opportunities for growth. By analyzing market gaps, customer segments, and emerging trends, businesses can identify untapped niches, underserved demographics, or new product innovations. For instance, research might reveal a growing demand for eco-friendly products in a specific region, allowing companies to tailor their offerings and gain a competitive advantage.</p>
<h4>Understanding Customer Needs and Behavior</h4>
<p>Market research helps businesses understand not just who their customers are, but what drives their purchasing decisions. This insight enables organizations to measure customer satisfaction and loyalty, which are essential for long-term growth.</p>
<h4>Mitigating Business Risks</h4>
<p>Investing in new products, entering new markets, or launching marketing campaigns can validate market demand before committing significant resources. Similarly, competitor analysis helps businesses anticipate market shifts and adapt strategies proactively.</p>
<img src="' . $main_images_dir . 'blogimg3.png" alt="Analysis Process Checklist" />
<h3>Continuous Monitoring And Adaptation</h3>
<p>Aenean lorem diam, venenatis nec venenatis id, adipiscing ac massa. Nam vel dui eget justo dictum pretium a rhoncus ipsum. Donec venenatis erat tincidunt nunc suscipit, ut amet bibendum lacus posuere. Sed scelerisque, dolor a pharetra sodales, mi augue consequat sapien, et interdum tellus leo et nunc. Morbi imperdiet ac libero ut imperdiet.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non placerat mi. Etiam non tellus tempor, feugiat pretium convallis lorem, ut omet rhoncus ante mollis a. Integer bibendum interdum sem, eget volutpat purus pulvinar in. Sed tristique augue vitae sagittis porta. Phasellus ullamcorper, dolor a feugiat mollis, lorem sapien elit condimentum odio, ut imperdiet nisl risus sit amet odio.</p>
<blockquote>Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model search for evolved over sometimes by accident, sometimes on purpose.</blockquote>
<p>Aenean lorem diam, venenatis nec venenatis id, adipiscing ac massa. Nam vel dui eget justo dictum pretium a rhoncus ipsum. Donec venenatis erat tincidunt nunc suscipit, ut amet bibendum lacus posuere. Sed scelerisque, dolor a pharetra sodales, mi augue consequat sapien, et interdum tellus leo et nunc. Morbi imperdiet ac libero ut imperdiet.</p>',
    ],
    [
        'title'   => 'The Importance of Consumer Insights in Decision-Making',
        'excerpt' => 'Discover how consumer insights help brands refine products, improve services, and enhance customer experience.',
        'image'   => 'blogimg2.png',
        'date'    => '2026-07-21 09:00:00',
        'content' => '<p>Discover how consumer insights help brands refine products, improve services, and enhance customer experience.</p>',
    ],
    [
        'title'   => 'How Competitive Analysis Shapes Market Strategy',
        'excerpt' => 'Explore methods to monitor competitors, benchmark performance, and identify emerging market trends.',
        'image'   => 'blogimg3.png',
        'date'    => '2026-07-21 09:00:00',
        'content' => '<p>Explore methods to monitor competitors, benchmark performance, and identify emerging market trends.</p>',
    ],
    [
        'title'   => 'Using Quantitative & Qualitative Research Together',
        'excerpt' => 'Understand the balance between qualitative and quantitative research for comprehensive business insights.',
        'image'   => 'blogimg4.png',
        'date'    => '2026-07-21 09:00:00',
        'content' => '<p>Understand the balance between qualitative and quantitative research for comprehensive business insights.</p>',
    ],
    [
        'title'   => 'Maximizing ROI with Data-Driven Strategies',
        'excerpt' => 'Learn how to translate research insights into actionable strategies that drive measurable ROI.',
        'image'   => 'blogimg5.png',
        'date'    => '2026-07-21 09:00:00',
        'content' => '<p>Learn how to translate research insights into actionable strategies that drive measurable ROI.</p>',
    ],
];

echo '<h2>Import log</h2>';

foreach ($posts as $p) {
    // Skip if a post with this exact title already exists (safe to re-run).
    $existing = get_page_by_title($p['title'], OBJECT, 'post');
    if ($existing) {
        echo "Skipped (already exists): " . esc_html($p['title']) . "<br>";
        continue;
    }

    $post_id = wp_insert_post([
        'post_title'   => $p['title'],
        'post_excerpt' => $p['excerpt'],
        'post_content' => $p['content'],
        'post_status'  => 'publish',
        'post_type'    => 'post',
        'post_date'    => $p['date'],
    ]);

    if (is_wp_error($post_id)) {
        echo "❌ Failed: " . esc_html($p['title']) . " — " . esc_html($post_id->get_error_message()) . "<br>";
        continue;
    }

    echo "✅ Created: " . esc_html($p['title']) . " (ID $post_id)<br>";

    $attach_id = gx_attach_local_image($main_images_dir . $p['image'], $post_id, $p['title']);
    if ($attach_id) {
        set_post_thumbnail($post_id, $attach_id);
        echo "&nbsp;&nbsp;🖼️ Featured image set: " . esc_html($p['image']) . "<br>";
    }
}

echo '<hr><strong>Done. Please delete this import-posts.php file from the server now.</strong>';
