<?php

namespace App\Http\Requests\Reports\Stickers;

use App\Http\Requests\ApiFormRequest;
use Illuminate\Validation\Validator;

class StickerPrintRequest extends ApiFormRequest
{
    protected function prepareForValidation(): void
    {
        parent::prepareForValidation();

        if (!$this->has('class_section_id') && $this->has('class_id')) {
            $this->merge(['class_section_id' => $this->input('class_id')]);
        }
    }

    public function authorize(): bool
    {
        return auth()->check();
    }

    public function rules(): array
    {
        return [
            'school_year' => ['nullable', 'string', 'max:20'],
            'student_id' => ['nullable', 'integer', 'min:1'],
            'class_section_id' => ['nullable', 'integer', 'min:1'],
            'print_all' => ['nullable', 'boolean'],
            'sticker_size' => ['nullable', 'string', 'max:20'],
            'sticker_width' => ['nullable', 'numeric', 'min:1'],
            'sticker_height' => ['nullable', 'numeric', 'min:1'],
            'stickers_per_page' => ['nullable', 'integer', 'min:1'],
            'page_size' => ['nullable', 'string', 'max:20'],
            'orientation' => ['nullable', 'string', 'max:2'],
            'margin_left' => ['nullable', 'numeric', 'min:0'],
            'margin_top' => ['nullable', 'numeric', 'min:0'],
            'margin_right' => ['nullable', 'numeric', 'min:0'],
            'margin_bottom' => ['nullable', 'numeric', 'min:0'],
            'gap_x' => ['nullable', 'numeric', 'min:0'],
            'gap_y' => ['nullable', 'numeric', 'min:0'],
            'copies' => ['nullable', 'array'],
            'copies.*' => ['integer', 'min:0'],
            'single_copies' => ['nullable', 'integer', 'min:0'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $hasStudent = $this->filled('student_id');
            $hasClass = $this->filled('class_section_id');
            $printAll = (bool) $this->input('print_all', false);

            if (!$hasStudent && !$hasClass && !$printAll) {
                $validator->errors()->add('selection', 'Please select a student or class, or set print_all.');
            }
        });
    }
}
