<?php
/**
 * AJAX handler for creating WordPress posts from Content Strategy
 *
 * @package    Aysa
 * @subpackage Aysa/includes/ajax
 */

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

class Aysa_Content_Strategy_Create_Post {
    
    public function __construct() {
        add_action('wp_ajax_aysa_create_post_from_strategy', array($this, 'create_post_from_strategy'));
    }
    
    /**
     * Create a new WordPress post from Content Strategy title and keywords
     */
    public function create_post_from_strategy() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_create_post_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        // Check user permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'You do not have permission to create posts'));
            return;
        }
        
        $result = self::create_post_programmatically(array(
            'title' => isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '',
            'keywords' => json_decode(stripslashes($_POST['keywords'] ?? '[]'), true),
            'intent' => isset($_POST['intent']) ? sanitize_text_field($_POST['intent']) : 'I',
            'associated_pages' => $_POST['associated_pages'] ?? '',
            'associated_page' => $_POST['associated_page'] ?? '',
            'strategy_id' => isset($_POST['strategy_id']) ? intval($_POST['strategy_id']) : 0,
            'source' => 'content-strategy',
        ));

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
            return;
        }

        wp_send_json_success($result);
    }

    public static function create_post_programmatically(array $args) {
        $instance = new self();

        $title = sanitize_text_field((string) ($args['title'] ?? ''));
        $keywords = isset($args['keywords']) && is_array($args['keywords']) ? array_values($args['keywords']) : array();
        $intent = sanitize_text_field((string) ($args['intent'] ?? 'I'));
        $associated_pages = $instance->normalize_associated_pages_from_post($args['associated_pages'] ?? '');
        $associated_page_fallback = isset($args['associated_page']) ? $instance->normalize_single_associated_page($args['associated_page']) : '';
        if (empty($associated_pages) && $associated_page_fallback !== '') {
            $associated_pages = array($associated_page_fallback);
        }
        $associated_page = isset($associated_pages[0]) ? $associated_pages[0] : '';
        $strategy_id = intval($args['strategy_id'] ?? 0);
        $source = sanitize_key((string) ($args['source'] ?? 'content-strategy'));

        if ($title === '') {
            return new WP_Error('missing_title', 'Title is required');
        }

        $main_keyword = !empty($keywords) ? sanitize_text_field((string) $keywords[0]) : $title;
        $secondary_keywords = array_values(array_filter(array_map('sanitize_text_field', array_slice($keywords, 1))));

        $content = '';
        if (!empty($associated_page)) {
            $content = sprintf(
                '<!-- wp:paragraph --><p>%s <a href="%s">%s</a></p><!-- /wp:paragraph -->',
                __('See also:', 'aysaaiseo'),
                esc_url($associated_page),
                __('Related Content', 'aysaaiseo')
            );
        }

        $post_data = array(
            'post_title'   => $title,
            'post_content' => $content,
            'post_status'  => 'draft',
            'post_type'    => 'post',
            'post_author'  => get_current_user_id(),
        );

        $post_id = wp_insert_post($post_data, true);
        if (is_wp_error($post_id)) {
            return new WP_Error('create_failed', 'Failed to create post: ' . $post_id->get_error_message());
        }
        $post_id = intval($post_id);

        if (class_exists('Aysa_Content_Strategy_Manager')) {
            if ($strategy_id > 0) {
                Aysa_Content_Strategy_Manager::link_post_to_strategy($strategy_id, $post_id);
            } else {
                Aysa_Content_Strategy_Manager::link_post_by_title($title, $post_id);
            }
        }

        $keyword_data = array(
            'article_topic'  => $title,
            'keyword'        => $main_keyword,
            'second_keyword' => implode(', ', $secondary_keywords),
            'intent'         => $intent,
            'source'         => $source,
        );

        update_post_meta($post_id, 'aysa_keyword_data', $keyword_data);
        update_post_meta($post_id, 'aysa_main_keyword', $main_keyword);
        update_post_meta($post_id, 'aysa_secondary_keywords', implode(', ', $secondary_keywords));
        update_post_meta($post_id, 'aysa_search_intent', $intent);
        update_post_meta($post_id, 'aysa_associated_page', $associated_page);
        update_post_meta($post_id, 'aysa_associated_pages', $associated_pages);
        update_post_meta($post_id, 'aysa_generation_source', $source);

        $generation_payload = array(
            'post_id' => $post_id,
            'title' => $title,
            'main_keyword' => $main_keyword,
            'secondary_keywords' => array_values($secondary_keywords),
            'associated_pages' => array_values($associated_pages),
        );
        update_post_meta($post_id, '_aysa_existing_post_generation_status', 'queued');
        update_post_meta($post_id, '_aysa_existing_post_generation_queued_at', current_time('mysql'));
        delete_post_meta($post_id, '_aysa_existing_post_generation_error');
        wp_schedule_single_event(time() + 2, 'aysa_generate_existing_strategy_post', array($generation_payload));

        aysa_debug_log('[AYSA Content Strategy] Created post #' . $post_id . ' with title: ' . $title);
        aysa_debug_log('[AYSA Content Strategy] Main keyword: ' . $main_keyword);
        aysa_debug_log('[AYSA Content Strategy] Secondary keywords: ' . implode(', ', $secondary_keywords));

        return array(
            'message'  => 'Article created. Full content generation is queued and will run server-side.',
            'post_id'  => $post_id,
            'edit_url' => get_edit_post_link($post_id, ''),
            'view_url' => get_permalink($post_id),
            'title'    => $title,
            'keywords' => array_merge(array($main_keyword), $secondary_keywords),
            'content_generated' => false,
            'generation_queued' => true,
        );
    }

    private function normalize_single_associated_page($value) {
        $raw = trim((string) $value);
        if ($raw === '' || $raw === '-' || strtolower($raw) === 'n/a' || strpos($raw, 'http://-') === 0 || strpos($raw, 'https://-') === 0) {
            return '';
        }
        if (preg_match('#^https?://#i', $raw)) {
            return esc_url_raw($raw);
        }
        if (strpos($raw, '/') === 0) {
            return esc_url_raw(home_url($raw));
        }
        return '';
    }

    private function normalize_associated_pages_from_post($value) {
        if (is_string($value)) {
            $decoded = json_decode(stripslashes($value), true);
            if (is_array($decoded)) {
                $value = $decoded;
            }
        }
        $values = is_array($value) ? $value : array($value);
        $seen = array();
        $clean = array();
        foreach ($values as $item) {
            $normalized = $this->normalize_single_associated_page($item);
            if ($normalized === '') {
                continue;
            }
            $key = strtolower($normalized);
            if (isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;
            $clean[] = $normalized;
        }
        return $clean;
    }
}

// Initialize the handler
new Aysa_Content_Strategy_Create_Post();
