<?php

namespace AIPT\Api\AutomationJobs;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

/**
 * Draft Content REST API Controller
 *
 * Handles REST API endpoints for draft content management
 *
 * @since 2.3.0
 */
class DraftContentController {

    /**
     * Draft content manager instance
     * @var DraftContentManager
     */
    private $draft_manager;

    /**
     * Constructor
     */
    public function __construct() {
        $this->draft_manager = new DraftContentManager();
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {

        register_rest_route('aipt/v1', '/draft-content', [
            [
                'methods' => 'GET',
                'callback' => [$this, 'get_draft_content'],
                'permission_callback' => [$this, 'check_permissions'],
                'args' => [
                    'page' => [
                        'default' => 1,
                        'sanitize_callback' => 'absint',
                    ],
                    'per_page' => [
                        'default' => 20,
                        'sanitize_callback' => 'absint',
                    ],
                    'status' => [
                        'default' => 'pending',
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                    'job_id' => [
                        'sanitize_callback' => 'absint',
                    ],
                    'product_id' => [
                        'sanitize_callback' => 'absint',
                    ],
                    'content_type' => [
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ],
        ]);

        register_rest_route('aipt/v1', '/draft-content/(?P<id>\d+)/approve', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'approve_draft_content'],
                'permission_callback' => [$this, 'check_permissions_write'],
                'args' => [
                    'id' => [
                        'required' => true,
                        'sanitize_callback' => 'absint',
                    ],
                ],
            ],
        ]);

        register_rest_route('aipt/v1', '/draft-content/(?P<id>\d+)/reject', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'reject_draft_content'],
                'permission_callback' => [$this, 'check_permissions_write'],
                'args' => [
                    'id' => [
                        'required' => true,
                        'sanitize_callback' => 'absint',
                    ],
                ],
            ],
        ]);

        register_rest_route('aipt/v1', '/draft-content/bulk-approve', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'bulk_approve_draft_content'],
                'permission_callback' => [$this, 'check_permissions_write'],
                'args' => [
                    'ids' => [
                        'required' => true,
                        'validate_callback' => function($param) {
                            return is_array($param) && !empty($param);
                        },
                        'sanitize_callback' => function($param) {
                            return array_map('absint', $param);
                        },
                    ],
                ],
            ],
        ]);

        register_rest_route('aipt/v1', '/draft-content/bulk-delete', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'bulk_delete_draft_content'],
                'permission_callback' => [$this, 'check_permissions_write'],
                'args' => [
                    'ids' => [
                        'required' => true,
                        'validate_callback' => function($param) {
                            return is_array($param) && !empty($param);
                        },
                        'sanitize_callback' => function($param) {
                            return array_map('absint', $param);
                        },
                    ],
                ],
            ],
        ]);

        register_rest_route('aipt/v1', '/draft-content/(?P<id>\d+)', [
            [
                'methods' => 'DELETE',
                'callback' => [$this, 'delete_draft_content'],
                'permission_callback' => [$this, 'check_permissions_write'],
                'args' => [
                    'id' => [
                        'required' => true,
                        'sanitize_callback' => 'absint',
                    ],
                ],
            ],
        ]);
    }

    /**
     * Check permissions for API access
     *
     * @param WP_REST_Request $request Request object
     * @return bool|WP_Error Permission status
     */
    public function check_permissions($request) {
        if (!current_user_can('manage_woocommerce')) {
            return new WP_Error(
                'rest_forbidden',
                __('You do not have permission to access this resource.', 'ai-product-tools'),
                ['status' => 403]
            );
        }

        return true;
    }
    /**
     * Check permissions for write operations (POST/DELETE)
     * Requires manage_woocommerce and a valid REST nonce
     *
     * @param WP_REST_Request $request
     * @return bool|WP_Error
     */
    public function check_permissions_write($request) {
        if (!current_user_can('manage_woocommerce')) {
            return new WP_Error(
                'rest_forbidden',
                __('You do not have permission to perform this action.', 'ai-product-tools'),
                ['status' => 403]
            );
        }

        $nonce = $request instanceof \WP_REST_Request ? $request->get_header('X-WP-Nonce') : '';
        if (empty($nonce) && isset($_REQUEST['_wpnonce'])) {
            $nonce = sanitize_text_field(wp_unslash($_REQUEST['_wpnonce']));
        }

        if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('rest_invalid_nonce', __('Invalid or missing security nonce.', 'ai-product-tools'), ['status' => 403]);
        }

        return true;
    }

    /**
     * Get draft content
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error Response object
     */
    public function get_draft_content($request) {

        try {
            $page = $request->get_param('page');
            $per_page = min($request->get_param('per_page'), 100); 
            $offset = ($page - 1) * $per_page;

            $filters = [];
            if ($request->get_param('status')) {
                $filters['status'] = $request->get_param('status');
            }
            if ($request->get_param('job_id')) {
                $filters['job_id'] = $request->get_param('job_id');
            }
            if ($request->get_param('product_id')) {
                $filters['product_id'] = $request->get_param('product_id');
            }
            if ($request->get_param('content_type')) {
                $filters['content_type'] = $request->get_param('content_type');
            }

            $draft_content = $this->draft_manager->getDraftContent($filters, $per_page, $offset);
            $total_count = $this->draft_manager->getDraftContentCount($filters);

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'items' => $draft_content,
                    'pagination' => [
                        'page' => $page,
                        'per_page' => $per_page,
                        'total' => $total_count,
                        'total_pages' => ceil($total_count / $per_page),
                    ],
                ],
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error(
                'draft_content_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }

    /**
     * Approve draft content
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error Response object
     */
    public function approve_draft_content($request) {
        try {
            $draft_id = $request->get_param('id');

            $success = $this->draft_manager->approveDraftContent($draft_id);

            if ($success) {
                return new WP_REST_Response([
                    'success' => true,
                    'message' => __('Draft content approved and applied to product successfully.', 'ai-product-tools'),
                ], 200);
            } else {
                return new WP_Error(
                    'approval_failed',
                    __('Failed to approve draft content.', 'ai-product-tools'),
                    ['status' => 500]
                );
            }

        } catch (\Exception $e) {
            return new WP_Error(
                'approval_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }

    /**
     * Reject draft content
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error Response object
     */
    public function reject_draft_content($request) {
        try {
            $draft_id = $request->get_param('id');

            $success = $this->draft_manager->rejectDraftContent($draft_id);

            if ($success) {
                return new WP_REST_Response([
                    'success' => true,
                    'message' => __('Draft content rejected successfully.', 'ai-product-tools'),
                ], 200);
            } else {
                return new WP_Error(
                    'rejection_failed',
                    __('Failed to reject draft content.', 'ai-product-tools'),
                    ['status' => 500]
                );
            }

        } catch (\Exception $e) {
            return new WP_Error(
                'rejection_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }

    /**
     * Bulk approve draft content
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error Response object
     */
    public function bulk_approve_draft_content($request) {
        try {
            $draft_ids = $request->get_param('ids');

            $results = $this->draft_manager->bulkApproveDraftContent($draft_ids);

            $success_count = count(array_filter($results));
            $total_count = count($results);

            return new WP_REST_Response([
                'success' => true,
                'message' => sprintf(
                    /* translators: 1: Number of successfully approved items, 2: Total number of items */
                    __('Bulk approval completed: %1$d of %2$d items approved successfully.', 'ai-product-tools'),
                    $success_count,
                    $total_count
                ),
                'data' => [
                    'results' => $results,
                    'success_count' => $success_count,
                    'total_count' => $total_count,
                ],
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error(
                'bulk_approval_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }

    /**
     * Bulk delete draft content
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error Response object
     */
    public function bulk_delete_draft_content($request) {
        try {
            $draft_ids = $request->get_param('ids');

            $results = $this->draft_manager->bulkDeleteDraftContent($draft_ids);

            $success_count = count(array_filter($results));
            $total_count = count($results);

            return new WP_REST_Response([
                'success' => true,
                'message' => sprintf(
                    /* translators: 1: Number of successfully deleted items, 2: Total number of items */
                    __('Bulk deletion completed: %1$d of %2$d items deleted successfully.', 'ai-product-tools'),
                    $success_count,
                    $total_count
                ),
                'data' => [
                    'results' => $results,
                    'success_count' => $success_count,
                    'total_count' => $total_count,
                ],
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error(
                'bulk_deletion_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }

    /**
     * Delete draft content
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error Response object
     */
    public function delete_draft_content($request) {
        try {
            $draft_id = $request->get_param('id');

            $success = $this->draft_manager->deleteDraftContent($draft_id);

            if ($success) {
                return new WP_REST_Response([
                    'success' => true,
                    'message' => __('Draft content deleted successfully.', 'ai-product-tools'),
                ], 200);
            } else {
                return new WP_Error(
                    'deletion_failed',
                    __('Failed to delete draft content.', 'ai-product-tools'),
                    ['status' => 500]
                );
            }

        } catch (\Exception $e) {
            return new WP_Error(
                'deletion_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }
}
