<?php
/**
 * Security Helper Class
 */

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

class Trstemp_Security {
    
    public static function verify_ajax_nonce($action = 'trstemp_nonce_action') {
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce'] ?? $_GET['nonce'] ?? ''));
        
        if (!wp_verify_nonce($nonce, $action)) {
            wp_send_json_error(esc_html__('Security verification failed', 'turbo-templates-library-for-elementor'));
        }
        
        return true;
    }
    
    public static function check_admin_capability() {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Insufficient permissions', 'turbo-templates-library-for-elementor'));
        }
        
        return true;
    }
    
    public static function sanitize_template_id($template_id) {
        return absint($template_id);
    }
    
    public static function sanitize_customization_data($data) {
        if (!is_array($data)) {
            return array();
        }
        
        $sanitized = array();
        foreach ($data as $key => $value) {
            $key = sanitize_key($key);
            
            if (is_array($value)) {
                $sanitized[$key] = self::sanitize_customization_data($value);
            } elseif (is_string($value)) {
                if (strpos($key, 'color') !== false) {
                    $sanitized[$key] = sanitize_hex_color($value);
                } elseif (strpos($key, 'url') !== false) {
                    $sanitized[$key] = esc_url_raw($value);
                } else {
                    $sanitized[$key] = sanitize_text_field($value);
                }
            } else {
                $sanitized[$key] = $value;
            }
        }
        
        return $sanitized;
    }
    
    public static function escape_output($data, $context = 'html') {
        switch ($context) {
            case 'attr': return esc_attr($data);
            case 'url': return esc_url($data);
            case 'js': return esc_js($data);
            case 'textarea': return esc_textarea($data);
            default: return esc_html($data);
        }
    }
    
    public static function create_nonce($action = 'trstemp_nonce_action') {
        return wp_create_nonce($action);
    }
}
