<?php

namespace App\Http\Requests;

use App\Traits\ConvertsBase64ToFiles;
use Illuminate\Foundation\Http\FormRequest;

class CombustibleRequest extends FormRequest
{
    use ConvertsBase64ToFiles;

    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $tipo_hero = $this->input('tipo_hero');
        return [
            'titulo' => 'required|min:3|max:18',
            'eslogan' => 'required|min:3|max:125',
            'descripcion_corto' => 'max:300',
            'descripcion' => 'required|max:300',

            'imagen_hero' => $this->heroRule($tipo_hero),
            'imagen' =>   $this->imageRule(),
            'estado' => 'required',
            'video_url' => [
                $tipo_hero === 2 ? 'required' : 'nullable',
                'url',
                'regex:/^(https?:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_-]+))|(https?:\/\/youtu\.be\/([a-zA-Z0-9_-]+))$/'
            ]

        ];
    }

    protected function prepareForValidation()
    {
        $input = $this->input();

        if ($this->method() !== 'POST') {
            $isBase64 = isImageBase64($input['imagen']);
            if (!$isBase64) {
                unset($input['imagen']);
                $this->replace($input ?? []);
            }


            $isBase64 = isImageBase64($input['imagen_hero']);
            if (!$isBase64) {
                unset($input['imagen_hero']);
                $this->replace($input ?? []);
            }

            $isBase64 = isImageBase64($input['imagen_ficha_tecnica']);
            if (!$isBase64) {
                unset($input['imagen_ficha_tecnica']);
                $this->replace($input ?? []);
            }
        }

        $this->convertBase64ToFiles();
        $this->replace($input ?? []);
    }

    protected function base64FileKeys(): array
    {
        return ['imagen', 'imagen_hero', 'imagen_ficha_tecnica'];
    }

    protected function imageRule()
    {
        $img = $this->method() === 'POST' ? 'required' : 'nullable';
        return [
            $img,
            'image',
            'mimes:png',
            'dimensions:min_width=404,min_height=71'
        ];
    }
    protected function heroRule($tipo)
    {
        $img = $this->method() === 'POST' ? 'required' : 'nullable';
        return [
            $tipo === 1 ? $img : 'nullable',
            'image',
            'mimes:webp,jpg,png',
            'dimensions:min_width=404,min_height=71'
        ];
    }
}
