<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $fillable = [
        'name','type','division','company_name','email','phone','address',
        'pic_name','pic_phone','max_visits_per_month','monthly_fee',
        'extra_visit_fee','sla_enabled','contract_start','contract_end',
        'is_active','notes'
    ];
    protected $casts = [
        'sla_enabled'    => 'boolean',
        'is_active'      => 'boolean',
        'contract_start' => 'date',
        'contract_end'   => 'date',
        'monthly_fee'    => 'decimal:2',
        'extra_visit_fee'=> 'decimal:2',
    ];

    public function users()    { return $this->hasMany(ClientUser::class); }
    public function devices()  { return $this->hasMany(Device::class); }
    public function tickets()  { return $this->hasMany(Ticket::class); }
    public function visits()   { return $this->hasMany(Visit::class); }
    public function invoices() { return $this->hasMany(Invoice::class); }
    public function isps()     { return $this->hasMany(Isp::class); }
    public function slaConfig(){ return $this->hasOne(SlaConfig::class); }

    public function getVisitsThisMonth(): int
    {
        return $this->visits()
            ->whereMonth('visit_date', now()->month)
            ->whereYear('visit_date', now()->year)
            ->where('status','!=','cancelled')
            ->count();
    }

    public function getRemainingVisits(): int
    {
        return max(0, $this->max_visits_per_month - $this->getVisitsThisMonth());
    }

    public function getTypeLabelAttribute(): string
    {
        $map = [
            'maintenance'     => 'Maintenance',
            'non_maintenance' => 'Non-Maintenance',
            'individual'      => 'Perorangan',
        ];
        return isset($map[$this->type]) ? $map[$this->type] : $this->type;
    }
}
