<?php

namespace PhotoSphereViewer\Includes;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Manages enable/disable state for Elementor widgets registered by this plugin.
 *
 * - Stores user preferences in a single option: psv_widget_settings
 * - Exposes static helper is_widget_enabled() used at registration time
 * - Registers AJAX endpoints for the admin React UI
 *
 * @package photo-sphere-viewer
 */
class WidgetSettings {

    const OPTION_KEY = 'psv_widget_settings';

    /**
     * Default enabled state for every widget.
     *
     * Keys must match Elementor widget get_name() values.
     */
    public static function get_defaults() {
        return [
            'photo-sphere-viewer' => true,
            'psv-virtual-tour'    => true,
            'psv-video-360'       => true,
            'psv-ar-3d-viewer'    => true,
        ];
    }

    /**
     * Metadata for each widget (label, description, freemium flag).
     *
     * Returned to the admin UI so the React layer stays declarative.
     */
    public static function get_widgets_meta() {
        return [
            [
                'key'         => 'photo-sphere-viewer',
                'label'       => __('Photo Sphere Viewer', 'photo-sphere-viewer'),
                'description' => __('Classic 360° panorama viewer for Elementor.', 'photo-sphere-viewer'),
                'tier'        => 'free',
            ],
            [
                'key'         => 'psv-virtual-tour',
                'label'       => __('Virtual Tour', 'photo-sphere-viewer'),
                'description' => __('Link multiple panoramas together to create a guided walk-through.', 'photo-sphere-viewer'),
                'tier'        => 'freemium',
            ],
            [
                'key'         => 'psv-video-360',
                'label'       => __('360° Video', 'photo-sphere-viewer'),
                'description' => __('Embed immersive 360° video with playback controls.', 'photo-sphere-viewer'),
                'tier'        => 'freemium',
            ],
            [
                'key'         => 'psv-ar-3d-viewer',
                'label'       => __('AR 3D Viewer', 'photo-sphere-viewer'),
                'description' => __('Interactive 3D model viewer with AR support (glb / gltf).', 'photo-sphere-viewer'),
                'tier'        => 'freemium',
            ],
        ];
    }

    public function __construct() {
        add_action('wp_ajax_psv_get_widget_settings', [$this, 'ajax_get_settings']);
        add_action('wp_ajax_psv_save_widget_settings', [$this, 'ajax_save_settings']);
    }

    /**
     * Retrieve current settings, merged with defaults so new widgets are
     * treated as enabled by default when the option has not yet been saved.
     */
    public static function get_settings() {
        $saved = get_option(self::OPTION_KEY, []);
        if (!is_array($saved)) {
            $saved = [];
        }
        return array_merge(self::get_defaults(), $saved);
    }

    /**
     * Is the given widget enabled? Consumed by init_widgets() at registration.
     */
    public static function is_widget_enabled($widget_key) {
        $settings = self::get_settings();
        return !empty($settings[$widget_key]);
    }

    public function ajax_get_settings() {
        check_ajax_referer('psv_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'photo-sphere-viewer'));
        }

        wp_send_json_success([
            'settings' => self::get_settings(),
            'widgets'  => self::get_widgets_meta(),
        ]);
    }

    public function ajax_save_settings() {
        check_ajax_referer('psv_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'photo-sphere-viewer'));
        }

        $raw = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : '';
        if (is_string($raw)) {
            $decoded = json_decode($raw, true);
            if (is_array($decoded)) {
                $raw = $decoded;
            }
        }

        if (!is_array($raw)) {
            wp_send_json_error(__('Invalid settings payload', 'photo-sphere-viewer'));
        }

        $defaults  = self::get_defaults();
        $sanitized = [];
        foreach ($defaults as $key => $default_value) {
            $sanitized[$key] = !empty($raw[$key]);
        }

        update_option(self::OPTION_KEY, $sanitized);

        wp_send_json_success([
            'message'  => __('Widget settings saved', 'photo-sphere-viewer'),
            'settings' => $sanitized,
        ]);
    }
}
