<?php

namespace App\Http\Requests;

use App\Models\Plan;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StorePlanRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->isSuperAdmin() ?? false;
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'slug' => $this->filled('slug') ? str($this->input('slug'))->slug()->toString() : Plan::uniqueSlug((string) $this->input('name')),
            'invoice_module_enabled' => $this->boolean('invoice_module_enabled'),
            'whatsapp_reminder_enabled' => $this->boolean('whatsapp_reminder_enabled'),
            'email_reminder_enabled' => $this->boolean('email_reminder_enabled'),
            'reports_enabled' => $this->boolean('reports_enabled'),
            'custom_branding_enabled' => $this->boolean('custom_branding_enabled'),
        ]);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:120'],
            'slug' => ['required', 'alpha_dash', 'max:140', 'unique:plans,slug'],
            'description' => ['nullable', 'string', 'max:1000'],
            'monthly_price' => ['required', 'numeric', 'min:0', 'max:999999'],
            'yearly_price' => ['required', 'numeric', 'min:0', 'max:999999'],
            'trial_days' => ['required', 'integer', 'min:0', 'max:365'],
            'max_staff' => ['nullable', 'integer', 'min:1', 'max:1000000'],
            'max_services' => ['nullable', 'integer', 'min:1', 'max:1000000'],
            'max_appointments_per_month' => ['nullable', 'integer', 'min:1', 'max:1000000'],
            'max_reminders_per_month' => ['nullable', 'integer', 'min:1', 'max:1000000'],
            'max_invoices_per_month' => ['nullable', 'integer', 'min:1', 'max:1000000'],
            'invoice_module_enabled' => ['boolean'],
            'whatsapp_reminder_enabled' => ['boolean'],
            'email_reminder_enabled' => ['boolean'],
            'reports_enabled' => ['boolean'],
            'custom_branding_enabled' => ['boolean'],
            'status' => ['required', Rule::in(array_keys(Plan::STATUSES))],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:1000'],
        ];
    }
}
