<?php
declare(strict_types=1);

/**
 * OnePanel B3: action handler group: messages
 * Generated from legacy action.php blocks for maintainability.
 */

function op_handle_messages(string $actionKey): void {
  switch ($actionKey) {
    case 'message-delete':
      _op_auth_required();
      	deleteMessage($_POST['id']);
      	header("Location: dashboard.php?messages");
      	exit;
      return;
    case 'addmessage':
      addMessage($_POST['text'], $_POST['user']);
      	header("Location: dashboard.php?messages");
      	exit;
      return;
    case 'updatemessage':
      $active = false;
      	if ($_POST['active'] == "on") {
      		$active = true;
      	}
      	saveMessage($_POST['id'], $_POST['text'], $_POST['user'], $active);
      	header("Location: dashboard.php?messages");
      	exit;
      return;
    default:
      http_response_code(400);
      echo 'Unknown action';
      return;
  }
}

// ---- B3.2 normalized wrappers ----

function handle_messages_add(array $post): void {
  _op_auth_required();
  $title = op_post_string($post, 'title', 1, 200);
  $message = op_post_string($post, 'message', 1, 5000);
  op_try(function() use ($title, $message) {
    addMessage($title, $message);
  }, 'dashboard.php?messages', 'Message added.');
}

function handle_messages_delete(array $post): void {
  _op_auth_required();
  $id = op_post_int($post, 'id', 1);
  op_try(function() use ($id) {
    deleteMessage($id);
  }, 'dashboard.php?messages', 'Message deleted.');
}

function handle_messages_update(array $post): void {
  _op_auth_required();
  $id = op_post_int($post, 'id', 1);
  $title = op_post_string($post, 'title', 1, 200);
  $message = op_post_string($post, 'message', 1, 5000);
  op_try(function() use ($id, $title, $message) {
    saveMessage($id, $title, $message);
  }, 'dashboard.php?messages', 'Message updated.');
}
