<?php
/**
 * Coupon Generator Storage REST Controller
 *
 * Handles permanent storage of AI-generated coupon templates to files.
 *
 * @package SAAI\REST
 */

namespace SAAI\REST;

defined( 'ABSPATH' ) || exit;

use SAAI\Abstracts\Abstract_REST;
use SAAI\Traits\ACFWP_Check_Trait;
use SAAI\Traits\Singleton_Trait;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * Coupon_Generator_Storage class.
 *
 * @since 1.1.4
 */
class Coupon_Generator_Storage extends Abstract_REST {

    use Singleton_Trait;
    use ACFWP_Check_Trait;

    /**
     * Holds the class instance object.
     *
     * @var Coupon_Generator_Storage $instance object
     */
    protected static $instance;

    /**
     * The REST base path.
     *
     * @var string
     */
    protected $rest_base = 'coupon-generator-ai';

    /**
     * Register REST API routes.
     */
    public function register_routes() {
        // POST /storeagent-ai/v1/coupon-generator/save.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/save",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'save_template' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );

        // GET /storeagent-ai/v1/coupon-generator/saved.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/saved",
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'list_templates' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );

        // GET /storeagent-ai/v1/coupon-generator/saved/:id.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/saved/(?P<id>[a-zA-Z0-9_-]+)",
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_template' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );

        // DELETE /storeagent-ai/v1/coupon-generator/saved/:id.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/saved/(?P<id>[a-zA-Z0-9_-]+)",
            array(
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => array( $this, 'delete_template' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );
    }

    /**
     * Save AI-generated template permanently.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response or error.
     */
    public function save_template( $request ) {
        // Check if ACFWP Premium is active.
        if ( ! $this->is_acfwp_premium_active() ) {
            return new WP_Error(
                'premium_required',
                __( 'Advanced Coupons Premium is required to save AI templates.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 403 )
            );
        }

        // Delegate to ACFWP Premium plugin.
        if ( class_exists( '\ACFWP\Models\Coupon_Generator_Template_Manager' ) ) {
            // Get template from transient.
            $user_id       = get_current_user_id();
            $transient_key = Coupon_Generator_AI::TRANSIENT_PREFIX . $user_id;
            $template_data = get_transient( $transient_key );

            if ( false === $template_data ) {
                return new WP_Error(
                    'no_template',
                    __( 'No AI-generated template found to save.', 'storeagent-ai-for-woocommerce' ),
                    array( 'status' => 404 )
                );
            }

            $custom_name = sanitize_text_field( $request->get_param( 'name' ) );
            $prompt      = $request->get_param( 'prompt' ) ? sanitize_textarea_field( $request->get_param( 'prompt' ) ) : '';

            $template_id = \ACFWP\Models\Coupon_Generator_Template_Manager::save_template( $template_data, $prompt, $custom_name );

            if ( ! $template_id ) {
                return new WP_Error( 'save_failed', __( 'Failed to save template.', 'storeagent-ai-for-woocommerce' ) );
            }

            return rest_ensure_response(
                array(
                    'success'     => true,
                    'template_id' => $template_id,
                    'message'     => __( 'Template saved successfully.', 'storeagent-ai-for-woocommerce' ),
                )
            );
        }

        return new WP_Error(
            'service_unavailable',
            __( 'Template storage service is not available.', 'storeagent-ai-for-woocommerce' ),
            array( 'status' => 503 )
        );
    }

    /**
     * List all saved AI templates for current user.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response Response.
     */
    public function list_templates( $request ) {
        if ( ! $this->is_acfwp_premium_active() ) {
            return rest_ensure_response(
                array(
                    'success'   => true,
                    'templates' => array(),
                )
            );
        }

        // Delegate to ACFWP Premium plugin.
        if ( class_exists( '\ACFWP\Models\Coupon_Generator_Template_Manager' ) ) {
            $templates = \ACFWP\Models\Coupon_Generator_Template_Manager::list_templates();

            return rest_ensure_response(
                array(
                    'success'   => true,
                    'templates' => $templates,
                )
            );
        }

        return rest_ensure_response(
            array(
                'success'   => true,
                'templates' => array(),
            )
        );
    }

    /**
     * Get single saved template by ID.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response or error.
     */
    public function get_template( $request ) {
        if ( ! $this->is_acfwp_premium_active() ) {
            return new WP_Error(
                'premium_required',
                __( 'Advanced Coupons Premium is required to access saved templates.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 403 )
            );
        }

        // Delegate to ACFWP Premium plugin.
        if ( class_exists( '\ACFWP\Models\Coupon_Generator_Template_Manager' ) ) {
            $id       = $request['id'];
            $template = \ACFWP\Models\Coupon_Generator_Template_Manager::get_template( $id );

            if ( ! $template ) {
                return new WP_Error(
                    'not_found',
                    __( 'Template not found.', 'storeagent-ai-for-woocommerce' ),
                    array( 'status' => 404 )
                );
            }

            // Use Template_Processor for consistency with existing flow.
            if ( class_exists( '\ACFWF\Models\REST_API\Template_Processor' ) ) {
                $processor = new \ACFWF\Models\REST_API\Template_Processor(
                    \ACFWF()->Plugin_Constants,
                    \ACFWF()->Helper_Functions
                );
                $processed = $processor->process_template( $template['template_data'] );
            } else {
                $processed = $template['template_data'];
            }

            return rest_ensure_response(
                array(
                    'success' => true,
                    'data'    => $processed,
                )
            );
        }

        return new WP_Error(
            'service_unavailable',
            __( 'Template storage service is not available.', 'storeagent-ai-for-woocommerce' ),
            array( 'status' => 503 )
        );
    }

    /**
     * Delete saved template.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response or error.
     */
    public function delete_template( $request ) {
        if ( ! $this->is_acfwp_premium_active() ) {
            return new WP_Error(
                'premium_required',
                __( 'Advanced Coupons Premium is required to delete saved templates.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 403 )
            );
        }

        // Delegate to ACFWP Premium plugin.
        if ( class_exists( '\ACFWP\Models\Coupon_Generator_Template_Manager' ) ) {
            $id     = $request['id'];
            $result = \ACFWP\Models\Coupon_Generator_Template_Manager::delete_template( $id );

            if ( ! $result ) {
                return new WP_Error( 'delete_failed', __( 'Failed to delete template.', 'storeagent-ai-for-woocommerce' ) );
            }

            return rest_ensure_response( array( 'success' => true ) );
        }

        return new WP_Error(
            'service_unavailable',
            __( 'Template storage service is not available.', 'storeagent-ai-for-woocommerce' ),
            array( 'status' => 503 )
        );
    }
}
