<?php

declare(strict_types=1);

function reservationEnsureSoftDeleteColumns(mysqli $conn): array
{
    static $checked = false;

    if ($checked) {
        return [true, ""];
    }

    $columns = ["user_deleted", "admin_deleted"];

    foreach ($columns as $column) {
        $existsStmt = $conn->prepare(
            "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = 'reservations'
               AND COLUMN_NAME = ?"
        );

        if (!$existsStmt) {
            return [false, "Failed to prepare schema check query."];
        }

        $existsStmt->bind_param("s", $column);
        $existsStmt->execute();
        $existsStmt->bind_result($columnCount);
        $existsStmt->fetch();
        $existsStmt->close();

        if ((int) $columnCount === 0) {
            $alterSql = "ALTER TABLE reservations ADD COLUMN {$column} TINYINT(1) NOT NULL DEFAULT 0";
            if (!$conn->query($alterSql)) {
                return [false, "Failed to update reservation schema for soft delete support."];
            }
        }
    }

    $checked = true;
    return [true, ""];
}
