<?php

declare(strict_types=1);

use WHMCS\Database\Capsule;

final class HexaGameCloudProductMapping
{
    public static function resolvePlanSlug(array $params, string $fallback = 'free'): string
    {
        $productId = (int) ($params['pid'] ?? 0);
        if ($productId <= 0) {
            return $params['configoption1'] ?: $fallback;
        }

        try {
            $mapping = Capsule::table('mod_hexagamecloud_product_mappings')
                ->where('whmcs_product_id', $productId)
                ->where('is_active', 1)
                ->first();

            if ($mapping && !empty($mapping->plan_slug)) {
                return (string) $mapping->plan_slug;
            }
        } catch (Throwable) {
            // Mapping table may not exist before addon activation
        }

        return $params['configoption1'] ?: $fallback;
    }

    public static function resolveSoftwareFamily(array $params, string $fallback = 'VANILLA'): string
    {
        $productId = (int) ($params['pid'] ?? 0);
        if ($productId <= 0) {
            return $params['configoption3'] ?: $fallback;
        }

        try {
            $mapping = Capsule::table('mod_hexagamecloud_product_mappings')
                ->where('whmcs_product_id', $productId)
                ->where('is_active', 1)
                ->first();

            if ($mapping && !empty($mapping->default_software)) {
                return (string) $mapping->default_software;
            }
        } catch (Throwable) {
        }

        return $params['configoption3'] ?: $fallback;
    }

    public static function resolveMinecraftVersion(array $params, string $fallback = '1.21.1'): string
    {
        $productId = (int) ($params['pid'] ?? 0);
        if ($productId <= 0) {
            return $params['configoption2'] ?: $fallback;
        }

        try {
            $mapping = Capsule::table('mod_hexagamecloud_product_mappings')
                ->where('whmcs_product_id', $productId)
                ->where('is_active', 1)
                ->first();

            if ($mapping && !empty($mapping->default_version)) {
                return (string) $mapping->default_version;
            }
        } catch (Throwable) {
        }

        return $params['configoption2'] ?: $fallback;
    }
}
