<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberInvitationModel extends Model
{
    protected $table = 'member_invitations';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'member_id', 'roll_no', 'email', 'phone', 'token',
        'purpose', 'expires_at', 'accepted_at', 'created_by',
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    public function hasPurposeColumn(): bool
    {
        return $this->db->fieldExists('purpose', $this->table);
    }

    public function getValidInvitationByToken(string $token, string $purpose = 'register'): ?array
    {
        $builder = $this->where('token', $token)
            ->where('accepted_at', null)
            ->where('expires_at >=', date('Y-m-d H:i:s'));

        if ($this->hasPurposeColumn()) {
            $builder = $builder->where('purpose', $purpose);
        } elseif ($purpose !== 'register') {
            return null;
        }

        return $builder->first();
    }
}
