<?php

namespace App\Http\Requests\Partnership;

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

/**
 * Form Request: StorePartnerRequest
 * 
 * Validates partner organization creation and updates.
 */
class StorePartnerRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth()->check() && (
            auth()->user()->can('create partners') ||
            auth()->user()->can('edit partners') ||
            auth()->user()->can('edit own partners')
        );
    }

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

        return [
            'organization_name' => [
                'required',
                'string',
                'max:191',
                Rule::unique('r_partners', 'organization_name')->ignore($partnerId),
            ],
            'legal_name' => ['nullable', 'string', 'max:191'],
            'description' => ['nullable', 'string', 'max:5000'],
            'mission_statement' => ['nullable', 'string', 'max:2000'],
            'email' => ['required', 'email', 'max:191'],
            'phone' => ['nullable', 'string', 'max:50'],
            'website' => ['nullable', 'url', 'max:191'],
            'address_line_1' => ['nullable', 'string', 'max:191'],
            'address_line_2' => ['nullable', 'string', 'max:191'],
            'city' => ['nullable', 'string', 'max:100'],
            'state_province' => ['nullable', 'string', 'max:100'],
            'postal_code' => ['nullable', 'string', 'max:20'],
            'country' => ['nullable', 'string', 'max:100'],
            'organization_type' => [
                'required',
                Rule::in([
                    'government',
                    'ngo',
                    'private_sector',
                    'academic',
                    'healthcare',
                    'international',
                    'community_based',
                    'faith_based',
                    'other',
                ]),
            ],
            'category' => ['nullable', 'string', 'max:191'],
            'logo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp,svg', 'max:2048'],
            'banner_image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:5120'],
            'social_media' => ['nullable', 'array'],
            'social_media.facebook' => ['nullable', 'url', 'max:191'],
            'social_media.twitter' => ['nullable', 'url', 'max:191'],
            'social_media.linkedin' => ['nullable', 'url', 'max:191'],
            'social_media.instagram' => ['nullable', 'url', 'max:191'],
            'partnership_start_date' => ['nullable', 'date'],
            'partnership_end_date' => ['nullable', 'date', 'after:partnership_start_date'],
            'partnership_status' => [
                'sometimes',
                Rule::in(['active', 'inactive', 'pending', 'suspended']),
            ],
            'partnership_level' => [
                'sometimes',
                Rule::in(['bronze', 'silver', 'gold', 'platinum']),
            ],
            'services_offered' => ['nullable', 'array'],
            'services_offered.*' => ['string', 'max:191'],
            'show_in_directory' => ['sometimes', 'boolean'],
            'is_featured' => ['sometimes', 'boolean'],
            'internal_notes' => ['nullable', 'string', 'max:5000'],
            // Contacts
            'contacts' => ['nullable', 'array'],
            'contacts.*.name' => ['required_with:contacts', 'string', 'max:191'],
            'contacts.*.title' => ['nullable', 'string', 'max:191'],
            'contacts.*.email' => ['nullable', 'email', 'max:191'],
            'contacts.*.phone' => ['nullable', 'string', 'max:50'],
            'contacts.*.role' => [
                'nullable',
                Rule::in(['primary_contact', 'executive', 'technical', 'administrative', 'other']),
            ],
            'contacts.*.is_primary' => ['nullable', 'boolean'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'organization_name.required' => 'The organization name is required.',
            'organization_name.unique' => 'An organization with this name already exists.',
            'email.required' => 'A contact email is required.',
            'email.email' => 'Please provide a valid email address.',
            'organization_type.required' => 'Please select the organization type.',
            'website.url' => 'Please provide a valid website URL.',
            'partnership_end_date.after' => 'The partnership end date must be after the start date.',
            'logo.max' => 'The logo cannot exceed 2MB.',
            'banner_image.max' => 'The banner image cannot exceed 5MB.',
            'contacts.*.name.required_with' => 'Contact name is required.',
            'contacts.*.email.email' => 'Please provide a valid email for the contact.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Sanitize organization name
        $this->merge([
            'organization_name' => strip_tags($this->organization_name),
        ]);

        // Set default country
        if (!$this->country) {
            $this->merge(['country' => 'Kenya']);
        }

        // Convert comma-separated services_offered string to array
        if ($this->has('services_offered') && is_string($this->services_offered)) {
            $services = array_filter(array_map('trim', explode(',', $this->services_offered)));
            $this->merge(['services_offered' => array_values($services)]);
        }

        // Normalize checkboxes
        $this->merge([
            'show_in_directory' => $this->boolean('show_in_directory'),
            'is_featured'       => $this->boolean('is_featured'),
        ]);
    }
}
