<?php

namespace MediaTrim\Core;

use MediaTrim\Traits\Singleton;

defined('ABSPATH') || exit;

/**
 * Class SettingsManager
 *
 * Handles plugin settings.
 *
 * @package MediaTrim\Core
 */
class SettingsManager
{
    use Singleton;

    /**
     * Settings option name
     *
     * @var string
     */
    private $settings_option = 'mtrim_settings';

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     */
    public function init_hooks()
    {
        add_action('wp_ajax_mtrim_get_settings', [$this, 'ajax_get_settings']);
        add_action('wp_ajax_mtrim_save_settings', [$this, 'ajax_save_settings']);
    }

    /**
     * AJAX handler to get settings
     */
    public function ajax_get_settings()
    {
        check_ajax_referer('mtrim_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'media-trim')]);
        }

        $settings = get_option($this->settings_option, []);
        wp_send_json_success($settings);
    }

    /**
     * AJAX handler to save settings
     */
    public function ajax_save_settings()
    {
        check_ajax_referer('mtrim_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'media-trim')]);
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON needs to be parsed before sanitization, individual fields are sanitized below.
        $settings_raw = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : '';
        $settings = json_decode($settings_raw, true);

        if ($settings === null) {
            wp_send_json_error(['message' => __('Invalid settings data', 'media-trim')]);
        }

        // Sanitize settings
        $sanitized_settings = [
            'auto_scan' => isset($settings['auto_scan']) ? (bool) $settings['auto_scan'] : false,
            'exclude_paths' => isset($settings['exclude_paths']) ? sanitize_textarea_field($settings['exclude_paths']) : '',
            'duplicate_threshold' => isset($settings['duplicate_threshold']) ? absint($settings['duplicate_threshold']) : 95,
            'trash_retention_days' => isset($settings['trash_retention_days']) ? absint($settings['trash_retention_days']) : 30,
            'pexels_api_key' => isset($settings['pexels_api_key']) ? sanitize_text_field($settings['pexels_api_key']) : '',
        ];

        update_option($this->settings_option, $sanitized_settings);

        wp_send_json_success(['message' => __('Settings saved', 'media-trim')]);
    }
}
