<?php

defined( 'ABSPATH' ) or die( 'Forbidden' );

/**
 * Safe option storage helpers (JSON, not PHP serialize).
 *
 * Extracted from SCPWOO_States_Places to keep the main class lean.
 */
class SCPWOO_Options {

    /**
     * Read a plugin option stored as JSON.
     *
     * Backward-compatible: if the value is still a PHP-serialized array
     * (legacy data), it is returned as-is so existing installs keep working.
     * New writes always use JSON via update_json_option().
     *
     * @param string $key     Option name.
     * @param array  $default Default value.
     * @return array
     */
    public static function get_json_option( string $key, array $default = array() ): array {
        $raw = get_option( $key, null );
        if ( $raw === null || $raw === '' || $raw === false ) {
            return $default;
        }
        // Already an array (legacy serialized by WP) — return as-is
        if ( is_array( $raw ) ) {
            return $raw;
        }
        // JSON string (new format)
        if ( is_string( $raw ) ) {
            $decoded = json_decode( $raw, true );
            return is_array( $decoded ) ? $decoded : $default;
        }
        return $default;
    }

    /**
     * Store a plugin option as a JSON string.
     *
     * This avoids PHP's unserialize() when the data is read back,
     * eliminating object injection risks.
     *
     * @param string $key  Option name.
     * @param array  $data Data to store.
     * @return bool
     */
    public static function update_json_option( string $key, array $data ): bool {
        return update_option( $key, wp_json_encode( $data ) );
    }
}
