<?php

namespace WPVOID\StockBeacon\Api;

use WPVOID\StockBeacon\Core\WaitlistManager;
use WPVOID\StockBeacon\Notifications\EmailManager;
use WPVOID\StockBeacon\Settings;
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class SettingsEndpoints extends RestController {
    private EmailManager $email;

    public function __construct( EmailManager $email ) {
        $this->email = $email;
    }

    public function register() : void {
        add_action( 'rest_api_init', function () {
            register_rest_route( 'stockbeacon/v1', '/settings', array(array(
                'methods'             => 'GET',
                'callback'            => array($this, 'get_settings'),
                'permission_callback' => array($this, 'can_manage'),
            ), array(
                'methods'             => 'PUT',
                'callback'            => array($this, 'update_settings'),
                'permission_callback' => array($this, 'can_manage'),
            )) );
            register_rest_route( 'stockbeacon/v1', '/email/test', array(
                'methods'             => 'POST',
                'callback'            => array($this, 'send_test_email'),
                'permission_callback' => array($this, 'can_manage'),
            ) );
        } );
    }

    public function get_settings( \WP_REST_Request $request ) : \WP_REST_Response {
        try {
            return rest_ensure_response( Settings::get() );
        } catch ( \Throwable $e ) {
            $this->log_exception( 'settings_get', $e );
            return rest_ensure_response( Settings::defaults() );
        }
    }

    public function update_settings( \WP_REST_Request $request ) : \WP_REST_Response {
        $params = (array) $request->get_json_params();
        try {
            return rest_ensure_response( Settings::update( $params ) );
        } catch ( \Throwable $e ) {
            $this->log_exception( 'settings_update', $e );
            $merged = array_merge( Settings::defaults(), array_intersect_key( $params, Settings::defaults() ) );
            return rest_ensure_response( $merged );
        }
    }

    /**
     * POST body: { "to": "you@example.com", optional unsaved email/style keys for editor preview.
     */
    public function send_test_email( \WP_REST_Request $request ) {
        $params = (array) $request->get_json_params();
        $to = sanitize_email( (string) ($params['to'] ?? '') );
        if ( '' === $to || !is_email( $to ) ) {
            return new \WP_Error('invalid_email', __( 'Please enter a valid email address.', 'stockbeacon-product-waitlists-for-woocommerce' ), array(
                'status' => 400,
            ));
        }
        $allowed_keys = array(
            'restock_email_subject',
            'restock_email_heading',
            'restock_email_body',
            'restock_email_cta_text',
            'email_accent_color',
            'email_heading_font_size',
            'email_body_font_size',
            'email_button_font_size',
            'email_footer_font_size',
            'email_box_shadow_enabled',
            'form_accent_color'
        );
        $overrides = array();
        foreach ( $allowed_keys as $key ) {
            if ( array_key_exists( $key, $params ) && is_scalar( $params[$key] ) ) {
                $overrides[$key] = $params[$key];
            }
        }
        $email_type = sanitize_key( (string) ($params['email_type'] ?? 'restock') );
        $result = null;
        if ( 'confirmation' === $email_type ) {
        }
        if ( null === $result ) {
            $result = $this->email->send_test_restock_email( $to, $overrides );
        }
        if ( is_wp_error( $result ) ) {
            return $result;
        }
        return rest_ensure_response( array(
            'success' => true,
            'message' => __( 'Test email accepted by WordPress mailer. If it does not arrive, check spam and your SMTP/delivery setup.', 'stockbeacon-product-waitlists-for-woocommerce' ),
        ) );
    }

}
