<?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() {
        $auth = self::verify_request();
        if ( is_wp_error( $auth ) ) {
            wp_send_json_error( array( 'message' => $auth->get_error_message() ), 403 );
            return;
        }

        $article_ids = isset( $_POST['article_ids'] ) ? $_POST['article_ids'] : array();
        $result      = Rank_Ms_Chat_Services::writer_upload( is_array( $article_ids ) ? $article_ids : array() );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ), $result->get_error_data( 'status' ) ?: 400 );
            return;
        }

        wp_send_json_success( $result );
    }
}