<?php
/**
 * Security Trait
 *
 * @package Easy_Invoice
 * @subpackage Traits
 */

namespace EasyInvoice\Traits;

/**
 * SecurityTrait contains methods for handling security checks, nonce verification, and capability checks
 */
trait SecurityTrait {
    /**
     * Verify nonce for AJAX requests
     * 
     * @param string $nonce The nonce to verify
     * @param string $action The nonce action
     * @return bool|WP_Error True if verified, WP_Error otherwise
     */
    protected function verifyNonce($nonce, $action = 'easy_invoice_nonce') {
        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            return new \WP_Error('invalid_nonce', __('Security verification failed. Please refresh the page and try again.', 'easy-invoice'));
        }
        
        return true;
    }
    
    /**
     * Check if current user has required capability
     * 
     * @param string $capability The required capability, defaults to manage_options
     * @return bool|WP_Error True if has capability, WP_Error otherwise
     */
    protected function checkCapability($capability = 'manage_options') {
        if (!current_user_can($capability)) {
            return new \WP_Error('invalid_capability', __('You do not have permission to perform this action.', 'easy-invoice'));
        }
        
        return true;
    }
    
    /**
     * Common security check for AJAX requests
     * 
     * @param string $nonce The nonce to verify
     * @param string $nonce_action The nonce action
     * @param string $capability The required capability
     * @return bool|WP_Error True if checks pass, WP_Error otherwise
     */
    protected function securityCheck($nonce, $nonce_action = 'easy_invoice_nonce', $capability = 'manage_options') {
        // Check nonce
        $nonce_check = $this->verifyNonce($nonce, $nonce_action);
        if (is_wp_error($nonce_check)) {
            return $nonce_check;
        }
        
        // Check capability
        $cap_check = $this->checkCapability($capability);
        if (is_wp_error($cap_check)) {
            return $cap_check;
        }
        
        return true;
    }
    
    /**
     * Handle AJAX security check and send error response if needed
     * 
     * @param string $nonce The nonce to verify
     * @param string $nonce_action The nonce action
     * @param string $capability The required capability
     * @return bool True if checks pass, false otherwise (and sends JSON error)
     */
    protected function handleAjaxSecurity($nonce, $nonce_action = 'easy_invoice_nonce', $capability = 'manage_options') {
        $security_check = $this->securityCheck($nonce, $nonce_action, $capability);
        
        if (is_wp_error($security_check)) {
            wp_send_json_error([
                'message' => $security_check->get_error_message(),
                'code' => $security_check->get_error_code()
            ]);
            return false;
        }
        
        return true;
    }
} 