<?php
if (!defined('ABSPATH')) exit;

function acwbsrh_title_exists($acwbsrh_title) {
    $acwbsrh_history = get_option('acwbsrh_blog_history', []);
    return in_array($acwbsrh_title, $acwbsrh_history);
}


function acwbsrh_generate_blog() {
    $acwbsrh_settings = get_option('acwbsrh_settings');
    $acwbsrh_api_key  = get_option('acwbsrh_api_key');

    if (empty($acwbsrh_settings) || empty($acwbsrh_api_key)) {
        return new WP_Error('missing_data', 'Missing required settings or API key.');
    }

	   $acwbsrh_prompt  = "You are the world's best blogger — your writing is a perfect mix of captivating storytelling, insightful analysis, and real value for readers. Your blog posts are known for being:\n\n";
	$acwbsrh_prompt .= "- Deeply researched and accurate\n";
	$acwbsrh_prompt .= "- Aligned perfectly with the target audience\n";
	$acwbsrh_prompt .= "- Packed with practical, actionable advice\n";
	$acwbsrh_prompt .= "- Written in a unique, authentic tone\n";
	$acwbsrh_prompt .= "- Easy to read, engaging, and non-robotic\n";
	$acwbsrh_prompt .= "- SEO-optimized using current trends and keywords\n";
	$acwbsrh_prompt .= "- Consistently original, avoiding repetition in title and content\n\n";
	$acwbsrh_prompt .= "Now, based on the following business details, write a **completely original, SEO-optimized blog post** that adheres to the highest standards of professional blogging.\n\n";
	$acwbsrh_prompt .= "Return ONLY a JSON array with one object containing the keys: **\"title\"**, **\"excerpt\"**, and **\"content\"**.\n\n";
	$acwbsrh_prompt .= "Business Information:\n{\n";
	$acwbsrh_prompt .= "\"business_name\": \"" . $acwbsrh_settings['business_name'] . "\",\n";
	$acwbsrh_prompt .= "\"business_type\": \"" . $acwbsrh_settings['business_type'] . "\",\n";
	$acwbsrh_prompt .= "\"services\": \"" . $acwbsrh_settings['services_offered'] . "\",\n";
	$acwbsrh_prompt .= "\"tone_of_voice\": \"" . $acwbsrh_settings['tone_of_voice'] . "\",\n";
	$acwbsrh_prompt .= "\"target_audience\": \"" . $acwbsrh_settings['target_audience'] . "\",\n";
	$acwbsrh_prompt .= "\"unique_selling_point\": \"" . $acwbsrh_settings['usp'] . "\",\n";
	$acwbsrh_prompt .= "\"blog_frequency\": \"" . $acwbsrh_settings['blog_frequency'] . "\"\n";
	$acwbsrh_prompt .= "}\n\n";

	$acwbsrh_prompt .= "### Writing Instructions:\n\n";
	$acwbsrh_prompt .= "- ✍️ **Content Style**: Use the specified tone of voice. Keep it natural, friendly, and human-centric. Avoid robotic language.\n";
	$acwbsrh_prompt .= "- 📈 **SEO Best Practices**:\n";
	$acwbsrh_prompt .= "  - Include **relevant, trending keywords** for the industry and services.\n";
	$acwbsrh_prompt .= "  - Use **semantic variations** and natural keyword flow (no stuffing).\n";
	$acwbsrh_prompt .= "  - Include a **compelling, SEO-friendly excerpt** (around 20–30 words).\n";
	$acwbsrh_prompt .= "  - Craft a **click-worthy and unique title** that hasn’t been used before.\n";
	$acwbsrh_prompt .= "- 🧠 **Structure & Format**:\n";
	$acwbsrh_prompt .= "  - Use **proper HTML formatting**: `<h2>`, `<h3>`, `<p>`, `<ul>`, `<li>`, etc.\n";
	$acwbsrh_prompt .= "  - Use **headings** for clear sections.\n";
	$acwbsrh_prompt .= "  - Break content into **short paragraphs** for readability.\n";
	$acwbsrh_prompt .= "  - Use **bullet points or numbered lists** where appropriate.\n";
	$acwbsrh_prompt .= "- 🔁 **Avoid Duplication**:\n";
	$acwbsrh_prompt .= "  - Do not reuse previous titles or topics. Assume access to blog history.\n";
	$acwbsrh_prompt .= "- 📏 **Length**: Keep blog content between **700–900 words**.\n";
	$acwbsrh_prompt .= "- ✅ **Return Format**:\n";
	$acwbsrh_prompt .= "Return ONLY a JSON array like the example below (no commentary or explanation):\n\n";
	$acwbsrh_prompt .= "[\n";
	$acwbsrh_prompt .= "{\n";
	$acwbsrh_prompt .= "\"title\": \"How Agencies Drive ROI in 2025\",\n";
	$acwbsrh_prompt .= "\"excerpt\": \"Learn how modern agencies maximize ROI with tailored strategies.\",\n";
	$acwbsrh_prompt .= "\"content\": \"<h2>Understanding ROI in the Digital Age</h2><p>...</p>\"\n";
	$acwbsrh_prompt .= "}\n";
	$acwbsrh_prompt .= "]\n";


    // --- Call Gemini API ---
    $url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" . urlencode($acwbsrh_api_key);

    $body = json_encode([
        'contents' => [[
            'role'  => 'user',
            'parts' => [['text' => $acwbsrh_prompt]],
        ]],
        'generationConfig' => [
            'responseMimeType' => 'application/json',
            'maxOutputTokens'  => 1200,
            'temperature'      => 0.7,
        ],
    ]);

    $acwbsrh_response = wp_remote_post($url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body'    => $body,
        'timeout' => 60,
    ]);

    if (is_wp_error($acwbsrh_response)) {
        return $acwbsrh_response;
    }

    $acwbsrh_code = wp_remote_retrieve_response_code($acwbsrh_response);
    $acwbsrh_data = json_decode(wp_remote_retrieve_body($acwbsrh_response), true);

    if ($acwbsrh_code !== 200 || empty($acwbsrh_data['candidates'][0]['content']['parts'][0]['text'])) {
        return new WP_Error('invalid_response', 'Gemini returned an invalid response.');
    }

    $acwbsrh_json_string = trim($acwbsrh_data['candidates'][0]['content']['parts'][0]['text']);
    $acwbsrh_json = json_decode($acwbsrh_json_string, true);

    if (!is_array($acwbsrh_json) || empty($acwbsrh_json[0])) {
        return new WP_Error('invalid_json', 'Failed to decode valid JSON.');
    }

    $acwbsrh_title   = sanitize_text_field($acwbsrh_json[0]['title']);
    $acwbsrh_excerpt = sanitize_text_field($acwbsrh_json[0]['excerpt'] ?? '');
    $acwbsrh_content = wp_kses_post($acwbsrh_json[0]['content']);

    if (acwbsrh_title_exists($acwbsrh_title)) {
        return new WP_Error('duplicate', 'Duplicate blog post title.');
    }

    $acwbsrh_post_id = wp_insert_post([
        'post_title'    => $acwbsrh_title,
        'post_content'  => $acwbsrh_content,
        'post_excerpt'  => $acwbsrh_excerpt,
        'post_status'   => in_array(strtolower($acwbsrh_settings['post_status']), ['publish', 'published']) ? 'publish' : 'draft',
        'post_type'     => 'post',
    ]);

    if (is_wp_error($acwbsrh_post_id)) {
        return new WP_Error('insertion_failed', 'Failed to insert blog post.');
    }

    return $acwbsrh_post_id;
}

add_action('wp_ajax_acwbsrh_start_auto_blogging', 'acwbsrh_handle_auto_blogging');
function acwbsrh_handle_auto_blogging() {
    // Get plugin settings
    $acwbsrh_settings = get_option('acwbsrh_settings');
    $acwbsrh_cronschedule = $acwbsrh_settings['blog_frequency'] ?? 'weekly';
    $acwbsrh_intervals = wp_get_schedules();

    // Generate blog
    $acwbsrh_result = acwbsrh_generate_blog(); // This function should return a post ID or WP_Error

    if (is_wp_error($acwbsrh_result)) {
        wp_send_json_error($acwbsrh_result->get_error_message());
    }

    // Calculate next interval (or fallback to 1 week)
    $acwbsrh_interval_seconds = $acwbsrh_intervals[$acwbsrh_cronschedule]['interval'] ?? 604800;

    // Reschedule next auto blog
    $acwbsrh_next = wp_next_scheduled('acwbsrh_auto_generate_blog');
    if ($acwbsrh_next) {
        wp_unschedule_event($acwbsrh_next, 'acwbsrh_auto_generate_blog');
    }

    wp_schedule_event(time() + $acwbsrh_interval_seconds, $acwbsrh_cronschedule, 'acwbsrh_auto_generate_blog');

    wp_send_json_success([
        'post_id' => $acwbsrh_result,
    ]);
}

// Register the actual cron action callback:
add_action('acwbsrh_auto_generate_blog', 'acwbsrh_pro_generate_blog_cron_handler');
function acwbsrh_pro_generate_blog_cron_handler() {
    $acwbsrh_result = acwbsrh_generate_blog();
}