<?php

declare(strict_types=1);

namespace OnoxWhmcs;

use WHMCS\Database\Capsule;

/**
 * Miscellaneous helpers for the Onoxsoft WHMCS module.
 */
class Helper
{
    /** @var array<string,string>|null */
    private static $strings = null;

    // ─── Language ─────────────────────────────────────────────────────────

    /**
     * Retrieve a translated string.
     *
     * Priority: WHMCS client language → English fallback → key itself.
     *
     * @param  string  $key  Language string key
     * @return string Translated string
     */
    public static function lang(string $key): string
    {
        if (self::$strings === null) {
            self::$strings = self::loadStrings();
        }

        return self::$strings[$key] ?? $key;
    }

    /**
     * Load the appropriate language file.
     *
     * @return array<string,string>
     */
    private static function loadStrings(): array
    {
        $langDir = __DIR__.'/../lang/';

        // Detect active language from WHMCS session (best-effort)
        $whmcsLang = 'english';
        if (function_exists('WHMCS\Config\Setting::getValue')) {
            // Not always available in module context; ignore errors
        } elseif (isset($_SESSION['Language'])) {
            $whmcsLang = strtolower((string) $_SESSION['Language']);
        }

        $langFile = $langDir.$whmcsLang.'.php';
        if (! file_exists($langFile)) {
            $langFile = $langDir.'english.php';
        }

        $_LANG = [];
        /** @noinspection PhpIncludeInspection */
        include $langFile;

        return is_array($_LANG) ? $_LANG : [];
    }

    // ─── Account ID ───────────────────────────────────────────────────────

    /**
     * Resolve the Onoxsoft account ID stored in tblhosting.subscriptionid.
     *
     * @param  array  $params  WHMCS module params
     * @return string Onoxsoft account ID
     *
     * @throws \RuntimeException if not found
     */
    public static function resolveAccountId(array $params): string
    {
        // model is a WHMCS Eloquent model instance (WHMCS 7.6+)
        $id = '';

        if (isset($params['model'])) {
            $id = (string) ($params['model']->subscriptionid ?? '');
        }

        // Fallback: direct DB read for older WHMCS versions
        if ($id === '' && function_exists('WHMCS\Database\Capsule::table')) {
            $row = Capsule::table('tblhosting')
                ->where('id', $params['serviceid'])
                ->value('subscriptionid');
            $id = (string) ($row ?? '');
        }

        if ($id === '') {
            throw new \RuntimeException(
                self::lang('account_id_missing').' (serviceid='.($params['serviceid'] ?? '?').')'
            );
        }

        return $id;
    }

    // ─── Sanitisation ─────────────────────────────────────────────────────

    /**
     * Sanitise a value for safe inclusion in HTML attributes or body.
     *
     * @param  mixed  $value
     */
    public static function e($value): string
    {
        return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}
