<?php

namespace App\Models;

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

/**
 * Model: RPartnerContact (Partner Contact Person)
 * 
 * Represents contact persons for partner organizations.
 * 
 * @property int $id
 * @property int $partner_id
 * @property string $name
 * @property string|null $title
 * @property string|null $email
 * @property string|null $phone
 * @property string|null $mobile
 * @property string $role
 * @property bool $is_primary
 * @property bool $is_active
 * @property string|null $notes
 */
class RPartnerContact extends Model
{
    use HasFactory;

    protected $table = 'r_partner_contacts';

    protected $fillable = [
        'partner_id',
        'name',
        'title',
        'email',
        'phone',
        'mobile',
        'role',
        'is_primary',
        'is_active',
        'notes',
    ];

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

    /**
     * Role constants.
     */
    const ROLE_PRIMARY_CONTACT = 'primary_contact';
    const ROLE_EXECUTIVE = 'executive';
    const ROLE_TECHNICAL = 'technical';
    const ROLE_ADMINISTRATIVE = 'administrative';
    const ROLE_COMMUNICATIONS = 'communications';
    const ROLE_OTHER = 'other';

    /**
     * Get the partner organization.
     */
    public function partner(): BelongsTo
    {
        return $this->belongsTo(RPartner::class, 'partner_id');
    }

    /**
     * Scope: Primary contacts.
     */
    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    /**
     * Scope: Active contacts.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope: By role.
     */
    public function scopeByRole($query, string $role)
    {
        return $query->where('role', $role);
    }

    /**
     * Get role label.
     */
    public function getRoleLabelAttribute(): string
    {
        return match($this->role) {
            self::ROLE_PRIMARY_CONTACT => 'Primary Contact',
            self::ROLE_EXECUTIVE => 'Executive',
            self::ROLE_TECHNICAL => 'Technical',
            self::ROLE_ADMINISTRATIVE => 'Administrative',
            self::ROLE_COMMUNICATIONS => 'Communications',
            default => 'Other',
        };
    }

    /**
     * Get best phone number.
     */
    public function getBestPhoneAttribute(): ?string
    {
        return $this->mobile ?? $this->phone;
    }

    /**
     * Set as primary contact.
     */
    public function setAsPrimary(): void
    {
        // Remove primary from other contacts
        static::where('partner_id', $this->partner_id)
              ->where('id', '!=', $this->id)
              ->update(['is_primary' => false]);

        $this->update(['is_primary' => true]);
    }
}
