<?php
/**
 * TitanCart WooCommerce Import REST Controller
 *
 * @package TitanCart\REST\WooImport
 */

namespace TitanCart\REST\WooImport;

use TitanCart\Modules\WooImport\WooImportService;
use WP_REST_Request;
use WP_REST_Response;

defined( 'ABSPATH' ) || exit;

class WooImportController {

    private string $ns = 'titancart/v1';

    public function admin_check(): bool {
        return current_user_can( 'manage_options' );
    }

    public function register_routes(): void {
        register_rest_route( $this->ns, '/woo-import/detect', [
            [ 'methods' => 'GET', 'callback' => [ $this, 'detect' ], 'permission_callback' => [ $this, 'admin_check' ] ],
        ] );

        register_rest_route( $this->ns, '/woo-import/run', [
            [ 'methods' => 'POST', 'callback' => [ $this, 'run' ], 'permission_callback' => [ $this, 'admin_check' ] ],
        ] );

        register_rest_route( $this->ns, '/woo-import/progress', [
            [ 'methods' => 'GET', 'callback' => [ $this, 'progress' ], 'permission_callback' => [ $this, 'admin_check' ] ],
        ] );
    }

    /**
     * GET /woo-import/detect — check for WooCommerce and count entities.
     */
    public function detect( WP_REST_Request $req ): WP_REST_Response {
        $svc = new WooImportService();
        return new WP_REST_Response( $svc->detect() );
    }

    /**
     * POST /woo-import/run — start the import.
     * Body: { entities: ['categories','products','orders',...] }
     */
    public function run( WP_REST_Request $req ): WP_REST_Response {
        $entities = $req->get_param( 'entities' );
        if ( ! is_array( $entities ) || empty( $entities ) ) {
            return new WP_REST_Response( [ 'error' => 'No entities selected.' ], 400 );
        }

        $allowed = [ 'categories', 'tags', 'products', 'customers', 'orders', 'reviews', 'coupons' ];
        $entities = array_intersect( $entities, $allowed );

        $svc    = new WooImportService();
        $result = $svc->run( $entities );

        return new WP_REST_Response( $result );
    }

    /**
     * GET /woo-import/progress — poll import progress.
     */
    public function progress( WP_REST_Request $req ): WP_REST_Response {
        $svc = new WooImportService();
        return new WP_REST_Response( $svc->get_progress() );
    }
}
