<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Conversation extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'contact_id', 'assigned_to',
        'contact_phone', 'contact_name', 'status',
        'label', 'language', 'last_message', 'last_message_at',
        'customer_last_message_at', 'unread_count',
    ];

    protected $casts = [
        'last_message_at'           => 'datetime',
        'customer_last_message_at'  => 'datetime',
    ];

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

    public function contact()
    {
        return $this->belongsTo(Contact::class);
    }

    public function messages()
    {
        return $this->hasMany(Message::class);
    }

    /**
     * Hours remaining in WhatsApp 24-hour customer service window.
     * Uses customer_last_message_at if set, otherwise falls back to created_at.
     * Returns null only if conversation is older than 24 hours and no customer message.
     */
    public function hoursLeftToReply(): ?float
    {
        // Use last customer message time; fall back to conversation creation time
        $reference = $this->customer_last_message_at ?? $this->created_at;
        if (!$reference) return null;

        $elapsed = now()->diffInMinutes($reference) / 60;
        $left    = round(24 - $elapsed, 1);

        // If window has completely expired and no customer message ever sent, return null
        if ($left <= 0 && !$this->customer_last_message_at) return null;

        return max(0, $left);
    }

    /**
     * Initials for the contact avatar (up to 2 chars).
     */
    public function initials(): string
    {
        $name = $this->contact_name ?: $this->contact_phone;
        $parts = explode(' ', trim($name));
        if (count($parts) >= 2) {
            return strtoupper(substr($parts[0], 0, 1) . substr($parts[1], 0, 1));
        }
        return strtoupper(substr($name, 0, 1));
    }
}
