<?php
/**
 * thirdparty/flutterwave/flw_reusable.php
 * Safe one-time loader + wrapper for Flutterwave v3 checkout.
 *
 * Usage in your view BEFORE calling openFlwCheckout():
 *   include $FLW_HELPER;
 *   flw_emit_setup($FLW_PUBLIC_KEY, [
 *     'title'       => 'Katete Town Council',
 *     'description' => 'Property Rates Payment',
 *     'logo'        => 'https://app.kateteerp.xyz/logo.png'
 *   ]);
 */

if (!function_exists('flw_emit_setup')) {
  function flw_emit_setup($publicKey, $defaults = array()) {
    // Sanitize inputs
    $pk   = isset($publicKey) ? (string)$publicKey : '';
    $tit  = isset($defaults['title']) ? (string)$defaults['title'] : 'Payments';
    $desc = isset($defaults['description']) ? (string)$defaults['description'] : '';
    $logo = isset($defaults['logo']) ? (string)$defaults['logo'] : '';

    // Precompute JSON literals (avoid expressions in heredoc)
    $pk_json   = ($pk !== '') ? json_encode($pk) : 'null';
    $tit_json  = json_encode($tit);
    $desc_json = json_encode($desc);
    $logo_json = json_encode($logo);

    echo <<<HTML
<script>
(function() {
  // ---- Singleton state (avoid duplicate inserts across partials) ----
  if (!window.__flw) window.__flw = {};
  var state = window.__flw;

  // Public key + defaults (can be overridden per call)
  state.publicKey = {$pk_json};
  state.defaults  = {
    title: {$tit_json},
    description: {$desc_json},
    logo: {$logo_json}
  };

  // If promise already exists, don't recreate.
  if (!state.readyPromise) {
    state.readyPromise = new Promise(function(resolve, reject) {
      // If script already present and loaded
      if (window.FlutterwaveCheckout) { resolve(); return; }

      // Ensure the <script> tag is present only once
      var existing = document.querySelector('script[data-flw-v3="true"]');
      if (!existing) {
        var s = document.createElement('script');
        s.src = 'https://checkout.flutterwave.com/v3.js';
        s.async = true;
        s.defer = true;
        s.setAttribute('data-flw-v3', 'true');
        s.onload  = function(){ resolve(); };
        s.onerror = function(){ reject(new Error('Failed to load Flutterwave library.')); };
        document.head.appendChild(s);
      }

      // Poll fallback in case onload didn't fire but lib is present
      var tries = 0, iv = setInterval(function(){
        if (window.FlutterwaveCheckout) {
          clearInterval(iv); resolve();
        } else if (++tries > 150) { // ~15s
          clearInterval(iv);
          reject(new Error('Flutterwave library not loaded yet (timeout).'));
        }
      }, 100);
    });
  }

  // Expose a helper to await readiness (optional use)
  window.openFlwReady = function() { return state.readyPromise; };

  // Main entry — always await library + merge defaults safely
  window.openFlwCheckout = async function(options) {
    if (!options || typeof options !== 'object') {
      throw new Error('openFlwCheckout: options object is required.');
    }
    // Wait for library to be ready
    await state.readyPromise;

    if (!state.publicKey) {
      throw new Error('Flutterwave public key is not set.');
    }

    // Compose config (defaults → caller overrides)
    var customizations = Object.assign(
      {
        title: (state.defaults && state.defaults.title) || 'Payments',
        description: (state.defaults && state.defaults.description) || '',
        logo: (state.defaults && state.defaults.logo) || ''
      },
      (options.customizations || {})
    );

    // Safety: ensure basic required fields exist
    var cfg = Object.assign({}, options, {
      public_key: state.publicKey,
      customizations: customizations
    });

    // Final call
    return window.FlutterwaveCheckout(cfg);
  };
})();
</script>
HTML;
  }
}
