<?php
/**
 * Guest Posts Handler
 *
 * Manages the custom "pending_guest_post" status and incoming guest posts
 * from the Consolety network.
 *
 * @package Consolety
 */

namespace Consolety;

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

class GuestPosts {
    const POST_STATUS = 'pending_guest_post';

    private $api;

    public function __construct(Api $api) {
        $this->api = $api;

        // Register custom post status
        add_action('init', [$this, 'registerPostStatus']);

        // Add status to post status dropdown
        add_action('admin_footer-edit.php', [$this, 'appendStatusToDropdown']);
        add_action('admin_footer-post.php', [$this, 'appendStatusToDropdown']);

        // Display custom status in posts list
        add_filter('display_post_states', [$this, 'displayPostStates'], 10, 2);

        // REST API endpoint for receiving guest posts from Hub
        add_action('rest_api_init', [$this, 'registerRestEndpoints']);
    }

    /**
     * Register custom post status for incoming guest posts
     */
    public function registerPostStatus() {
        register_post_status(self::POST_STATUS, [
            'label'                     => __('Pending Guest Post', 'consolety'),
            /* translators: %s: number of pending guest posts */
            'label_count'               => _n_noop(
                'Pending Guest Post <span class="count">(%s)</span>',
                'Pending Guest Posts <span class="count">(%s)</span>',
                'consolety'
            ),
            'public'                    => false,
            'internal'                  => true,
            'private'                   => true,
            'exclude_from_search'       => true,
            'show_in_admin_all_list'    => true,
            'show_in_admin_status_list' => true,
        ]);
    }

    /**
     * Get count of pending guest posts
     */
    public function getPendingCount(): int {
        $posts = get_posts([
            'post_status' => self::POST_STATUS,
            'post_type'   => 'post',
            'numberposts' => -1,
            'fields'      => 'ids',
        ]);
        return count($posts);
    }

    /**
     * Add custom status to dropdown in post editor
     */
    public function appendStatusToDropdown() {
        global $post;
        if (!$post) return;

        $isGuestPost = ($post->post_status === self::POST_STATUS);
        $label = __('Pending Guest Post', 'consolety');

        $inlineJs = sprintf(
            'jQuery(document).ready(function($) {' .
                'var vpStatus = %s;' .
                'var vpLabel = %s;' .
                'var vpIsActive = %s;' .
                '$("select#post_status").append(\'<option value="\' + vpStatus + \'"\' + (vpIsActive ? \' selected="selected"\' : \'\') + \'>\' + vpLabel + \'</option>\');' .
                'if (vpIsActive) { $("#post-status-display").text(vpLabel); }' .
            '});',
            wp_json_encode(self::POST_STATUS),
            wp_json_encode($label),
            wp_json_encode($isGuestPost)
        );

        wp_add_inline_script('jquery', $inlineJs);
    }

    /**
     * Display custom status in post list
     */
    public function displayPostStates($states, $post) {
        if ($post->post_status === self::POST_STATUS) {
            $states[self::POST_STATUS] = '<span style="color: #10b981; font-weight: 600;">&#10003; ' . __('Pending Guest Post', 'consolety') . '</span>';
        }
        return $states;
    }

    /**
     * Register REST API endpoints for receiving guest posts from Hub
     */
    public function registerRestEndpoints() {
        register_rest_route('consolety/v1', '/guest-post', [
            'methods'             => 'POST',
            'callback'            => [$this, 'handleIncomingGuestPost'],
            'permission_callback' => [$this, 'validateHubRequest'],
        ]);
    }

    /**
     * Validate that request comes from Consolety Hub
     */
    public function validateHubRequest(\WP_REST_Request $request): bool {
        $hub_token = $request->get_header('X-Consolety-Hub-Token');
        $expected_token = get_option('consolety_webhook_secret', '');

        if (empty($expected_token)) {
            // Generate one if not exists
            $expected_token = wp_generate_uuid4();
            update_option('consolety_webhook_secret', $expected_token);
        }

        return !empty($hub_token) && hash_equals($expected_token, $hub_token);
    }

    /**
     * Handle incoming guest post from Hub API
     */
    public function handleIncomingGuestPost(\WP_REST_Request $request): \WP_REST_Response {
        $title = sanitize_text_field($request->get_param('title'));
        $content = wp_kses_post($request->get_param('content'));
        $author_name = sanitize_text_field($request->get_param('author_name'));
        $author_site = esc_url($request->get_param('author_site'));
        $hub_guest_post_id = absint($request->get_param('hub_guest_post_id'));
        $connection_id = absint($request->get_param('connection_id'));

        if (empty($title) || empty($content)) {
            return new \WP_REST_Response([
                'success' => false,
                'error' => 'Title and content are required',
            ], 400);
        }

        // Create post with pending_guest_post status
        $post_id = wp_insert_post([
            'post_title'   => $title,
            'post_content' => $content,
            'post_status'  => self::POST_STATUS,
            'post_type'    => 'post',
            'post_author'  => get_current_user_id() ?: 1,
            'meta_input'   => [
                '_gp_guest_post'    => true,
                '_gp_author_name'   => $author_name,
                '_gp_author_site'   => $author_site,
                '_gp_hub_id'        => $hub_guest_post_id,
                '_gp_connection_id' => $connection_id,
                '_gp_received_at'   => current_time('mysql'),
            ],
        ]);

        if (is_wp_error($post_id)) {
            return new \WP_REST_Response([
                'success' => false,
                'error' => $post_id->get_error_message(),
            ], 500);
        }

        // Invalidate badge cache so the new guest post shows immediately
        delete_transient('consolety_badge_counts');

        return new \WP_REST_Response([
            'success' => true,
            'post_id' => $post_id,
            'edit_url' => get_edit_post_link($post_id, 'raw'),
        ]);
    }

}
