<?php

namespace App\Http\Requests;

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

/**
 * UpdateHealthInstitutionRequest
 *
 * Validates health institution update data.
 * Only Health Marketors who own the institution can update.
 *
 * Requirements: 1.5, 10.1
 */
class UpdateHealthInstitutionRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $institution = $this->route('institution');
        
        // Allow admins
        if (auth()->user()->hasAnyRole(['Super Manager', 'Manager'])) {
            return true;
        }

        // Allow owner (Health Marketor)
        return $institution && $institution->isOwnedBy(auth()->user());
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $institution = $this->route('institution');

        return [
            // Basic Information
            'name' => [
                'sometimes',
                'required',
                'string',
                'max:191',
                'min:3',
            ],
            'short_name' => [
                'nullable',
                'string',
                'max:100',
            ],
            'logo' => [
                'nullable',
                'image',
                'mimes:jpeg,jpg,png,webp,svg',
                'max:2048',
            ],

            // Location Information
            'city' => [
                'sometimes',
                'required',
                'string',
                'max:100',
            ],
            'address' => [
                'sometimes',
                'required',
                'string',
                'max:191',
            ],
            'country' => [
                'sometimes',
                'required',
                'string',
                'max:100',
            ],

            // Contact Information
            'email' => [
                'sometimes',
                'required',
                'email',
                'max:191',
            ],
            'phone' => [
                'sometimes',
                'required',
                'string',
                'max:50',
                'regex:/^[+]?[0-9\s\-\(\)]{7,20}$/',
            ],
            'website_url' => [
                'nullable',
                'url',
                'max:191',
            ],

            // Content
            'description' => [
                'sometimes',
                'required',
                'string',
                'min:50',
                'max:5000',
            ],
            'services' => [
                'nullable',
                'array',
            ],
            'services.*' => [
                'string',
                'max:191',
            ],

            // Images
            'images' => [
                'nullable',
                'array',
                'max:10',
            ],
            'images.*' => [
                'image',
                'mimes:jpeg,jpg,png,webp',
                'max:2048',
            ],

            // Status (Admin only)
            'listing_status' => [
                'sometimes',
                Rule::in(['draft', 'pending_payment', 'published', 'paused', 'expired', 'suspended']),
            ],
            'payment_status' => [
                'sometimes',
                Rule::in(['pending', 'paid', 'overdue', 'exempt']),
            ],

            // Admin Assignment
            'user_id' => [
                'sometimes',
                'nullable',
                'exists:users,id',
            ],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'name.required' => 'The institution name is required.',
            'city.required' => 'Please select a city.',
            'email.required' => 'A contact email is required.',
            'email.email' => 'Please enter a valid email address.',
            'phone.required' => 'A phone number is required.',
            'phone.regex' => 'Please enter a valid phone number.',
            'description.min' => 'Please provide a more detailed description.',
            'images.max' => 'You can upload a maximum of 10 images.',
            'images.*.max' => 'Each image must not exceed 2MB.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Sanitize text inputs
        if ($this->has('name')) {
            $this->merge(['name' => strip_tags($this->name)]);
        }
        if ($this->has('description')) {
            $this->merge(['description' => strip_tags($this->description, '<p><br><strong><em><ul><ol><li>')]);
        }

        // Normalize phone number
        if ($this->phone) {
            $this->merge([
                'phone' => preg_replace('/[^0-9+]/', '', $this->phone),
            ]);
        }
    }
}
