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

$option_key = "simpinby_tax_settings";

/**
 * Structure:
 * [
 *   "default_tax_id" => "tax_123",
 *   "taxes" => [
 *      [
 *        "id" => "tax_xxx",
 *        "name" => "GST",
 *        "percent" => 18
 *      ]
 *   ]
 * ]
 */
$default = [
  "default_tax_id" => "",
  "taxes" => []
];

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

// Handle Add Tax
if (isset($_POST['simpinby_add_tax'])) {

  if (!current_user_can('manage_options')) {
    wp_die('Permission denied.');
  }

  check_admin_referer("simpinby_tax_settings_save");

  $name = isset($_POST["tax_name"])
    ? sanitize_text_field( wp_unslash($_POST["tax_name"]) )
    : "";

  $percent = isset($_POST["tax_percent"])
    ? floatval( wp_unslash($_POST["tax_percent"]) )
    : 0;


  if ($name !== "" && $percent >= 0) {
    $new_tax = [
      "id" => "tax_" . time() . "_" . wp_rand(1000, 9999),
      "name" => $name,
      "percent" => $percent
    ];

    $data["taxes"][] = $new_tax;

    // if first tax, make default automatically
    if (empty($data["default_tax_id"])) {
      $data["default_tax_id"] = $new_tax["id"];
    }

    update_option($option_key, $data);

    echo '<div class="updated notice"><p><strong>' . esc_html__('Saved!', 'simpinby-invoice-manager') . '</strong> ' . esc_html__('Tax added successfully.', 'simpinby-invoice-manager') . '</p></div>';
  } else {
    echo '<div class="error notice"><p><b>Error:</b> Please enter valid Tax Name and Percent.</p></div>';
  }
}

// Handle Delete Tax (with nonce)
if (isset($_GET['delete_tax'])) {

  if (
    ! isset($_GET['_wpnonce']) ||
    ! wp_verify_nonce(
        sanitize_text_field( wp_unslash($_GET['_wpnonce']) ),
        'simpinby_delete_tax'
    )
  ) {
    wp_die('Invalid or expired request.');
  }

  if (!current_user_can('manage_options')) {
    wp_die('Permission denied.');
  }

  $delete_id = sanitize_text_field(
      wp_unslash($_GET['delete_tax'])
  );

  $data["taxes"] = array_values(array_filter($data["taxes"], function ($t) use ($delete_id) {
    return $t["id"] !== $delete_id;
  }));

  // if deleted default, reset default
  if ($data["default_tax_id"] === $delete_id) {
    $data["default_tax_id"] = isset($data["taxes"][0]) ? $data["taxes"][0]["id"] : "";
  }

  update_option($option_key, $data);

  echo '<div class="updated notice"><p><b>Deleted!</b> Tax removed successfully.</p></div>';
}


// Handle Set Default Tax
if (isset($_POST['simpinby_set_default_tax'])) {

  if (!current_user_can('manage_options')) {
    wp_die('Permission denied.');
  }

  check_admin_referer("simpinby_tax_settings_save");

  $default_id = isset($_POST["default_tax_id"])
    ? sanitize_text_field( wp_unslash($_POST["default_tax_id"]) )
    : "";

  $exists = false;

  foreach ($data["taxes"] as $t) {
    if ($t["id"] === $default_id) {
      $exists = true;
      break;
    }
  }

  if ($exists) {
    $data["default_tax_id"] = $default_id;
    update_option($option_key, $data);
    echo '<div class="updated notice"><p><b>Saved!</b> Default tax updated.</p></div>';
  } else {
    echo '<div class="error notice"><p><b>Error:</b> Invalid default tax selection.</p></div>';
  }
}
?>

<h2>Tax Settings</h2>
<p class="description">Add multiple tax types like GST / VAT and select one default tax.</p>

<hr/>

<h3>Add New Tax</h3>

<form method="post" style="max-width:600px;">
  <?php wp_nonce_field("simpinby_tax_settings_save"); ?>

  <table class="form-table">
    <tr>
      <th><label>Tax Name</label></th>
      <td>
        <input type="text" name="tax_name" class="regular-text" placeholder="GST / VAT" required />
      </td>
    </tr>

    <tr>
      <th><label>Tax Percent (%)</label></th>
      <td>
        <input type="number" step="0.01" name="tax_percent" placeholder="18" required />
      </td>
    </tr>
  </table>

  <p>
    <button type="submit" name="simpinby_add_tax" class="button button-primary">
      + Add Tax
    </button>
  </p>
</form>

<hr/>

<h3>Available Taxes</h3>

<?php if (empty($data["taxes"])): ?>
  <p>No taxes added yet.</p>
<?php else: ?>

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

  <table class="widefat striped" style="max-width:800px;">
    <thead>
      <tr>
        <th>Default</th>
        <th>Tax Name</th>
        <th>Percent</th>
        <th>Action</th>
      </tr>
    </thead>

    <tbody>
      <?php foreach ($data["taxes"] as $tax): ?>
        <tr>
          <td>
            <input type="radio" name="default_tax_id"
              value="<?php echo esc_attr($tax["id"]); ?>"
              <?php checked($data["default_tax_id"], $tax["id"]); ?>
            />
          </td>

          <td><?php echo esc_html($tax["name"]); ?></td>
          <td><?php echo esc_html($tax["percent"]); ?>%</td>

          <td>
            <?php
              $delete_url = wp_nonce_url(
                admin_url('admin.php?page=simpinby-settings&tab=tax&delete_tax=' . urlencode($tax["id"])),
                'simpinby_delete_tax'
              );
            ?>

            <a class="button button-small"
              href="<?php echo esc_url($delete_url); ?>"
              onclick="return confirm('Are you sure you want to delete this tax?');">
              Delete
            </a>

          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

  <p style="margin-top:12px;">
    <button type="submit" name="simpinby_set_default_tax" class="button button-primary">
      Save Default Tax
    </button>
  </p>

</form>

<?php endif; ?>
