<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Support\Formatter;
use RuntimeException;

class UploadRequest extends FormRequest
{
    public function __construct(Formatter $formatter)
    {
        $this->formatter = $formatter;
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        if (!is_array($this->fileList)) {
            return;
        }
        $sanitizedFiles = [];
        foreach($this->fileList as $file) {
            $sanitizedFiles[] = [
                'name' => $this->formatter->transformItem($file['name'], 'strip_tags|xss_clean'),
                'size' => $file['size'],
                'type' => $file['type'],
                'galleryUid'
            ];
        }
        $this->merge([
            'fileList' => $sanitizedFiles
        ]);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'fileList' => 'array|required',
            'fileList.*.name' => 'required|max:255',
            'fileList.*.size' => 'required|int',
            'galleryUid' => 'required|alpha_num|max:32',
        ];
    }
}
