<?php
/**
 * API admin wishlists class.
 *
 * @package SaveToWishlist\Classes\API
 * @since 1.0.0
 */
namespace SaveToWishlist\Classes\API;

use SaveToWishlist\Abstracts\Singleton;
use SaveToWishlist\Classes\Factories\Collections;
use SaveToWishlist\Classes\Factories\Collection;
use SaveToWishlist\Helpers\Helper_Functions;

/**
 * Class API Admin Wishlists
 *
 * This class creates an API for the plugin.
 */
class API_Admin_Wishlists extends Singleton {
    use \SaveToWishlist\Traits\API_Permissions;

    /**
     * The API namespace.
     *
     * @since 1.0.0
     * @access private
     * @var string
     */
    private $api_namespace = 'saveto-wishlist/v1';

    /**
     * Base route.
     *
     * @since 1.0.0
     * @access private
     * @var string
     */
    private $base = 'admin/wishlists';

    /**
     * Run the application.
     *
     * @since 1.0.0
     * @access public
     */
    public function run() {
        // Register the API.
        add_action( 'rest_api_init', array( $this, 'register_api' ) );
    }

    /**
     * Register the API.
     */
    public function register_api() {

        \register_rest_route(
            $this->api_namespace,
            '/' . $this->base,
            array(
                array(
                    'methods'             => \WP_REST_Server::CREATABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'save_collection' ),
                ),
                array(
                    'methods'             => \WP_REST_Server::DELETABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'delete_collection' ),
                ),
            )
        );

        \register_rest_route(
            $this->api_namespace,
            '/' . $this->base . '/collections',
            array(
                array(
                    'methods'             => \WP_REST_Server::READABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'get_all_collections' ),
                ),
            )
        );

        \register_rest_route(
            $this->api_namespace,
            '/' . $this->base . '/collection/(?P<id>\d+)',
            array(
                array(
                    'methods'             => \WP_REST_Server::READABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'get_collection' ),
                ),
            )
        );

        \register_rest_route(
            $this->api_namespace,
            '/' . $this->base . '/items',
            array(
                array(
                    'methods'             => \WP_REST_Server::READABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'get_collection_products' ),
                ),
            )
        );
    }

    /*
    |--------------------------------------------------------------------------
    | REST API callback methods.
    |--------------------------------------------------------------------------
     */

    /**
     * Get all collections.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function get_all_collections( $request ) {
        $params = $request->get_params();

        $collections = Collections::instance()->get_collections( $params );

        return rest_ensure_response( $collections );
    }

    /**
     * Save a collection.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function save_collection( $request ) {
        $params = $request->get_params();

        // Resolve the effective status: use the request value if provided, otherwise fall back
        // to the persisted status for partial updates that omit the status field.
        $status = $params['status'] ?? '';
        if ( '' === $status && ! empty( $params['id'] ) ) {
            $existing = Collections::instance()->get_collection( (int) $params['id'] );
            if ( $existing ) {
                $status = $existing->status ?? '';
            }
        }

        // Prevent adding new products to a draft wishlist. A missing or non-positive
        // id marks the row as a new insert; existing items reference a persisted row.
        if ( 'draft' === $status && ! empty( $params['items'] ) ) {
            foreach ( $params['items'] as $item ) {
                $item_id = isset( $item['id'] ) ? (int) $item['id'] : 0;
                if ( $item_id <= 0 ) {
                    return new \WP_Error(
                        'stwlite_draft_wishlist_items',
                        esc_html__( 'Products cannot be added to a wishlist in draft status.', 'saveto-wishlist-lite-for-woocommerce' ),
                        array( 'status' => 422 )
                    );
                }
            }
        }

        $params['admin_request'] = true;
        $collection              = Collections::instance()->save_collection( $params );

        $response = array(
            'status'  => 'success',
            'message' => esc_html__( 'Collection saved successfully.', 'saveto-wishlist-lite-for-woocommerce' ),
            'data'    => $collection,
        );

        return rest_ensure_response( $response );
    }

    /**
     * Get a collection.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function get_collection( $request ) {
        $params = $request->get_params();

        $collection = Collections::instance()->get_collection( $params['id'] );
        $data       = Collection::get_instance( $collection );

        $data = apply_filters( 'stwlite_single_collection_data', $data );

        $response = array(
            'status'  => 'success',
            'message' => esc_html__( 'Collection fetched successfully.', 'saveto-wishlist-lite-for-woocommerce' ),
            'data'    => $data,
        );

        return rest_ensure_response( $response );
    }

    /**
     * Get collection products.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function get_collection_products( $request ) {
        $params = $request->get_params();

        $items = array();

        $response = array(
            'total'       => 0,
            'currentPage' => 1,
            'data'        => $items,
        );

        return rest_ensure_response( $response );
    }

    /**
     * Delete a collection.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function delete_collection( $request ) {
        $params = $request->get_params();

        $ids     = $params['ids'];
        $deleted = Collections::instance()->delete_collections( $ids );
        $skipped = Collections::instance()->get_skipped_last_wishlist_ids();

        if ( ! empty( $skipped ) && 0 === (int) $deleted ) {
            $message = _n(
                'The user\'s last wishlist cannot be deleted because it would be recreated automatically.',
                'These wishlists cannot be deleted because each is its owner\'s last wishlist and would be recreated automatically.',
                count( $skipped ),
                'saveto-wishlist-lite-for-woocommerce'
            );
        } elseif ( ! empty( $skipped ) ) {
            $message = __( 'Some wishlists were skipped because they are the only wishlist for their owner.', 'saveto-wishlist-lite-for-woocommerce' );
        } else {
            $message = __( 'Collection deleted successfully.', 'saveto-wishlist-lite-for-woocommerce' );
        }

        $response = array(
            'status'  => 'success',
            'message' => $message,
            'count'   => $deleted,
            'skipped' => array_map( 'intval', $skipped ),
        );

        return rest_ensure_response( $response );
    }
}
