<?php

require_once __DIR__ . '/db.php';

function sparrow_contact_message_statuses(): array
{
    return ['New', 'Read'];
}

function sparrow_get_contact_message_counts(): array
{
    $row = sparrow_db()->query("
        SELECT
            COUNT(*) AS total_count,
            SUM(CASE WHEN status = 'New' THEN 1 ELSE 0 END) AS new_count,
            SUM(CASE WHEN status = 'Read' THEN 1 ELSE 0 END) AS read_count
        FROM contact_messages
    ")->fetch();

    return [
        'all' => (int) ($row['total_count'] ?? 0),
        'new' => (int) ($row['new_count'] ?? 0),
        'read' => (int) ($row['read_count'] ?? 0),
    ];
}

function sparrow_get_contact_messages(string $status = ''): array
{
    $pdo = sparrow_db();

    if (in_array($status, sparrow_contact_message_statuses(), true)) {
        $stmt = $pdo->prepare("
            SELECT *
            FROM contact_messages
            WHERE status = :status
            ORDER BY created_at DESC, id DESC
        ");

        $stmt->execute([':status' => $status]);

        return $stmt->fetchAll();
    }

    return $pdo->query("
        SELECT *
        FROM contact_messages
        ORDER BY created_at DESC, id DESC
    ")->fetchAll();
}

function sparrow_get_contact_message(int $message_id): ?array
{
    $stmt = sparrow_db()->prepare("
        SELECT *
        FROM contact_messages
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([':id' => $message_id]);
    $message = $stmt->fetch();

    return $message ?: null;
}

function sparrow_update_contact_message_status(int $message_id, string $status): void
{
    if (!in_array($status, sparrow_contact_message_statuses(), true)) {
        throw new InvalidArgumentException('Invalid contact message status.');
    }

    $stmt = sparrow_db()->prepare("
        UPDATE contact_messages
        SET status = :status
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':status' => $status,
        ':id' => $message_id,
    ]);
}
