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

class SPG_QR
{
  const SUBDIR = 'spg-qr';

  /**
   * Get public URL to cached QR PNG for a wallet address.
   * Generates PNG in uploads/spg-qr/ if missing.
   *
   * @param string $address
   * @param string $coin
   * @param string $network
   * @param string $tag  (XRP/XLM memo/tag optional; we DON'T embed into QR by default)
   * @return string URL or '' on failure
   */
  public static function get_url($address, $coin = '', $network = '', $tag = '')
  {
    $address = trim((string) $address);
    if ($address === '') return '';

    $coin    = trim((string) $coin);
    $network = trim((string) $network);
    $tag     = trim((string) $tag);

    $payload = self::build_payload($address, $coin, $network, $tag);
    if ($payload === '') return '';

    $up = wp_upload_dir(null, false);
    if (empty($up['basedir']) || empty($up['baseurl'])) return '';

    $dir_path = trailingslashit($up['basedir']) . self::SUBDIR;
    $dir_url  = trailingslashit($up['baseurl']) . self::SUBDIR;

    if (!wp_mkdir_p($dir_path)) return '';

    // Cache key: payload + net + coin (stable)
    $hash = md5($payload . '|' . strtolower($network) . '|' . strtolower($coin));
    $file = 'spgqr_' . $hash . '.png';

    $abs = trailingslashit($dir_path) . $file;
    $url = trailingslashit($dir_url) . $file;

    if (file_exists($abs) && filesize($abs) > 0) {
      return $url;
    }

    if (!self::ensure_lib_loaded()) return '';

    // Generate a crisp QR (UI can show at 220px later)
    $level  = defined('QR_ECLEVEL_M') ? QR_ECLEVEL_M : 'M';
    $size   = 8; // module size
    $margin = 2; // quiet zone

    try {
      @QRcode::png($payload, $abs, $level, $size, $margin);
    } catch (\Throwable $e) {
      return '';
    }

    if (!file_exists($abs) || filesize($abs) <= 0) return '';
    return $url;
  }

  /**
   * What we encode inside the QR.
   * Most compatible across wallets: plain address.
   * (We will show tag/memo separately in UI.)
   */
  private static function build_payload($address, $coin, $network, $tag)
  {
    return trim((string) $address);
  }

  private static function ensure_lib_loaded()
  {
    if (class_exists('QRcode')) return true;

    // expects: SPG_PATH . 'lib/phpqrcode/qrlib.php'
    $path = defined('SPG_PATH')
      ? rtrim(SPG_PATH, '/\\') . '/lib/phpqrcode/qrlib.php'
      : '';

    if ($path === '' || !file_exists($path)) return false;

    require_once $path;
    return class_exists('QRcode');
  }
}
