<?php
/**
 * Rank Writer AJAX Handlers
 * 
 * Handles AJAX requests for the Rank Writer tab.
 */

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

class Rank_Writer_Ajax {
    
    /**
     * Initialize AJAX hooks
     */
    public static function init() {
        add_action( 'wp_ajax_rank_writer_get_articles', array( __CLASS__, 'ajax_get_articles' ) );
        add_action( 'wp_ajax_rank_writer_upload_to_wp', array( __CLASS__, 'ajax_upload_to_wp' ) );
    }
    
    /**
     * Verify nonce and user permissions
     * 
     * @return bool|WP_Error True if authorized, WP_Error otherwise
     */
    private static function verify_request() {
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'rank_ajax_nonce' ) ) {
            return new WP_Error( 'invalid_nonce', 'Security check failed.', array( 'status' => 403 ) );
        }
        
        if ( ! current_user_can( 'manage_options' ) ) {
            return new WP_Error( 'insufficient_permissions', 'Permission denied.', array( 'status' => 403 ) );
        }
        
        return true;
    }
    
    /**
     * AJAX handler: Get articles list with pagination and upload status
     */
    public static function ajax_get_articles() {
        // Verify request
        $auth = self::verify_request();
        if ( is_wp_error( $auth ) ) {
            wp_send_json_error( array( 'message' => $auth->get_error_message() ), 403 );
            return;
        }
        
        // Get pagination params
        $page = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
        $per_page = isset( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 10;
        
        // Validate per_page
        if ( $per_page < 1 || $per_page > 100 ) {
            $per_page = 10;
        }
        
        // Get articles with upload status
        $result = Rank_Writer::get_articles_with_status( $page, $per_page );
        
        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ), 400 );
            return;
        }
        
        // Format response
        $response = array(
            'articles' => isset( $result['data'] ) ? $result['data'] : array(),
            'total' => isset( $result['total'] ) ? intval( $result['total'] ) : 0,
            'page' => isset( $result['page'] ) ? intval( $result['page'] ) : $page,
            'per_page' => isset( $result['per_page'] ) ? intval( $result['per_page'] ) : $per_page,
            'total_pages' => 0
        );
        
        // Calculate total pages
        if ( $response['total'] > 0 && $response['per_page'] > 0 ) {
            $response['total_pages'] = ceil( $response['total'] / $response['per_page'] );
        }
        
        wp_send_json_success( $response );
    }
    
    /**
     * AJAX handler: Upload selected articles to WordPress as drafts
     */
    public static function ajax_upload_to_wp() {
        // Verify request
        $auth = self::verify_request();
        if ( is_wp_error( $auth ) ) {
            wp_send_json_error( array( 'message' => $auth->get_error_message() ), 403 );
            return;
        }
        
        // Get article IDs
        $article_ids = isset( $_POST['article_ids'] ) ? $_POST['article_ids'] : array();
        
        if ( empty( $article_ids ) || ! is_array( $article_ids ) ) {
            wp_send_json_error( array( 'message' => 'No articles selected.' ), 400 );
            return;
        }
        
        // Sanitize article IDs
        $article_ids = array_map( 'sanitize_text_field', $article_ids );
        
        // Process each article
        $results = array();
        $uploaded_count = 0;
        $failed_count = 0;
        
        foreach ( $article_ids as $article_id ) {
            // Skip if already uploaded
            if ( Rank_Writer_DB::is_article_uploaded( $article_id ) ) {
                $results[] = array(
                    'article_id' => $article_id,
                    'status' => 'skipped',
                    'message' => 'Already uploaded'
                );
                continue;
            }
            
            // Fetch full article content from API
            $article = Rank_Writer::get_article( $article_id );
            
            if ( is_wp_error( $article ) ) {
                $results[] = array(
                    'article_id' => $article_id,
                    'status' => 'error',
                    'message' => $article->get_error_message()
                );
                $failed_count++;
                continue;
            }
            
            // Create WordPress draft
            $post_id = Rank_Writer::create_wp_draft( $article );
            
            if ( is_wp_error( $post_id ) ) {
                $results[] = array(
                    'article_id' => $article_id,
                    'status' => 'error',
                    'message' => $post_id->get_error_message()
                );
                $failed_count++;
                continue;
            }
            
            // Success
            $results[] = array(
                'article_id' => $article_id,
                'status' => 'success',
                'wp_post_id' => $post_id,
                'title' => $article['title'],
                'edit_url' => get_edit_post_link( $post_id, 'raw' )
            );
            $uploaded_count++;
        }
        
        // Build response message
        $message = sprintf(
            '%d article(s) uploaded as drafts.',
            $uploaded_count
        );
        
        if ( $failed_count > 0 ) {
            $message .= sprintf( ' %d failed.', $failed_count );
        }
        
        wp_send_json_success( array(
            'message' => $message,
            'uploaded' => $uploaded_count,
            'failed' => $failed_count,
            'results' => $results
        ) );
    }
}