<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Log;

class PostRequest 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
    {
        if ($this->isMethod('POST')) {
            return [
                'KategoriId' => 'required|integer|exists:Kategori,KategoriId',
                'SubKategoriId' => 'required|integer|exists:SubKategori,SubKategoriId',
                'JudulPost' => ['required', 'string', 'max:255'],
                'SlugPost' => ['required', 'string', 'max:255'],
                'DescPost' => ['required', 'string'],
                'ImagePost' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
                'IsPublish' => 'boolean',
            ];
        }

        if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
            return [
                'KategoriId' => 'nullable|integer|exists:Kategori,KategoriId',
                'SubKategoriId' => 'nullable|integer|exists:SubKategori,SubKategoriId',
                'JudulPost' => ['nullable', 'string', 'max:255'],
                'SlugPost' => ['nullable', 'string', 'max:255'],
                'DescPost' => ['nullable', 'string'],
                'ImagePost' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
                'IsPublish' => 'nullable|boolean',
            ];
        }

        return [];
    }

    // Add this method to handle validation before rules are applied
    protected function prepareForValidation()
    {
        if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
            // Only set these if they're not provided in the request
            if (!$this->has('KategoriId')) {
                $this->merge(['KategoriId' => $this->route('post')->KategoriId]);
            }
            if (!$this->has('SubKategoriId')) {
                $this->merge(['SubKategoriId' => $this->route('post')->SubKategoriId]);
            }
            if (!$this->has('JudulPost')) {
                $this->merge(['JudulPost' => $this->route('post')->JudulPost]);
            }
            if (!$this->has('SlugPost')) {
                $this->merge(['SlugPost' => $this->route('post')->SlugPost]);
            }
            if (!$this->has('DescPost')) {
                $this->merge(['DescPost' => $this->route('post')->DescPost]);
            }
        }
    }
}
