<?php
/**
 * LeadMachine Post Sync
 * Handles syncing WordPress posts and categories to LeadMachine
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * LeadMachine Post Sync Class
 */
class LeadMachine_Post_Sync {

    private static $instance = null;

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // Auto-sync on post publish/update
        add_action('publish_post', array($this, 'sync_single_post'), 10, 2);
        add_action('edit_post', array($this, 'maybe_sync_on_update'), 10, 2);

        // AJAX handlers
        add_action('wp_ajax_leadmachine_sync_categories', array($this, 'ajax_sync_categories'));
        add_action('wp_ajax_leadmachine_sync_all_posts', array($this, 'ajax_sync_all_posts'));
        add_action('wp_ajax_leadmachine_sync_single_post', array($this, 'ajax_sync_single_post'));
    }

    /**
     * Check if post sync is enabled
     */
    public function is_sync_enabled() {
        return get_option('leadmachine_post_sync_enabled', false);
    }

    /**
     * Get categories configured for sync
     */
    public function get_sync_categories() {
        $cats = get_option('leadmachine_post_sync_categories', array());
        if (!is_array($cats)) {
            $cats = array();
        }
        return array_map('intval', $cats);
    }

    /**
     * Auto-sync when a post is published
     */
    public function sync_single_post($post_id, $post) {
        // Check if sync is enabled
        if (!$this->is_sync_enabled()) {
            return;
        }

        // Only sync published posts
        if ($post->post_status !== 'publish' || $post->post_type !== 'post') {
            return;
        }

        // Check if post is in a synced category
        $sync_categories = $this->get_sync_categories();
        if (!empty($sync_categories)) {
            $post_categories = wp_get_post_categories($post_id);
            $in_sync_category = array_intersect($post_categories, $sync_categories);
            if (empty($in_sync_category)) {
                return;
            }
        }

        // Sync the post
        $this->send_post_to_leadmachine($post_id);
    }

    /**
     * Maybe sync post on update (if it's published)
     */
    public function maybe_sync_on_update($post_id, $post) {
        // Don't double-trigger on publish
        if (did_action('publish_post')) {
            return;
        }

        // Only sync if post is published
        if (!is_object($post)) {
            $post = get_post($post_id);
        }
        if (!$post || $post->post_status !== 'publish' || $post->post_type !== 'post') {
            return;
        }

        $this->sync_single_post($post_id, $post);
    }

    /**
     * Send a single post to LeadMachine
     */
    public function send_post_to_leadmachine($post_id) {
        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');
        $api_url = get_option('leadmachine_api_url', 'https://app.leadmachine.fyi');

        if (empty($company_id) || empty($api_key)) {
            return new WP_Error('config', 'Missing Company ID or API Key');
        }

        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'post') {
            return new WP_Error('invalid_post', 'Invalid post');
        }

        // Get post data
        $featured_image = get_the_post_thumbnail_url($post_id, 'large');
        $author = get_the_author_meta('display_name', $post->post_author);
        $categories = wp_get_post_categories($post_id);

        // Build data payload
        $data = array(
            'company_id' => $company_id,
            'api_key' => $api_key,
            'wp_post_id' => $post_id,
            'title' => $post->post_title,
            'excerpt' => $post->post_excerpt ?: wp_trim_words(strip_tags($post->post_content), 55),
            'content' => $post->post_content,
            'featured_image_url' => $featured_image ?: '',
            'permalink' => get_permalink($post_id),
            'author_name' => $author,
            'published_at' => $post->post_date_gmt,
            'categories' => $categories
        );

        // Send to LeadMachine
        $response = wp_remote_post(
            rtrim($api_url, '/') . '/api/wordpress/sync-post.php',
            array(
                'body' => wp_json_encode($data),
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/json',
                ),
            )
        );

        if (is_wp_error($response)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                error_log('LeadMachine Post Sync Error: ' . $response->get_error_message());
            }
            return $response;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('LeadMachine Post Sync [' . $response_code . ']: ' . $response_body);
        }

        $result = json_decode($response_body, true);

        if ($response_code === 200 && isset($result['success']) && $result['success']) {
            // Update last sync timestamp
            update_post_meta($post_id, '_leadmachine_synced_at', current_time('mysql'));
            return true;
        }

        return new WP_Error('api_error', $result['error'] ?? 'Unknown error');
    }

    /**
     * Sync all categories to LeadMachine
     */
    public function sync_categories() {
        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');
        $api_url = get_option('leadmachine_api_url', 'https://app.leadmachine.fyi');

        if (empty($company_id) || empty($api_key)) {
            return new WP_Error('config', 'Missing Company ID or API Key');
        }

        // Get all categories
        $categories = get_categories(array(
            'hide_empty' => false,
            'orderby' => 'name',
            'order' => 'ASC'
        ));

        if (empty($categories)) {
            return new WP_Error('no_categories', 'No categories found');
        }

        // Build category data
        $category_data = array();
        foreach ($categories as $cat) {
            $category_data[] = array(
                'id' => $cat->term_id,
                'name' => $cat->name,
                'slug' => $cat->slug,
                'parent' => $cat->parent,
                'count' => $cat->count
            );
        }

        // Send to LeadMachine
        $data = array(
            'company_id' => $company_id,
            'api_key' => $api_key,
            'categories' => $category_data
        );

        $response = wp_remote_post(
            rtrim($api_url, '/') . '/api/wordpress/sync-categories.php',
            array(
                'body' => wp_json_encode($data),
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/json',
                ),
            )
        );

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

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $result = json_decode($response_body, true);

        if ($response_code === 200 && isset($result['success']) && $result['success']) {
            update_option('leadmachine_categories_last_sync', current_time('mysql'));
            return $result;
        }

        return new WP_Error('api_error', $result['error'] ?? 'Unknown error');
    }

    /**
     * Sync all posts in configured categories
     */
    public function sync_all_posts() {
        $sync_categories = $this->get_sync_categories();

        // Query posts
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'date',
            'order' => 'ASC'
        );

        // Filter by categories if specified
        if (!empty($sync_categories)) {
            $args['category__in'] = $sync_categories;
        }

        $posts = get_posts($args);

        if (empty($posts)) {
            return array(
                'synced' => 0,
                'errors' => 0,
                'message' => 'No posts found to sync'
            );
        }

        $synced = 0;
        $errors = 0;

        foreach ($posts as $post) {
            $result = $this->send_post_to_leadmachine($post->ID);
            if (is_wp_error($result)) {
                $errors++;
            } else {
                $synced++;
            }
        }

        // Update last sync time
        update_option('leadmachine_posts_last_sync', current_time('mysql'));

        return array(
            'synced' => $synced,
            'errors' => $errors,
            'total' => count($posts),
            'message' => "Synced {$synced} posts" . ($errors > 0 ? ", {$errors} errors" : '')
        );
    }

    /**
     * AJAX: Sync categories
     */
    public function ajax_sync_categories() {
        check_ajax_referer('leadmachine_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $result = $this->sync_categories();

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

        wp_send_json_success($result);
    }

    /**
     * AJAX: Sync all posts
     */
    public function ajax_sync_all_posts() {
        check_ajax_referer('leadmachine_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $result = $this->sync_all_posts();

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

        wp_send_json_success($result);
    }

    /**
     * AJAX: Sync single post
     */
    public function ajax_sync_single_post() {
        check_ajax_referer('leadmachine_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $post_id = intval($_POST['post_id'] ?? 0);

        if (!$post_id) {
            wp_send_json_error(array('message' => 'Invalid post ID'));
        }

        $result = $this->send_post_to_leadmachine($post_id);

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

        wp_send_json_success(array('message' => 'Post synced successfully'));
    }

    /**
     * Get sync status for display
     */
    public function get_sync_status() {
        $sync_categories = $this->get_sync_categories();

        // Count posts in sync categories
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields' => 'ids'
        );

        if (!empty($sync_categories)) {
            $args['category__in'] = $sync_categories;
        }

        $posts = get_posts($args);

        return array(
            'enabled' => $this->is_sync_enabled(),
            'post_count' => count($posts),
            'categories_last_sync' => get_option('leadmachine_categories_last_sync', ''),
            'posts_last_sync' => get_option('leadmachine_posts_last_sync', '')
        );
    }
}

// Initialize
function leadmachine_post_sync_init() {
    return LeadMachine_Post_Sync::get_instance();
}
add_action('init', 'leadmachine_post_sync_init');
