<?php
declare(strict_types=1);

namespace App\Modules\Archive\Models;

use App\Core\App;

class MembershipNumberChain
{
    public static function create(array $data): int
    {
        $db = App::getInstance()->db();
        return $db->insert('membership_number_chain', $data);
    }

    public static function find(int $id): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne("SELECT * FROM membership_number_chain WHERE id = ?", [$id]);
    }

    public static function getChainForNumber(string $membershipNumber): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM membership_number_chain WHERE membership_number = ? ORDER BY held_from ASC",
            [$membershipNumber]
        );
    }

    public static function getCurrentHolder(string $membershipNumber): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM membership_number_chain WHERE membership_number = ? AND held_until IS NULL ORDER BY held_from DESC LIMIT 1",
            [$membershipNumber]
        );
    }

    public static function getHoldersForEntity(string $entityType, int $entityId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM membership_number_chain WHERE holder_entity_type = ? AND holder_entity_id = ? ORDER BY held_from DESC",
            [$entityType, $entityId]
        );
    }

    public static function endCurrentHolder(string $membershipNumber): void
    {
        $db = App::getInstance()->db();
        $db->update(
            'membership_number_chain',
            ['held_until' => date('Y-m-d H:i:s')],
            '`membership_number` = ? AND `held_until` IS NULL',
            [$membershipNumber]
        );
    }
}