CREATE TABLE IF NOT EXISTS notices (
  id INT AUTO_INCREMENT PRIMARY KEY,
  tenant_id INT NOT NULL,
  message TEXT NOT NULL,
  valid_from DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  valid_until DATETIME NOT NULL,
  created_by_user_id INT NULL,
  deleted_at DATETIME NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_notices_tenant_valid_until (tenant_id, valid_until),
  KEY idx_notices_created_by_user (created_by_user_id),
  CONSTRAINT fk_notices_tenant
    FOREIGN KEY (tenant_id) REFERENCES tenants(id)
    ON DELETE CASCADE,
  CONSTRAINT fk_notices_created_by_user
    FOREIGN KEY (created_by_user_id) REFERENCES users(id)
    ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- One-time carry-over so currently visible legacy banners are not lost when
-- hinweise.php switches from kl_hinweise to the tenant-scoped notices table.
-- kl_hinweise itself is left untouched; it stays as the golden-master
-- reference for the legacy system.
INSERT INTO notices (tenant_id, message, valid_from, valid_until)
SELECT t.id, h.nachricht, NOW(), h.gueltig_bis
FROM kl_hinweise h
JOIN tenants t ON t.slug = 'default'
WHERE h.gueltig_bis >= NOW();
