<?php

namespace App\Models;

/**
 * Parallel to PasswordResetCodeModel (staff), not a reuse of it — see
 * CreateEventOrganizerPasswordCodesTable's migration comment. Same
 * 6-digit numeric, single-use, short-lived shape. Serves BOTH the
 * staff-triggered first-time invite (EventController::inviteOrganizer())
 * and the organizer's own self-service forgot-password
 * (EventOrganizerPasswordController::requestCode()) — the "set password"
 * step this feeds is identifier-based (organizer re-enters their email),
 * not session-gated, so both entry points share one verify step.
 */
class EventOrganizerPasswordCodeModel extends TenantModel
{
    protected $table            = 'event_organizer_password_codes';
    protected $primaryKey       = 'id';
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = ['organizer_id', 'code', 'expires_at', 'used_at'];

    private const TTL_MINUTES = 10;

    /** Invalidates any previous unused code for this organizer (so only the most recently issued code ever works) and issues a new one. */
    public function generateFor(int $organizerId): string
    {
        $this->where('organizer_id', $organizerId)->where('used_at', null)->set(['used_at' => date('Y-m-d H:i:s')])->update(null);

        $code = (string) random_int(100000, 999999);

        $this->insert([
            'organizer_id' => $organizerId,
            'code'         => $code,
            'expires_at'   => date('Y-m-d H:i:s', strtotime('+' . self::TTL_MINUTES . ' minutes')),
            'used_at'      => null,
        ]);

        return $code;
    }

    public function isValid(int $organizerId, string $code): bool
    {
        return $this->where('organizer_id', $organizerId)
            ->where('code', $code)
            ->where('used_at', null)
            ->where('expires_at >', date('Y-m-d H:i:s'))
            ->first() !== null;
    }

    public function consume(int $organizerId, string $code): void
    {
        $this->where('organizer_id', $organizerId)->where('code', $code)->set(['used_at' => date('Y-m-d H:i:s')])->update(null);
    }
}
