<?php

defined("ABSPATH") || exit();

class Chit_Admin_Generate
{
    public function __construct()
    {
        add_action("admin_post_chit_generate_codes", [$this, "handle_post"]);
    }

    public function render()
    {
        if (!current_user_can("manage_woocommerce")) {
            wp_die(esc_html__("No permission.", "chit-download-codes-for-woocommerce"), 403);
        } ?>
          <div class="wrap">
              <h1><?php esc_html_e("Generate codes", "chit-download-codes-for-woocommerce"); ?></h1>

              <?php if (!empty($_GET["generated"])):

                  $token = sanitize_key($_GET["generated"]);
                  $result = get_transient("chit_generated_$token");
                  if ($result): ?>
                      <div class="notice notice-success"><p>
                          <?php
                          printf(
                              /* translators: %1$d: number of codes generated, %2$d: batch ID */
                              esc_html__(
                                  'Generated %1$d codes (batch #%2$d).',
                                  "chit-download-codes-for-woocommerce"
                              ),
                              count($result["codes"]),
                              (int) $result["batch_id"]
                          ); ?>
                          <?php if (!empty($result["note"])): ?>
                              &mdash; <em><?php echo esc_html(
                                  $result["note"],
                              ); ?></em>
                          <?php endif; ?>
                      </p></div>

                      <?php
                      $batch_args = [
                          "page" => "chit-view",
                          "batch_id" => (int) $result["batch_id"],
                      ];
                      $print_url = wp_nonce_url(
                          add_query_arg(
                              $batch_args + ["action" => "print_pdf"],
                              admin_url("admin.php")
                          ),
                          "chit_print_pdf"
                      );
                      $csv_url = wp_nonce_url(
                          add_query_arg(
                              $batch_args + ["action" => "export_codes"],
                              admin_url("admin.php")
                          ),
                          "chit_export_codes"
                      );
                      ?>
                      <p>
                          <a href="<?php echo esc_url(
                              $print_url
                          ); ?>" class="button button-primary" target="_blank">
                              <?php esc_html_e("Print PDF", "chit-download-codes-for-woocommerce"); ?>
                          </a>
                          <a href="<?php echo esc_url(
                              $csv_url
                          ); ?>" class="button">
                              <?php esc_html_e("Export CSV", "chit-download-codes-for-woocommerce"); ?>
                          </a>
                      </p>

                      <pre><?php echo esc_html(
                          implode("\n", $result["codes"]),
                      ); ?></pre>
                      <?php delete_transient("chit_generated_$token"); ?>
                  <?php endif;
                  ?>
              <?php
              endif; ?>

              <form method="post" action="<?php echo esc_url(
                  admin_url("admin-post.php"),
              ); ?>">
                  <input type="hidden" name="action" value="chit_generate_codes">
                  <?php wp_nonce_field("chit_generate_codes"); ?>

                  <table class="form-table"><tbody>
                      <tr>
                          <th><label for="product_id"><?php esc_html_e(
                              "Product",
                              "chit-download-codes-for-woocommerce",
                          ); ?></label></th>
                          <td>
                              <select name="product_id" id="product_id" required>
                                  <option value=""><?php esc_html_e(
                                      "— select —",
                                      "chit-download-codes-for-woocommerce",
                                  ); ?></option>
                                  <?php foreach (
                                      wc_get_products([
                                          "limit" => -1,
                                          "status" => "publish",
                                      ])
                                      as $p
                                  ): ?>
                                      <option value="<?php echo esc_attr(
                                          $p->get_id(),
                                      ); ?>">
                                          <?php echo esc_html(
                                              $p->get_name(),
                                          ); ?>
                                      </option>
                                  <?php endforeach; ?>
                              </select>
                          </td>
                      </tr>
                      <tr>
                          <th><label for="quantity"><?php esc_html_e(
                              "Quantity",
                              "chit-download-codes-for-woocommerce",
                          ); ?></label></th>
                          <td><input type="number" name="quantity" id="quantity" min="1" max="10000" value="10" required></td>
                      </tr>
                      <tr>
                          <th><label for="note"><?php esc_html_e(
                              "Note (optional)",
                              "chit-download-codes-for-woocommerce",
                          ); ?></label></th>
                          <td><input type="text" name="note" id="note" class="regular-text"></td>
                      </tr>
                  </tbody></table>

                  <?php submit_button(esc_html__("Generate codes", "chit-download-codes-for-woocommerce")); ?>
              </form>
          </div>
          <?php
    }

    public function handle_post()
    {
        check_admin_referer("chit_generate_codes");

        if (!current_user_can("manage_woocommerce")) {
            wp_die(esc_html__("No permission.", "chit-download-codes-for-woocommerce"), 403);
        }

        $product_id = absint($_POST["product_id"] ?? 0);
        $quantity = max(1, min(10000, absint($_POST["quantity"] ?? 0)));
        $note = sanitize_text_field(wp_unslash($_POST["note"] ?? ""));

        if ($product_id <= 0 || $quantity <= 0) {
            wp_safe_redirect(
                add_query_arg(
                    ["page" => "chit-generate", "error" => "invalid"],
                    admin_url("admin.php"),
                ),
            );
            exit();
        }

        try {
            $result = Chit_Batches::create(
                $product_id,
                $quantity,
                $note ?: null,
            );
        } catch (Throwable $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                wp_trigger_error(__METHOD__, 'chit generate failed: ' . $e->getMessage());
            }
            wp_safe_redirect(
                add_query_arg(
                    ["page" => "chit-generate", "error" => "failed"],
                    admin_url("admin.php"),
                ),
            );
            exit();
        }

        $token = strtolower(wp_generate_password(12, false));
        set_transient("chit_generated_$token", $result, 60);

        wp_safe_redirect(
            add_query_arg(
                ["page" => "chit-generate", "generated" => $token],
                admin_url("admin.php"),
            ),
        );
        exit();
    }
}
