<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;


class Point extends Model
{
    use HasFactory;
    use LogsActivity;

    protected $table = 'points';
    protected $casts = [
        'road_category'   => 'array',
        'accounting_flag' => 'integer',
        'segment_from' => 'float',
        'segment_to'   => 'float',
    ];

    protected $fillable = [
        'name',
        'latitude',
        'longitude',
        'district_id',
        'geojson',
        'length',
        'accounting_point',
        'road_category',
        'road_subcategory',
        'record_number',
        'accounting_type',
        'monitoring_freq',
        'accounting_flag',
        'segment_from',
        'segment_to',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('ПУИДД')
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs()
            ->logOnly([
                'name',
                'latitude',
                'longitude',
                'district_id',
                'geojson',
                'length',
                'accounting_point',
                'road_category',
                'road_subcategory',
                'record_number',
                'accounting_type',
                'monitoring_freq',
                'accounting_flag',
                'segment_from',
                'segment_to',
            ]);
    }

    public function district(): BelongsTo
    {
        return $this->belongsTo(District::class, 'district_id');
    }

    public function plans(): Point|HasMany
    {
        return $this->hasMany(PointPlan::class, 'point_id');
    }

    public function requests(): BelongsToMany
    {
        return $this->belongsToMany(
            RequestSet::class,
            'point_request',
            'point_id',
            'request_id'
        )
            ->using(PointRequest::class)
            ->withTimestamps();
    }

    /**
     * Это подъезд (approach)?
     */
    public function isApproach(): bool
    {
        return $this->accounting_flag === 1;
    }

    /**
     * Это перегон (passage)?
     */
    public function isPassage(): bool
    {
        return $this->accounting_flag === 2;
    }

    /**
     * Возвращает accounting_point как киллометры в формате float,
     * переведя "X+YYY" в X.YYY
     */
    public function getAccountingKilometersAttribute(): float
    {
        $raw = $this->attributes['accounting_point'];

        if (str_contains($raw, '+')) {
            [$km, $thousandths] = explode('+', $raw, 2);
            // а вдруг там не три цифры, или пусто — приводим к 0
            $km   = (float) $km;
            $frac = (int) ltrim($thousandths, '0') / 1000;
            return $km + $frac;
        }

        // просто целое или дробь через точку
        return (float) str_replace(',', '.', $raw);
    }

}
