<?php

namespace WeDevs\AppBridge\Integrations\WooCommerce\REST;

use WP_REST_Server;
use WP_REST_Controller;

/**
 * Class RestController
 * Dedicated REST controller for WooCommerce Product Add-Ons endpoints.
 */
class AddOnsController extends WP_REST_Controller {
    /**
     * Endpoint namespace
     *
     * @var string
     */
    protected $namespace = 'app-bridge/v1';

    /**
     * Base path used by this controller
     *
     * @var string
     */
    protected $rest_base = 'pocket-store';

    public function __construct() {
        $this->register_routes();
    }

    /**
     * Register routes
     *
     * @return void
     */
    public function register_routes() {
        // POST /app-bridge/v1/pocket-store/addons/file-upload
        register_rest_route(
            $this->namespace, '/' . $this->rest_base . '/addons/file-upload', [
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [ $this, 'upload_addon_file' ],
                    'permission_callback' => '__return_true',
                ],
            ],
        );
    }

    /**
     * Upload a file for WooCommerce Product Add-Ons
     *
     * Route: POST /app-bridge/v1/pocket-store/addons/file-upload
     * Payload: multipart/form-data with a single field named "file"
     *
     * Uses WC_Product_Addons_Field_File_Upload::handle_upload to process
     * the file and returns the $upload array from wp_handle_upload
     * (file, url, type) or a WP_Error on failure.
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response|\WP_Error
     */
    public function upload_addon_file( $request ) {
        // Ensure a file was uploaded with the expected field name.
        $files = $request->get_file_params();
        if ( empty( $files ) || empty( $files['file'] ) || empty( $files['file']['name'] ) ) {
            return new \WP_Error( 'dokan_cart_rest_no_file', __( 'No file uploaded. The payload must include a field named "file".', 'app-bridge' ), [ 'status' => 400 ] );
        }

        // Ensure dependencies are available.
        if ( ! class_exists( 'WC_Product_Addons_Field' ) ) {
            $abstract_path = WP_PLUGIN_DIR . '/woocommerce-product-addons/includes/fields/abstract-wc-product-addons-field.php';
            if ( file_exists( $abstract_path ) ) {
                include_once $abstract_path;
            }
        }

        if ( ! class_exists( 'WC_Product_Addons_Field' ) ) {
            return new \WP_Error( 'dokan_cart_rest_dependency_missing', __( 'Required dependency not found: WC_Product_Addons_Field.', 'app-bridge' ), [ 'status' => 500 ] );
        }

        if ( ! class_exists( 'WC_Product_Addons_Field_File_Upload' ) ) {
            $class_path = WP_PLUGIN_DIR . '/woocommerce-product-addons/includes/fields/class-wc-product-addons-field-file-upload.php';
            if ( file_exists( $class_path ) ) {
                include_once $class_path;
            }
        }

        if ( ! class_exists( 'WC_Product_Addons_Field_File_Upload' ) ) {
            return new \WP_Error( 'dokan_cart_rest_dependency_missing', __( 'Required dependency not found: WC_Product_Addons_Field_File_Upload.', 'app-bridge' ), [ 'status' => 500 ] );
        }

        // Instantiate the field class (constructor expects an $addon array but
        // handle_upload does not depend on it). Provide minimal defaults.
        $field_instance = new \WC_Product_Addons_Field_File_Upload(
            [
                'name'         => 'File Upload',
                'field_name'   => 'file',
                'type'         => 'file_upload',
                'adjust_price' => '0',
                'price'        => '0',
                'price_type'   => 'flat_fee',
            ],
            '',
            false
        );

        // Delegate to the official handler used by WooCommerce Product Add-Ons.
        $upload = $field_instance->handle_upload( $_FILES['file'] ); // phpcs:ignore

        // If there is an error, return it as WP_Error. Otherwise return the upload array.
        if ( is_array( $upload ) && ! empty( $upload['error'] ) ) {
            return new \WP_Error( 'dokan_cart_rest_file_upload_error', $upload['error'], [ 'status' => 400 ] );
        }

        return rest_ensure_response( $upload );
    }
}
