<?php

namespace App\Models;

/** See CreateConciergeTables's migration comment. */
class ConciergeConversationModel extends TenantModel
{
    protected $table            = 'concierge_conversations';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = [
        'guest_id',
        'phone',
        'needs_staff',
        'pending_reply',
        'last_message_at',
        'resolved_at',
        'resolved_by',
    ];

    public function findOpenForPhone(string $phone): ?object
    {
        return $this->where('phone', $phone)
            ->where('resolved_at', null)
            ->orderBy('id', 'desc')
            ->first();
    }

    /**
     * @param 'needs_staff'|'pending_reply'|null $filter
     */
    public function list(?string $filter = null): array
    {
        $builder = $this->select('concierge_conversations.*, guests.full_name as guest_name')
            ->join('guests', 'guests.id = concierge_conversations.guest_id', 'left');

        if ($filter === 'needs_staff') {
            $builder->where('concierge_conversations.needs_staff', 1)->where('concierge_conversations.resolved_at', null);
        } elseif ($filter === 'pending_reply') {
            $builder->where('concierge_conversations.pending_reply', 1);
        }

        return $builder->orderBy('concierge_conversations.last_message_at', 'desc')->findAll();
    }

    public function countNeedsStaff(): int
    {
        return $this->where('needs_staff', 1)->where('resolved_at', null)->countAllResults();
    }

    public function countPendingReply(): int
    {
        return $this->where('pending_reply', 1)->countAllResults();
    }
}
