<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class AdditionalRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true; // Izinkan akses request
    }

    public function rules(): array
    {
        return [
            'nama'  => 'required|string|min:3|max:100',
            'harga' => 'required|numeric|min:0',
        ];
    }

    public function messages(): array
    {
        return [
            'required' => 'Kolom :attribute wajib diisi.',
            'numeric'  => ':attribute harus berupa angka.',
            'string'   => 'Input :attribute harus berupa teks valid.',
            'min'      => ':attribute minimal harus :min karakter/nilai.',
            'max'      => ':attribute melebihi batas maksimal :max karakter.',
        ];
    }

    public function attributes(): array
    {
        return [
            'nama'  => 'nama additional',
            'harga' => 'harga additional',
        ];
    }

    /**
     * Mengatur respon jika validasi gagal agar modal tidak tertutup.
     */
    protected function failedValidation(Validator $validator)
    {
        $redirect = redirect()->back()->withErrors($validator)->withInput();

        if ($this->isMethod('post')) {
            // Untuk modal tambah additional
            $redirect->with('error_modal', 'createAdd');
        } else {
            // Untuk modal edit berdasarkan ID additional
            $redirect->with('error_id_add', $this->route('additional'));
        }

        throw new HttpResponseException($redirect);
    }
}
