<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreCustomerRequest extends FormRequest
{
    protected function prepareForValidation(): void
    {
        $this->merge(['ip_address' => trim((string) $this->input('ip_address'))]);
    }

    public function authorize(): bool
    {
        return $this->user()?->can('customer.create') ?? false;
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255', 'unique:customers,email'],
            'contact_phone' => ['required', 'string', 'max:30'],
            'secondary_phone' => ['nullable', 'string', 'max:30'],
            'office_address' => ['nullable', 'string', 'max:500'],
            'customer_code' => ['nullable', 'string', 'max:255', 'unique:customers,customer_code'],
            'ip_address' => ['nullable', 'required_with:mikrotik_id', 'string', 'max:191', 'regex:/^[^\s\x00-\x1F\x7F]+$/u', 'unique:customers,ip_address'],
            'package_id' => ['nullable', 'integer', 'exists:packages,id'],
            'monthly_bill' => ['required', 'numeric', 'min:0'],
            'status' => ['required', 'integer', 'in:0,1,2,3'],
            'national_id' => ['nullable', 'string', 'max:100'],
            'gender' => ['nullable', 'string', 'max:20'],
            'connection_type' => ['nullable', 'string', 'max:100'],
            'billing_person_id' => ['nullable', 'integer', 'exists:users,id'],
            'connection_date' => ['nullable', 'date'],
            'inactive_date' => ['nullable', 'date'],
            'remark' => ['nullable', 'string', 'max:1000'],
            'mikrotik_id' => ['nullable', 'integer', 'exists:mikrotiks,id'],
            'queue_password' => ['nullable', 'required_with:mikrotik_id', 'string', 'max:255'],
            'mikrotik_disconnect' => ['nullable', 'date'],
            'send_sms' => ['sometimes', 'boolean'],
            'generate_bill_this_month' => ['sometimes', 'boolean'],
            'latitude' => ['nullable', 'string', 'max:50'],
            'longitude' => ['nullable', 'string', 'max:50'],
            'zone' => ['nullable', 'string', 'max:255'],
            'sub_zone' => ['nullable', 'string', 'max:255'],
            'destination' => ['nullable', 'string', 'max:255'],
            'onumac' => ['nullable', 'string', 'max:255'],
            'fibercode' => ['nullable', 'string', 'max:255'],
            'regular_mobile' => ['nullable', 'string', 'max:30'],
            'entry_date' => ['nullable', 'date'],
        ];
    }
}
