<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Call extends Model
{
    use BelongsToTenant, SoftDeletes;

    public const DIRECTIONS = [
        'incoming' => 'Primit',
        'outgoing' => 'Efectuat',
        'missed' => 'Pierdut',
    ];

    public const STATUSES = [
        'answered' => 'Răspuns',
        'missed' => 'Pierdut',
        'busy' => 'Ocupat',
        'no_answer' => 'Fără răspuns',
    ];

    protected $fillable = [
        'company_id', 'client_id', 'lead_id', 'user_id',
        'direction', 'phone', 'called_at', 'duration_sec',
        'status', 'recording_url', 'notes', 'lead_created',
    ];

    protected $casts = [
        'called_at' => 'datetime',
        'lead_created' => 'boolean',
    ];

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function lead(): BelongsTo
    {
        return $this->belongsTo(Lead::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function getDurationFormattedAttribute(): string
    {
        $sec = (int) $this->duration_sec;
        if ($sec === 0) return '—';
        return sprintf('%d:%02d', intdiv($sec, 60), $sec % 60);
    }
}
