<?php

namespace App\Models;

/**
 * A login identity for external event organizers — a third auth realm
 * alongside staff (UserModel) and Super Admin. See
 * CreateEventOrganizersTable's migration comment for why this is its own
 * table rather than bolted onto guests/event_clients.
 */
class EventOrganizerModel extends TenantModel
{
    protected $table            = 'event_organizers';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'full_name',
        'email',
        'phone',
        'password_hash',
        'is_active',
    ];

    protected $validationRules = [
        'full_name' => 'required|max_length[150]',
        'email'     => 'required|valid_email|max_length[150]|tenant_unique[event_organizers.email,id,{id}]',
        'phone'     => 'permit_empty|max_length[20]',
    ];

    public function findByEmail(string $email): ?object
    {
        return $this->where('email', $email)->first();
    }

    /** Mirrors UserModel::verifyCredentials() exactly, plus rejects an organizer who hasn't completed the set-password flow yet (password_hash still null). */
    public function verifyCredentials(string $email, string $password): ?object
    {
        $organizer = $this->where('email', $email)->where('is_active', 1)->first();

        if ($organizer === null || $organizer->password_hash === null || ! password_verify($password, $organizer->password_hash)) {
            return null;
        }

        unset($organizer->password_hash);

        return $organizer;
    }
}
