<?php
if (!defined('ABSPATH')) exit;

$option_key = "simpinby_invoice_number_settings";

$default = [
  "prefix" => "INV",
  "padding" => 6,
  "start_number" => 1
];

$data = get_option($option_key, $default);
$data = wp_parse_args($data, $default);

if (isset($_POST['simpinby_save_invoice_number_settings'])) {
  check_admin_referer("simpinby_invoice_number_settings_save");

  $data["prefix"] = sanitize_text_field($_POST["prefix"] ?? "INV");
  $data["padding"] = intval($_POST["padding"] ?? 6);
  $data["start_number"] = intval($_POST["start_number"] ?? 1);

  if ($data["padding"] < 1) $data["padding"] = 1;
  if ($data["padding"] > 12) $data["padding"] = 12;
  if ($data["start_number"] < 1) $data["start_number"] = 1;

  update_option($option_key, $data);

  echo '<div class="updated notice"><p><b>Saved!</b> Invoice number settings updated.</p></div>';
}

$example_number = $data["prefix"] . "-" . str_pad($data["start_number"], $data["padding"], "0", STR_PAD_LEFT);
?>

<form method="post">
  <?php wp_nonce_field("simpinby_invoice_number_settings_save"); ?>

  <table class="form-table">
    <tr>
      <th><label>Invoice Prefix</label></th>
      <td>
        <input type="text" name="prefix" value="<?php echo esc_attr($data["prefix"]); ?>" class="regular-text" />
        <p class="description">Example: INV, GST, BILL</p>
      </td>
    </tr>

    <tr>
      <th><label>Number Padding</label></th>
      <td>
        <input type="number" name="padding" value="<?php echo esc_attr($data["padding"]); ?>" min="1" max="12" />
        <p class="description">Example: 6 → 000001</p>
      </td>
    </tr>

    <tr>
      <th><label>Starting Number</label></th>
      <td>
        <input type="number" name="start_number" value="<?php echo esc_attr($data["start_number"]); ?>" min="1" />
      </td>
    </tr>
  </table>

  <p><b>Preview:</b> <?php echo esc_html($example_number); ?></p>

  <p>
    <button type="submit" name="simpinby_save_invoice_number_settings" class="button button-primary">
      Save Settings
    </button>
  </p>
</form>
