<?php

namespace App\Http\Requests\Mentorship;

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

class CategoryRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $categoryId = $this->route('category')?->id;

        $rules = [
            'name' => [
                'required',
                'string',
                'max:191',
                'min:2',
            ],
            'slug' => [
                'nullable',
                'string',
                'max:191',
                Rule::unique('mentorship_categories', 'slug')->ignore($categoryId),
            ],
            'description' => [
                'nullable',
                'string',
                'max:5000',
            ],
            'parent_id' => [
                'nullable',
                'exists:mentorship_categories,id',
                function ($attribute, $value, $fail) use ($categoryId) {
                    // Prevent setting self as parent
                    if ($value == $categoryId) {
                        $fail('A category cannot be its own parent.');
                    }
                    // Prevent circular reference (would need more complex check for deep hierarchies)
                },
            ],
            'is_active' => [
                'boolean',
            ],
            'sort_order' => [
                'nullable',
                'integer',
                'min:0',
                'max:9999',
            ],
            'icon' => [
                'nullable',
                'string',
                'max:100',
            ],
            'color' => [
                'nullable',
                'string',
                'max:20',
            ],
            'image_path' => [
                'nullable',
                'string',
                'max:500',
            ],
            'meta_title' => [
                'nullable',
                'string',
                'max:191',
            ],
            'meta_description' => [
                'nullable',
                'string',
                'max:500',
            ],
        ];

        return $rules;
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'name.required' => 'The category name is required.',
            'name.min' => 'The category name must be at least 2 characters.',
            'name.max' => 'The category name may not be greater than 191 characters.',
            'slug.unique' => 'This slug is already in use. Please choose a different one.',
            'parent_id.exists' => 'The selected parent category does not exist.',
            'sort_order.min' => 'The sort order must be at least 0.',
            'sort_order.max' => 'The sort order cannot exceed 9999.',
            'icon.max' => 'The icon class may not be greater than 100 characters.',
            'color.max' => 'The color value may not be greater than 20 characters.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'is_active' => $this->boolean('is_active'),
        ]);

        // Set default sort order if not provided
        if (!$this->has('sort_order')) {
            $this->merge(['sort_order' => 0]);
        }
    }

    /**
     * Get validated data with additional processing.
     */
    public function validated($key = null, $default = null): array
    {
        $validated = parent::validated($key, $default);

        // XSS Prevention
        $textFields = ['name', 'description'];
        foreach ($textFields as $field) {
            if (isset($validated[$field])) {
                $validated[$field] = strip_tags($validated[$field], '<p><br><strong><em><u><ol><ul><li><a>');
            }
        }

        return $validated;
    }
}
