<?php

namespace App\Models;

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

class Conversation extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'participant1_id',
        'participant1_type',
        'participant2_id',
        'participant2_type',
        'last_message_at',
        'customer_id',
        'workspace_id',
        'is_active'
    ];

    protected $hidden = [
        'customer_id',
        'workspace_id',
    ];

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

    public function participant1()
    {
        return $this->morphTo('participant1', 'participant1_type', 'participant1_id');
    }

    public function participant2()
    {
        return $this->morphTo('participant2', 'participant2_type', 'participant2_id');
    }

    public function messages()
    {
        return $this->hasMany(Message::class)->orderBy('created_at', 'asc');
    }

    public function lastMessage()
    {
        return $this->hasOne(Message::class)->latest();
    }

    public function getOtherParticipant($userId, $userType = 'user')
    {
        if ($this->participant1_id == $userId && $this->participant1_type === $userType) {
            return $this->participant2;
        } elseif ($this->participant2_id == $userId && $this->participant2_type === $userType) {
            return $this->participant1;
        }
        return null;
    }

    public function customer()
    {
        return $this->belongsTo(User::class, 'customer_id');
    }

    public function workspace()
    {
        return $this->belongsTo(\App\Models\Workspace::class, 'workspace_id');
    }

    // Helper methods for frontend
    public function getParticipantName($participant)
    {
        if (!$participant) return 'Unknown';

        if ($participant instanceof \App\Models\EmpCompanyDetails) {
            // Load the relationship if not already loaded
            if (!$participant->relationLoaded('empPersonalDetails')) {
                $participant->load('empPersonalDetails');
            }
            
            if ($participant->empPersonalDetails) {
                $details = $participant->empPersonalDetails;
                $fullName = trim(($details->first_name ?? '') . ' ' . ($details->middle_name ?? '') . ' ' . ($details->last_name ?? ''));
                
                // If we have a meaningful name, return it
                if (!empty(trim($fullName))) {
                    return $fullName;
                }
            }
            
            // Fallback: try to extract name from email
            $email = $participant->employee_email ?? 'Unknown User';
            if ($email !== 'Unknown User' && strpos($email, '@') !== false) {
                $emailPart = explode('@', $email)[0];
                // Convert dots and underscores to spaces and capitalize
                $nameFromEmail = ucwords(str_replace(['.', '_', '-'], ' ', $emailPart));
                return $nameFromEmail;
            }
            
            return $email;
        } elseif ($participant instanceof \App\Models\User) {
            return $participant->name ?? $participant->email ?? 'Unknown User';
        }
        return 'Unknown User';
    }

    public function getParticipantAvatar($participant)
    {
        if (!$participant) return '/img/profile.jpeg';

        if ($participant instanceof \App\Models\EmpCompanyDetails) {
            // Load the relationship if not already loaded
            if (!$participant->relationLoaded('tierEmpPersonalDetail')) {
                $participant->load('tierEmpPersonalDetail');
            }
            
            if ($participant->tierEmpPersonalDetail) {
                return $participant->tierEmpPersonalDetail->image ?? '/img/profile.jpeg';
            }
            return '/img/profile.jpeg';
        } elseif ($participant instanceof \App\Models\User) {
            return $participant->image ?? '/img/profile.jpeg';
        }
        return '/img/profile.jpeg';
    }
}
