<?php
/**
 * Guest Posts AJAX Handler
 *
 * Handles all AJAX requests related to guest posts:
 * - List/show guest posts
 * - Create/update/withdraw submissions
 * - Approve/reject/request-revision for hosts
 *
 * @package Consolety
 */

namespace Consolety\Ajax;

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

class GuestPostsAjaxHandler {
    private $api;

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

    /**
     * Register AJAX hooks
     */
    public function register(): void {
        add_action('wp_ajax_consolety_guest_posts_list', [$this, 'ajaxList']);
        add_action('wp_ajax_consolety_guest_posts_partners', [$this, 'ajaxPartners']);
        add_action('wp_ajax_consolety_guest_posts_show', [$this, 'ajaxShow']);
        add_action('wp_ajax_consolety_guest_posts_create', [$this, 'ajaxCreate']);
        add_action('wp_ajax_consolety_guest_posts_update', [$this, 'ajaxUpdate']);
        add_action('wp_ajax_consolety_guest_posts_approve', [$this, 'ajaxApprove']);
        add_action('wp_ajax_consolety_guest_posts_request_revision', [$this, 'ajaxRequestRevision']);
        add_action('wp_ajax_consolety_guest_posts_reject', [$this, 'ajaxReject']);
        add_action('wp_ajax_consolety_guest_posts_withdraw', [$this, 'ajaxWithdraw']);
        add_action('wp_ajax_consolety_guest_posts_dismiss', [$this, 'ajaxDismiss']);
    }

    /**
     * List guest posts (my submissions + pending review + received)
     */
    public function ajaxList(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $response = $this->api->get('/guest-posts');

        if (!empty($response['success'])) {
            // Update local credits from response
            if (isset($response['my_credits'])) {
                $siteInfo = get_option('consolety_site_info', []);
                $siteInfo['credits'] = $response['my_credits'];
                $siteInfo['credits_reserved'] = $response['my_credits_reserved'] ?? 0;
                update_option('consolety_site_info', $siteInfo);
            }
            wp_send_json_success($response['data'] ?? $response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to load guest posts'
        ]);
    }

    /**
     * Get available partners for guest post submission
     */
    public function ajaxPartners(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $response = $this->api->get('/guest-posts/partners');

        if (!empty($response['success'])) {
            wp_send_json_success($response['data'] ?? []);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to load partners'
        ]);
    }

    /**
     * Get single guest post details
     */
    public function ajaxShow(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        if (!$postId) {
            wp_send_json_error(['code' => 'INVALID_INPUT', 'message' => 'Invalid post ID']);
        }

        $response = $this->api->get('/guest-posts/' . $postId);

        if (!empty($response['success'])) {
            $data = $response['data'] ?? $response;

            // Fix escaped quotes in content (wp_unslash handles recursive slash removal)
            if (isset($data['content'])) {
                $data['content'] = wp_unslash($data['content']);
            }
            if (isset($data['author_bio'])) {
                $data['author_bio'] = wp_unslash($data['author_bio']);
            }
            if (isset($data['feedback'])) {
                $data['feedback'] = wp_unslash($data['feedback']);
            }

            wp_send_json_success($data);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to load post'
        ]);
    }

    /**
     * Create new guest post
     */
    public function ajaxCreate(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $data = [
            'host_site_id' => absint($_POST['host_site_id'] ?? 0),
            'title' => sanitize_text_field(wp_unslash($_POST['title'] ?? '')),
            'content' => wp_kses_post(wp_unslash($_POST['content'] ?? '')),
            'backlink_url' => esc_url_raw(wp_unslash($_POST['backlink_url'] ?? '')),
            'anchor_text' => sanitize_text_field(wp_unslash($_POST['anchor_text'] ?? '')),
            'author_bio' => sanitize_textarea_field(wp_unslash($_POST['author_bio'] ?? '')),
            'submit' => !empty($_POST['submit']),
        ];

        if (!$data['host_site_id'] || !$data['title'] || !$data['content']) {
            wp_send_json_error(['code' => 'VALIDATION_ERROR', 'message' => 'Missing required fields']);
        }

        $response = $this->api->post('/guest-posts', $data);

        if (!empty($response['success'])) {
            wp_send_json_success($response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to create guest post'
        ]);
    }

    /**
     * Update existing guest post (edit draft or resubmit after revision)
     */
    public function ajaxUpdate(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        if (!$postId) {
            wp_send_json_error(['code' => 'INVALID_INPUT', 'message' => 'Missing post ID']);
        }

        $data = [
            'title' => sanitize_text_field(wp_unslash($_POST['title'] ?? '')),
            'content' => wp_kses_post(wp_unslash($_POST['content'] ?? '')),
            'author_bio' => sanitize_textarea_field(wp_unslash($_POST['author_bio'] ?? '')),
            'submit' => !empty($_POST['submit']),
        ];

        if (!$data['title'] || !$data['content']) {
            wp_send_json_error(['code' => 'VALIDATION_ERROR', 'message' => 'Missing required fields']);
        }

        $response = $this->api->put('/guest-posts/' . $postId, $data);

        if (!empty($response['success'])) {
            wp_send_json_success($response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to update guest post'
        ]);
    }

    /**
     * Approve guest post and create WordPress post
     */
    public function ajaxApprove(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        if (!$postId) {
            wp_send_json_error(['code' => 'INVALID_INPUT', 'message' => 'Invalid post ID']);
        }

        // First get the post content from Hub
        $postResponse = $this->api->get('/guest-posts/' . $postId);

        if (empty($postResponse['success']) || empty($postResponse['data'])) {
            wp_send_json_error([
                'code' => $postResponse['error']['code'] ?? 'FETCH_FAILED',
                'message' => $postResponse['error']['message'] ?? 'Could not fetch post content'
            ]);
        }

        $guestPost = $postResponse['data'];

        // Get selected category (default to uncategorized if not provided)
        $categoryId = absint($_POST['category_id'] ?? 0);
        $postCategories = $categoryId ? [$categoryId] : [get_option('default_category', 1)];

        // Clean content (wp_unslash removes all slash layers from escaped quotes)
        $content = wp_kses_post(wp_unslash($guestPost['content']));
        $authorBio = isset($guestPost['author_bio']) ? sanitize_textarea_field(wp_unslash($guestPost['author_bio'])) : '';

        // Create WordPress post
        $wpPostId = wp_insert_post([
            'post_title' => sanitize_text_field(wp_unslash($guestPost['title'])),
            'post_content' => $content,
            'post_status' => 'publish',
            'post_type' => 'post',
            'post_author' => get_current_user_id(),
            'post_category' => $postCategories,
            'meta_input' => [
                '_gp_guest_post' => true,
                '_gp_source_id' => $postId,
                '_gp_submitter_domain' => $guestPost['submitter']['domain'] ?? '',
                '_gp_author_bio' => $authorBio,
            ],
        ], true);

        if (is_wp_error($wpPostId)) {
            wp_send_json_error(['code' => 'WP_ERROR', 'message' => 'Failed to create WordPress post: ' . $wpPostId->get_error_message()]);
        }

        // Set featured image if provided
        $featuredImageId = absint($_POST['featured_image_id'] ?? 0);
        if ($featuredImageId > 0) {
            $attachment = get_post($featuredImageId);
            if ($attachment && $attachment->post_type === 'attachment' && wp_attachment_is_image($featuredImageId)) {
                set_post_thumbnail($wpPostId, $featuredImageId);
            }
        }

        $publishedUrl = get_permalink($wpPostId);

        // Notify Hub of approval
        $response = $this->api->post('/guest-posts/' . $postId . '/approve', [
            'published_url' => $publishedUrl,
            'published_wp_post_id' => $wpPostId,
        ]);

        if (!empty($response['success'])) {
            delete_transient('consolety_badge_counts');
            wp_send_json_success([
                'message' => 'Guest post published!',
                'wp_post_id' => $wpPostId,
                'published_url' => $publishedUrl,
                'credits_earned' => $response['credits_earned'] ?? 0,
                'new_balance' => $response['new_balance'] ?? null,
            ]);
        }

        // Rollback WP post if Hub approval failed
        wp_delete_post($wpPostId, true);
        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to approve on Hub'
        ]);
    }

    /**
     * Request revision on guest post
     */
    public function ajaxRequestRevision(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        $feedback = sanitize_textarea_field(wp_unslash($_POST['feedback'] ?? ''));

        if (!$postId || !$feedback) {
            wp_send_json_error(['code' => 'VALIDATION_ERROR', 'message' => 'Post ID and feedback are required']);
        }

        $response = $this->api->post('/guest-posts/' . $postId . '/request-revision', [
            'feedback' => $feedback,
        ]);

        if (!empty($response['success'])) {
            delete_transient('consolety_badge_counts');
            wp_send_json_success($response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to request revision'
        ]);
    }

    /**
     * Reject guest post
     */
    public function ajaxReject(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        $reason = sanitize_textarea_field(wp_unslash($_POST['reason'] ?? ''));

        if (!$postId || !$reason) {
            wp_send_json_error(['code' => 'VALIDATION_ERROR', 'message' => 'Post ID and reason are required']);
        }

        $response = $this->api->post('/guest-posts/' . $postId . '/reject', [
            'reason' => $reason,
        ]);

        if (!empty($response['success'])) {
            delete_transient('consolety_badge_counts');
            wp_send_json_success($response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to reject'
        ]);
    }

    /**
     * Withdraw my submission
     */
    public function ajaxWithdraw(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        if (!$postId) {
            wp_send_json_error(['code' => 'INVALID_INPUT', 'message' => 'Invalid post ID']);
        }

        $response = $this->api->post('/guest-posts/' . $postId . '/withdraw');

        if (!empty($response['success'])) {
            delete_transient('consolety_badge_counts');
            wp_send_json_success($response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to withdraw'
        ]);
    }

    /**
     * Dismiss (hide) a rejected/withdrawn guest post
     */
    public function ajaxDismiss(): void {
        check_ajax_referer('consolety_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['code' => 'UNAUTHORIZED', 'message' => 'Unauthorized']);
        }

        $postId = absint($_POST['post_id'] ?? 0);
        if (!$postId) {
            wp_send_json_error(['code' => 'INVALID_INPUT', 'message' => 'Invalid post ID']);
        }

        $response = $this->api->dismissGuestPost($postId);

        if (!empty($response['success'])) {
            wp_send_json_success($response);
        }

        wp_send_json_error([
            'code' => $response['error']['code'] ?? 'API_ERROR',
            'message' => $response['error']['message'] ?? 'Failed to dismiss'
        ]);
    }
}
