<?php

namespace App\Http\Requests;

use App\Models\RequestType;
use Illuminate\Foundation\Http\FormRequest;

class StoreMarketingRequestRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->user()->isHarcourtsAdmin() || auth()->user()->isSuperAdmin();
    }

    public function rules(): array
    {
        $requestType = RequestType::find($this->input('request_type_id'));
        $requiresPropertyUrl = $requestType ? $requestType->requires_property_url : true;

        $rules = [
            'request_type_id' => ['required', 'exists:request_types,id'],
            'agent_id' => ['nullable', 'exists:agents,id'],
            'property_address' => ['nullable', 'string', 'max:255'],
            'property_url' => $requiresPropertyUrl ? ['required', 'url', 'max:500'] : ['nullable', 'url', 'max:500'],
            'required_date' => ['required', 'date', 'after_or_equal:today'],
            'required_time' => ['nullable', 'string'],
            'instructions' => ['nullable', 'string', 'max:5000'],
            'priority_override' => ['nullable', 'boolean'],
            'urgent_reason' => ['required_if:priority_override,1', 'nullable', 'string', 'max:1000'],
            'attachments.*' => ['nullable', 'file', 'mimes:pdf,jpg,jpeg,png,doc,docx', 'max:20480'], // Max 20MB
        ];

        if ($requestType && $requestType->supports_campaign_fields) {
            $rules['campaign_platform'] = ['nullable', 'string'];
            $rules['campaign_objective'] = ['nullable', 'string'];
            $rules['campaign_budget'] = ['nullable', 'string'];
            $rules['campaign_start_date'] = ['nullable', 'date'];
            $rules['campaign_end_date'] = ['nullable', 'date'];
            $rules['target_areas'] = ['nullable', 'string'];
            $rules['target_audience_notes'] = ['nullable', 'string'];
            $rules['cta'] = ['nullable', 'string'];
            $rules['ad_copy_required'] = ['nullable'];
            $rules['creative_required'] = ['nullable'];
            $rules['lead_form_required'] = ['nullable'];
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'property_url.required' => 'The Property Listing URL is required for property-related marketing requests.',
            'urgent_reason.required_if' => 'Please provide a reason when overriding priority to Urgent.',
            'attachments.*.mimes' => 'Allowed attachment types: PDF, JPG, JPEG, PNG, DOC, DOCX.',
            'attachments.*.max' => 'Attachment size must not exceed 20MB.',
        ];
    }
}
