<?php

namespace WPVOID\StockBeacon;

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class Settings {
    public static function defaults() : array {
        $defaults = self::free_defaults();
        return $defaults;
    }

    private static function free_defaults() : array {
        $site_title = ( function_exists( 'get_bloginfo' ) ? (string) get_bloginfo( 'name' ) : '' );
        $admin_email = ( function_exists( 'get_option' ) ? sanitize_email( (string) get_option( 'admin_email', '' ) ) : '' );
        return array(
            'plugin_enabled'               => true,
            'form_display_position'        => 'after_price',
            'form_title'                   => 'Notify Me When Available',
            'form_description'             => "Enter your email and we'll let you know when this product is back in stock.",
            'form_button_text'             => 'Notify Me',
            'form_placeholder'             => 'Enter your email address',
            'form_success_message'         => "You're on the list! We'll email you when this item is restocked.",
            'show_waitlist_count'          => true,
            'show_consent_checkbox'        => false,
            'consent_text'                 => 'I agree to receive a one-time restock notification for this product.',
            'form_theme_mode'              => 'light',
            'restock_email_subject'        => '{product_name} is back in stock!',
            'restock_email_heading'        => "Great news - it's back!",
            'restock_email_body'           => 'The product you were waiting for is now available. Grab it before it sells out again!',
            'restock_email_cta_text'       => 'Shop Now',
            'email_accent_color'           => '#2563eb',
            'email_heading_font_size'      => 30,
            'email_body_font_size'         => 16,
            'email_button_font_size'       => 15,
            'email_footer_font_size'       => 12,
            'email_box_shadow_enabled'     => false,
            'auto_remove_on_purchase'      => true,
            'throttle_per_minute'          => 5,
            'restock_subscriber_retention' => 'keep',
            'form_accent_color'            => '#2563eb',
            'form_button_color'            => '#2563eb',
            'form_background_color'        => '#ffffff',
            'form_text_color'              => '#0f172a',
            'form_description_color'       => '#64748b',
            'form_input_background_color'  => '#ffffff',
            'form_count_text_color'        => '#334155',
            'form_box_shadow_enabled'      => true,
            'form_title_font_size'         => 17,
            'form_description_font_size'   => 14,
            'form_input_font_size'         => 16,
            'form_button_font_size'        => 14,
            'form_count_font_size'         => 13,
            'form_success_font_size'       => 15,
            'email_from_name'              => $site_title,
            'email_reply_to'               => $admin_email,
            'delete_data_on_uninstall'     => false,
        );
    }

    public static function get() : array {
        $stored = get_option( 'stockbeacon_settings', null );
        $stored_settings = ( is_array( $stored ) ? $stored : array() );
        $defaults = self::defaults();
        $settings = array_intersect_key( wp_parse_args( $stored_settings, $defaults ), $defaults );
        if ( !array_key_exists( 'email_accent_color', $stored_settings ) || '' === (string) ($settings['email_accent_color'] ?? '') ) {
            $settings['email_accent_color'] = (string) ($settings['form_accent_color'] ?? '#2563eb');
        }
        return $settings;
    }

    public static function update( array $input ) : array {
        $current = self::get();
        $next = array();
        foreach ( self::defaults() as $key => $default ) {
            $value = $input[$key] ?? $current[$key];
            $handled = false;
            if ( !$handled ) {
                $value = self::sanitize_free_value( $key, $value, $default );
            }
            $next[$key] = $value;
        }
        update_option( 'stockbeacon_settings', $next );
        return self::get();
    }

    /**
     * @param mixed $value
     * @param mixed $default
     * @return mixed
     */
    private static function sanitize_free_value( string $key, $value, $default ) {
        if ( is_bool( $default ) ) {
            return (bool) $value;
        }
        if ( is_int( $default ) ) {
            $value = absint( $value );
            $ranges = array(
                'email_heading_font_size'    => array(18, 48),
                'email_body_font_size'       => array(12, 24),
                'email_button_font_size'     => array(12, 22),
                'email_footer_font_size'     => array(10, 16),
                'form_title_font_size'       => array(12, 32),
                'form_description_font_size' => array(11, 24),
                'form_input_font_size'       => array(12, 22),
                'form_button_font_size'      => array(12, 22),
                'form_count_font_size'       => array(10, 18),
                'form_success_font_size'     => array(11, 24),
            );
            if ( isset( $ranges[$key] ) ) {
                $value = min( $ranges[$key][1], max( $ranges[$key][0], $value ) );
            }
            return $value;
        }
        if ( 'form_display_position' === $key ) {
            $value = sanitize_key( (string) $value );
            if ( !in_array( $value, array(
                'before_price',
                'after_price',
                'before_add_to_cart',
                'after_add_to_cart',
                'summary_end'
            ), true ) ) {
                $value = (string) $default;
            }
            return $value;
        }
        if ( 'email_reply_to' === $key ) {
            $value = sanitize_email( (string) $value );
            return ( is_email( $value ) ? $value : '' );
        }
        if ( in_array( $key, array(
            'form_accent_color',
            'form_button_color',
            'form_background_color',
            'form_text_color',
            'form_description_color',
            'form_input_background_color',
            'form_count_text_color',
            'email_accent_color'
        ), true ) ) {
            return ( sanitize_hex_color( (string) $value ) ?: (string) $default );
        }
        $value = sanitize_text_field( (string) $value );
        if ( 'form_theme_mode' === $key && !in_array( $value, array('light', 'dark'), true ) ) {
            $value = 'light';
        }
        if ( 'restock_subscriber_retention' === $key && !in_array( $value, array('keep', 'remove'), true ) ) {
            $value = 'keep';
        }
        return $value;
    }

    private static function encrypt_secret( string $value ) : string {
        if ( '' === $value || !function_exists( 'openssl_encrypt' ) ) {
            return $value;
        }
        try {
            $method = 'AES-256-CBC';
            $key = hash( 'sha256', wp_salt( 'auth' ), true );
            $iv_len = openssl_cipher_iv_length( $method );
            if ( !is_int( $iv_len ) || $iv_len <= 0 ) {
                return $value;
            }
            $iv = random_bytes( $iv_len );
            $enc = openssl_encrypt(
                $value,
                $method,
                $key,
                OPENSSL_RAW_DATA,
                $iv
            );
        } catch ( \Throwable $e ) {
            return $value;
        }
        if ( false === $enc || '' === $enc ) {
            return $value;
        }
        return base64_encode( $iv . $enc );
    }

    private static function decrypt_secret( string $value ) : string {
        if ( '' === $value || !function_exists( 'openssl_decrypt' ) ) {
            return $value;
        }
        $raw = base64_decode( $value, true );
        if ( false === $raw || '' === $raw ) {
            return $value;
        }
        try {
            $method = 'AES-256-CBC';
            $key = hash( 'sha256', wp_salt( 'auth' ), true );
            $iv_len = openssl_cipher_iv_length( $method );
            if ( !is_int( $iv_len ) || $iv_len <= 0 || strlen( $raw ) <= $iv_len ) {
                return $value;
            }
            $iv = substr( $raw, 0, $iv_len );
            $enc = substr( $raw, $iv_len );
            $dec = openssl_decrypt(
                $enc,
                $method,
                $key,
                OPENSSL_RAW_DATA,
                $iv
            );
            return ( false === $dec ? '' : $dec );
        } catch ( \Throwable $e ) {
            return $value;
        }
    }

}
