<?php

namespace App\Http\Requests\Api\Auth;

use App\Models\Datmas\Indentitas;
use App\Models\Datmas\Siswa;
use Illuminate\Foundation\Http\FormRequest;

class SetupPinRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'nis' => 'required|string|exists:mai2.tsiswa,nis',
            'nouid' => 'nullable|string',
            'phone' => 'nullable|string|regex:/^[0-9]+$/|min:10|max:15',
            'pin' => 'required|digits:6|numeric|confirmed',
            'pin_confirmation' => 'required|digits:6',
            'device_name' => 'required|string|max:100',
        ];
    }

    public function messages(): array
    {
        return [
            'nis.exists' => 'NIS tidak valid.',
            'pin.digits' => 'PIN harus terdiri dari 6 digit angka.',
            'phone.regex' => 'Nomor telepon hanya boleh berisi angka.',
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            if (! $this->filled('nouid')) {
                return;
            }

            $identity = Indentitas::query()
                ->with('siswa')
                ->where('nouid', $this->string('nouid')->toString())
                ->first();

            if ($identity && $identity->siswa?->nis !== $this->string('nis')->toString()) {
                $validator->errors()->add('nouid', 'NIS tidak cocok dengan nomor identitas siswa.');
            }

            if (! $identity && $this->string('nouid')->toString() !== $this->string('nis')->toString()) {
                $validator->errors()->add('nouid', 'Nomor identitas tidak cocok dengan NIS.');
            }
        });
    }

    protected function prepareForValidation(): void
    {
        if (!$this->filled('nis') || $this->filled('nouid')) {
            return;
        }

        $siswa = Siswa::query()
            ->with('indentitas')
            ->where('nis', $this->string('nis')->toString())
            ->first();

        if ($siswa?->indentitas) {
            $this->merge([
                'nouid' => $siswa->indentitas->nouid,
            ]);
        }
    }
}
