<?php
declare(strict_types=1);

/**
 * OnePanel: Secure, consistent POST action helpers (B2.2)
 *
 * Usage:
 *   echo op_action_button('vpn.delete', ['id' => $id], '<i class="fa fa-times ..."></i>',
 *                        'btn btn-link text-secondary mb-0', "Are you sure?");
 *
 * Notes:
 * - Always includes CSRF.
 * - Always uses POST.
 * - Hidden fields are HTML-escaped.
 */
function op_hidden_inputs(array $fields): string {
  $out = '';
  foreach ($fields as $k => $v) {
    $k = htmlspecialchars((string)$k, ENT_QUOTES, 'UTF-8');
    $v = htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    $out .= '<input type="hidden" name="' . $k . '" value="' . $v . '">';
  }
  return $out;
}

/**
 * Build a secure POST form that triggers an action key in action.php.
 *
 * @param string $actionKey  e.g. 'vpn.delete' (action.php checks isset($_POST[$actionKey]))
 * @param array  $fields     additional hidden fields (e.g. ['id' => 123])
 * @param string $buttonHtml button inner HTML (icon/text)
 * @param string $buttonClass classes for <button>
 * @param string|null $confirm optional confirm message
 * @param array $formAttrs additional form attributes (e.g. ['style' => 'display:inline'])
 */
function op_action_form(
  string $actionKey,
  array $fields,
  string $buttonHtml,
  string $buttonClass = 'btn btn-danger',
  ?string $confirm = null,
  array $formAttrs = []
): string {
  $attrs = ['method' => 'post', 'action' => 'action.php'];
  foreach ($formAttrs as $k => $v) $attrs[$k] = $v;

  $attrStr = '';
  foreach ($attrs as $k => $v) {
    $k = htmlspecialchars((string)$k, ENT_QUOTES, 'UTF-8');
    $v = htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    $attrStr .= ' ' . $k . '="' . $v . '"';
  }

  $onsubmit = '';
  if ($confirm !== null && $confirm !== '') {
    $c = htmlspecialchars($confirm, ENT_QUOTES, 'UTF-8');
    $onsubmit = ' onsubmit="return confirm(\'' . $c . '\');"';
  }

  $ak = htmlspecialchars($actionKey, ENT_QUOTES, 'UTF-8');
  $btnClass = htmlspecialchars($buttonClass, ENT_QUOTES, 'UTF-8');

  // The action flag itself (matches action.php: isset($_POST['<actionKey>']))
  $actionFlag = '<input type="hidden" name="' . $ak . '" value="1">';

  return '<form' . $attrStr . $onsubmit . '>'
      . csrf_input()
      . $actionFlag
      . op_hidden_inputs($fields)
      . '<button type="submit" class="' . $btnClass . '">' . $buttonHtml . '</button>'
      . '</form>';
}

/**
 * Convenience: same as op_action_form().
 */
function op_action_button(
  string $actionKey,
  array $fields,
  string $buttonHtml,
  string $buttonClass = 'btn btn-danger',
  ?string $confirm = null,
  array $formAttrs = []
): string {
  return op_action_form($actionKey, $fields, $buttonHtml, $buttonClass, $confirm, $formAttrs);
}
