<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Chat extends Model
{
    use SoftDeletes;

    protected $table = 'chats';

    protected $fillable = [
        'user_id_1',
        'user_id_2',
        'connection_request_id',
        'questions_exchanged',
        'status',
        'decision_deadline',
        'user_1_decision',
        'user_2_decision',
        'last_reminder_sent_at'
    ];

    protected $casts = [
        'decision_deadline' => 'datetime',
        'last_reminder_sent_at' => 'datetime',
    ];

    // Relationships
    public function user1(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id_1');
    }

    public function user2(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id_2');
    }

    public function messages(): HasMany
    {
        return $this->hasMany(ChatMessage::class);
    }
    public function last_message(): HasOne
    {
        return $this->hasOne(ChatMessage::class)->latest('id');
    }

    // Helper methods
    public function getOtherUserId($currentUserId)
    {
        return $this->user_id_1 == $currentUserId ? $this->user_id_2 : $this->user_id_1;
    }

    public function getUserDecision($userId)
    {
        return $this->user_id_1 == $userId ? $this->user_1_decision : $this->user_2_decision;
    }

    public function setUserDecision($userId, $decision)
    {
        if ($this->user_id_1 == $userId) {
            $this->user_1_decision = $decision;
        } else {
            $this->user_2_decision = $decision;
        }
        $this->save();
    }

    public function shouldShowDecisionPrompt()
    {
        return $this->questions_exchanged > 0 && $this->questions_exchanged % 5 == 0 && $this->status == 'pending_decision';
    }

    public function bothUsersDecided()
    {
        return !is_null($this->user_1_decision) && !is_null($this->user_2_decision);
    }

    public function bothUsersAgreed()
    {
        return ($this->user_1_decision == 'yes' && $this->user_2_decision == 'yes');
    }

    public function anyUserDisagreed()
    {
        return ($this->user_1_decision == 'no' || $this->user_2_decision == 'no');
    }
}
