<?php

namespace PaymentPage;

if ( ! defined( 'ABSPATH' ) ) exit;

use WP_Query;
use PaymentPage\PostTypes\Form as FormPostType;

class PostTypes {

  /**
   * @var null|PostTypes;
   */
  protected static $_instance = null;

  /**
   * @return PostTypes
   */
  public static function instance(): PostTypes {
    if (self::$_instance === null) {
      self::$_instance = new self();
    }

    return self::$_instance;
  }

  public ?FormPostType $form = null;

  public function setup() {
    $this->form = new FormPostType();

    add_action( 'init', array( $this, '_register_post_types' ), 10 );
    add_action( 'init', array( $this, '_flush_rewrites_once_per_version' ), 11 );
  }

  public function _register_post_types() {
    $this->form->register_post_type();
  }

  /**
   * (Phase 41 / 1.5.0) Version-gated rewrite-rules flush.
   *
   * Why this exists: `register_activation_hook` doesn't reliably fire on
   * Freemius-managed plugins because the Freemius opt-in screen hijacks the
   * post-activation redirect (observed first-hand on Cloudways during
   * Phase 37 install — the activation hook fired BEFORE CPTs were registered,
   * so the cached rewrite rules in `wp_options.rewrite_rules` did NOT contain
   * the `payment-form/{slug}/` pattern). Result: every payment form created
   * post-install returned 404 on its frontend permalink until an admin
   * manually re-saved Permalinks settings.
   *
   * Fix: at `init` priority 11 (just after we register the CPT at 10), check
   * a one-shot option. If the stored version doesn't match the current
   * PAYMENT_PAGE_VERSION, call `flush_rewrite_rules()` exactly once + store
   * the new version. Subsequent requests skip the flush (cheap option read).
   * On every version bump the flush runs again, which is the right behavior
   * if 1.5.x ever changes a rewrite slug.
   *
   * Cost: one extra `get_option()` per request (negligible — the option is
   * autoloaded), and one `flush_rewrite_rules()` per upgrade (one-time write).
   */
  public function _flush_rewrites_once_per_version() {
    $option_key      = 'payment_page_rewrite_flush_version';
    $stored_version  = get_option( $option_key );
    if ( $stored_version === PAYMENT_PAGE_VERSION ) {
      return;
    }
    try {
      flush_rewrite_rules( false ); // false = don't write .htaccess; rewrite_rules option is enough
    } catch ( \Throwable $e ) {
      // Never fatal a request on a flush failure — log and move on.
      error_log( 'Payment Page: rewrite-rules flush failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    }
    update_option( $option_key, PAYMENT_PAGE_VERSION, true );
  }

}