<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

/**
 * @return array{id: int, message: string, valid_from: string, valid_until: string}|null
 */
function notices_fetch_active(PDO $pdo, int $tenantId): ?array
{
    $stmt = $pdo->prepare(
        "SELECT id, message, valid_from, valid_until
         FROM notices
         WHERE tenant_id = ?
           AND deleted_at IS NULL
           AND valid_from <= NOW()
           AND valid_until >= NOW()
         ORDER BY valid_until ASC
         LIMIT 1"
    );
    $stmt->execute([$tenantId]);
    $row = $stmt->fetch();

    return $row !== false ? $row : null;
}

/**
 * @return list<array{id: int, message: string, valid_from: string, valid_until: string}>
 */
function notices_fetch_all(PDO $pdo, int $tenantId): array
{
    $stmt = $pdo->prepare(
        "SELECT id, message, valid_from, valid_until
         FROM notices
         WHERE tenant_id = ?
           AND deleted_at IS NULL
         ORDER BY valid_until DESC"
    );
    $stmt->execute([$tenantId]);

    return $stmt->fetchAll();
}

function notices_create(PDO $pdo, int $tenantId, string $message, string $validUntil, ?int $createdByUserId): bool
{
    $message = trim($message);
    if ($message === '' || $validUntil === '') {
        return false;
    }

    $stmt = $pdo->prepare(
        'INSERT INTO notices (tenant_id, message, valid_from, valid_until, created_by_user_id)
         VALUES (?, ?, NOW(), ?, ?)'
    );

    return $stmt->execute([$tenantId, $message, $validUntil, $createdByUserId]);
}

function notices_soft_delete(PDO $pdo, int $tenantId, int $noticeId): bool
{
    $stmt = $pdo->prepare(
        'UPDATE notices
         SET deleted_at = NOW()
         WHERE id = ?
           AND tenant_id = ?
           AND deleted_at IS NULL'
    );
    $stmt->execute([$noticeId, $tenantId]);

    return $stmt->rowCount() > 0;
}
