<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Carbon\Carbon;

class CampaignStoreRequest 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.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'campaignName' => ['required', 'string', 'max:255'],
            'startDate' => ['required', 'date', function ($attribute, $value, $fail) {
                // Allow current date and future dates
                $startDate = \Carbon\Carbon::parse($value)->startOfDay();
                $today = \Carbon\Carbon::today()->startOfDay();

                if ($startDate->lt($today)) {
                    $fail('Start date cannot be in the past.');
                }
            }],
            'endDate' => ['required', 'date', 'after_or_equal:startDate'],
            'description' => ['nullable', 'string', 'max:1000'],
            'selectedAccounts' => ['required', 'array', 'min:1'],
            'selectedAccounts.*.id' => ['integer', 'exists:social_accounts,id'],

            'accounts' => ['required', 'array', 'min:1'],
            'accounts.*.account_id' => ['integer', 'exists:social_accounts,id'],
            'accounts.*.platform_id' => ['integer', 'exists:platforms,id'],
            'accounts.*.post_type' => ['string'],

            'postTypes' => ['required', 'array'],
            'postTypes.*' => ['string'],

            'content' => ['required', 'string'],

            'files' => ['nullable', 'array'],
            'files.*.id' => ['nullable'],
            'files.*.title' => ['required', 'string'],
            'files.*.type' => ['required', 'string'],
            'files.*.thumbnail' => ['nullable', 'string'],
            'files.*.caption' => ['nullable', 'string'],
            'files.*.alt' => ['nullable', 'string'],
            'files.*.order' => ['nullable', 'integer'],
            'files.*.isVideo' => ['nullable', 'boolean'],

            'links' => ['nullable', 'array'],
            'links.*.url' => ['required'],
            'links.*.id' => ['nullable'],

            'is_scheduled' => ['required', 'in:0,1,true,false'],
            'scheduled_time' => ['nullable', 'date', function ($attribute, $value, $fail) {
                // Only validate future date if actually scheduling (not immediate post or draft)
                // Check if is_scheduled is truthy (handles both boolean true and string "1")
                $isScheduled = in_array($this->input('is_scheduled'), [true, 1, "1", "true"], true);
                $isDraft = in_array($this->input('is_draft'), [true, 1, "1", "true"], true);

                if ($isScheduled && !$isDraft && $value) {
                    try {
                        // Parse the scheduled time and convert to UTC for comparison
                        $scheduledTime = \Carbon\Carbon::parse($value)->utc();

                        // Get current time in UTC for fair comparison
                        $now = \Carbon\Carbon::now()->utc()->subMinutes(5); // Allow 5 minute tolerance

                        if ($scheduledTime->lt($now)) {
                            $fail("The scheduled time cannot be in the past. Received: {$value} (UTC: {$scheduledTime->format('Y-m-d H:i:s')}), Current UTC: {$now->format('Y-m-d H:i:s')}");
                        }
                    } catch (\Exception $e) {
                        $fail('Invalid date format for scheduled time.');
                    }
                }
            }],
            'is_draft' => ['required', 'in:0,1,true,false'],
        ];
    }

    public function messages(): array
    {
        return [
            'campaignName.required' => 'Campaign name is required.',
            'campaignName.string' => 'Campaign name must be a valid text string.',
            'campaignName.max' => 'Campaign name cannot exceed 255 characters.',

            'startDate.required' => 'Start date is required.',
            'startDate.date' => 'Start date must be a valid date.',
            'startDate.after_or_equal' => 'Start date cannot be in the past.',

            'endDate.required' => 'End date is required.',
            'endDate.date' => 'End date must be a valid date.',
            'endDate.after_or_equal' => 'End date must be after or equal to start date.',

            'description.string' => 'Description must be a valid text string.',
            'description.max' => 'Description cannot exceed 1000 characters.',

            'selectedAccounts.required' => 'At least one account must be selected.',
            'selectedAccounts.array' => 'Selected accounts must be an array.',
            'selectedAccounts.*.id.integer' => 'Selected account ID must be an integer.',
            'selectedAccounts.*.id.exists' => 'One or more selected accounts are invalid.',

            'accounts.required' => 'At least one account must be selected for the post.',
            'accounts.array' => 'Accounts must be provided as an array.',
            'accounts.*.account_id.required' => 'Each account must have an account ID.',
            'accounts.*.account_id.integer' => 'Account ID must be an integer.',
            'accounts.*.account_id.exists' => 'One or more selected accounts are invalid.',

            'accounts.*.platform_id.required' => 'Each account must have a platform ID.',
            'accounts.*.platform_id.integer' => 'Platform ID must be an integer.',
            'accounts.*.platform_id.exists' => 'One or more selected platforms are invalid.',

            'accounts.*.post_type.required' => 'Each account must include a post type.',
            'accounts.*.post_type.string' => 'Post type must be a valid string.',

            'postTypes.required' => 'At least one post type is required.',
            'postTypes.array' => 'Post types must be an array.',
            'postTypes.*.string' => 'Each post type must be a string.',

            'content.required' => 'Content is required for your post.',
            'content.string' => 'Content must be a valid text string.',

            'files.array' => 'Files must be provided as an array.',
            'files.*.title.required' => 'Each file must have a title.',
            'files.*.title.string' => 'File title must be a string.',
            'files.*.type.required' => 'Each file must have a type.',
            'files.*.caption.string' => 'File caption must be a string.',

            'links.array' => 'Links must be provided as an array.',
            'links.*.url.required' => 'Each link must include a URL.',

            'is_scheduled.required' => 'The scheduled status is required.',
            'is_scheduled.boolean' => 'The scheduled status must be true or false.',

            'scheduled_time.date' => 'Scheduled time must be a valid date.',
            'scheduled_time.after_or_equal' => 'Scheduled time cannot be in the past.',

            'is_draft.required' => 'The draft status is required.',
            'is_draft.boolean' => 'The draft status must be true or false.',
        ];
    }

}
