<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateSliderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->hasRole('Manager') ?? false;
    }

    public function rules(): array
    {
        return [
            'title'         => ['required', 'string', 'max:191'],
            'image_source'  => ['required', 'in:upload,url'],
            'image_file'    => ['nullable', 'image', 'max:10240', 'mimes:jpeg,png,jpg,gif,webp'],
            'image_url'     => ['nullable', 'url', 'max:500'],
            'status'        => ['required', 'in:published,draft,archived'],
            'order'         => ['nullable', 'integer', 'min:0'],
        ];
    }

    public function messages(): array
    {
        return [
            'image_file.image' => 'The file must be a valid image.',
            'image_file.max' => 'The image must not exceed 10 MB.',
            'image_file.mimes' => 'The image must be JPEG, PNG, GIF, or WebP format.',
            'image_url.url' => 'Please provide a valid URL format (e.g., https://example.com/image.jpg).',
        ];
    }

    protected function prepareForValidation(): void
    {
        // Handle image_source changes
        if ($this->get('image_source') === 'upload') {
            $this->merge(['image_url' => null]);
        } elseif ($this->get('image_source') === 'url') {
            $this->merge(['image_file' => null]);
        }
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            // Only require image if switching to upload mode and no file is provided
            if ($this->get('image_source') === 'upload' && !$this->hasFile('image_file')) {
                $validator->errors()->add('image_file', 'Please upload an image file when using upload mode.');
            } elseif ($this->get('image_source') === 'url' && !$this->filled('image_url')) {
                $validator->errors()->add('image_url', 'Please provide a valid image URL when using URL mode.');
            }
        });
    }
}
