<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * 
     * Requires "edit users" permission.
     */
    public function authorize(): bool
    {
        return $this->user()->can('edit users');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique('users')->ignore($this->route('user'))
            ],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
            'roles' => ['required', 'array', 'min:1'],
            'roles.*' => ['exists:roles,name'],
            'is_active' => ['boolean'],
        ];
    }

    /**
     * Get custom error messages for validation rules.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'name.required' => 'The name field is required.',
            'name.max' => 'The name may not be greater than 255 characters.',
            'email.required' => 'The email field is required.',
            'email.email' => 'Please enter a valid email address.',
            'email.unique' => 'This email address is already registered.',
            'password.min' => 'The password must be at least 8 characters.',
            'password.confirmed' => 'The password confirmation does not match.',
            'roles.required' => 'At least one role must be assigned.',
            'roles.min' => 'At least one role must be assigned.',
            'roles.*.exists' => 'The selected role is invalid.',
        ];
    }

    /**
     * Prepare the data for validation.
     * Sanitize input to prevent XSS attacks.
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'name' => $this->sanitizeInput($this->name ?? ''),
            'email' => $this->sanitizeInput($this->email ?? ''),
        ]);
    }

    /**
     * Sanitize input to prevent XSS attacks.
     * 
     * @param string $input
     * @return string
     */
    private function sanitizeInput(string $input): string
    {
        // Remove HTML tags
        $sanitized = strip_tags($input);
        
        // Remove potentially dangerous characters and sequences
        $sanitized = str_replace(['<', '>', '"', "'", '&'], '', $sanitized);
        
        // Remove javascript: and data: protocols
        $sanitized = preg_replace('/javascript:/i', '', $sanitized);
        $sanitized = preg_replace('/data:/i', '', $sanitized);
        
        // Remove event handlers (onclick, onload, etc.)
        $sanitized = preg_replace('/on\w+\s*=/i', '', $sanitized);
        
        // Trim whitespace
        return trim($sanitized);
    }
}
