<?php
/**
 * Input sanitization service
 */
class InputSanitizer {
    /**
     * Sanitize a string input
     */
    public static function sanitizeString($input, $maxLength = 1000) {
        if ($input === null) {
            return '';
        }
        
        // Remove HTML tags and PHP tags
        $clean = strip_tags($input);
        
        // Convert special characters to HTML entities
        $clean = htmlspecialchars($clean, ENT_QUOTES, 'UTF-8');
        
        // Trim whitespace
        $clean = trim($clean);
        
        // Limit length
        if (strlen($clean) > $maxLength) {
            $clean = substr($clean, 0, $maxLength);
        }
        
        return $clean;
    }
    
    /**
     * Sanitize email address
     */
    public static function sanitizeEmail($email) {
        if ($email === null) {
            return '';
        }
        
        $email = trim($email);
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        
        return $email;
    }
    
    /**
     * Validate email address
     */
    public static function validateEmail($email) {
        $email = self::sanitizeEmail($email);
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
    
    /**
     * Sanitize name field
     */
    public static function sanitizeName($name, $maxLength = 100) {
        if ($name === null) {
            return '';
        }
        
        // Allow only letters, spaces, hyphens, and apostrophes
        $name = trim($name);
        $name = preg_replace('/[^a-zA-Z\s\-\'\.]/', '', $name);
        $name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
        
        if (strlen($name) > $maxLength) {
            $name = substr($name, 0, $maxLength);
        }
        
        return $name;
    }
    
    /**
     * Sanitize message/text area
     */
    public static function sanitizeMessage($message, $maxLength = 5000) {
        if ($message === null) {
            return '';
        }
        
        // Remove script tags and potentially dangerous content
        $message = preg_replace('/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/mi', '', $message);
        $message = preg_replace('/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/mi', '', $message);
        $message = preg_replace('/javascript:/i', '', $message);
        $message = preg_replace('/vbscript:/i', '', $message);
        $message = preg_replace('/onload=/i', '', $message);
        $message = preg_replace('/onerror=/i', '', $message);
        $message = preg_replace('/onclick=/i', '', $message);
        
        // Convert newlines to <br> for display (optional)
        $message = nl2br($message);
        
        // Remove remaining HTML tags
        $message = strip_tags($message);
        
        // Convert special characters
        $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
        
        // Trim and limit length
        $message = trim($message);
        if (strlen($message) > $maxLength) {
            $message = substr($message, 0, $maxLength);
        }
        
        return $message;
    }
    
    /**
     * Validate required fields
     */
    public static function validateRequired($data, $requiredFields) {
        $errors = [];
        
        foreach ($requiredFields as $field) {
            if (!isset($data[$field]) || empty(trim($data[$field]))) {
                $errors[$field] = ucfirst($field) . ' is required';
            }
        }
        
        return $errors;
    }
    
    /**
     * Validate field lengths
     */
    public static function validateLengths($data, $lengths) {
        $errors = [];
        
        foreach ($lengths as $field => $maxLength) {
            if (isset($data[$field]) && strlen($data[$field]) > $maxLength) {
                $errors[$field] = ucfirst($field) . ' must be less than ' . $maxLength . ' characters';
            }
        }
        
        return $errors;
    }
    
    /**
     * Sanitize phone number
     */
    public static function sanitizePhone($phone) {
        if ($phone === null) {
            return '';
        }
        
        // Remove all non-digit characters
        $phone = preg_replace('/\D/', '', $phone);
        
        // Ensure it's exactly 10 digits (US format)
        if (strlen($phone) > 10) {
            $phone = substr($phone, 0, 10);
        }
        
        return $phone;
    }
    
    /**
     * Sanitize boolean value
     */
    public static function sanitizeBoolean($value) {
        if ($value === null) {
            return false;
        }
        
        // Convert various boolean representations to actual boolean
        if (is_bool($value)) {
            return $value;
        }
        
        if (is_string($value)) {
            $value = strtolower(trim($value));
            return in_array($value, ['true', '1', 'yes', 'on', 'checked']);
        }
        
        if (is_numeric($value)) {
            return (bool)$value;
        }
        
        return false;
    }
}
