<?php

namespace WHMCS\Module\Addon\OnestreamReseller;

use WHMCS\Module\Addon\OnestreamReseller\Api\Client;

class Config
{
    public static function loadModuleConfig()
    {
        $dbkeys = \Illuminate\Database\Capsule\Manager::table('tbladdonmodules')->where('module', 'onestreamreseller')->get();

        return $dbkeys;
    }

    public static function loadProductConfig($serviceId, $serviceType)
    {
        $dbkeys = \Illuminate\Database\Capsule\Manager::table('tblproducts')->where('servertype', $serviceType)->where('id', $serviceId)->get();

        return $dbkeys[0] ?? null;
    }

    public static function getConfiguredPanels()
    {
        $config = self::loadModuleConfig();

        $panels = [];

        foreach ($config as $c) {
            $matches = [];
            if (preg_match('/^s(\d+)_(.*)/', $c->setting, $matches)) {
                $panelN = $matches[1];
                $setting = $matches[2];

                $panels[$panelN][$setting] = $c->value;
            }
        }

        foreach ($panels as $id => $p) {
            if (empty($p['panel_url'])) {
                unset($panels[$id]);
            }
        }

        return $panels;
    }

    public static function getApiClient($panelNumber, $authToken = null)
    {
        $panels = self::getConfiguredPanels();

        if (empty($panels[$panelNumber])) {
            return null;
        }

        $panel = $panels[$panelNumber];

        $config = [
            'url' => $panel['panel_url'],
            'x-api-key' => $panel['api_token'],
            'x-auth-user' => $authToken ?: $panel['user_token'],
        ];

        $client = new Client($config);

        return $client;
    }

    public static function getAdminUserName()
    {
        // getting any admin user in order to perform action
        $adminData = \Illuminate\Database\Capsule\Manager::table('tbladmins')->where('disabled', '=', 0)->first();
        if (!empty($adminData)) {
            return $adminData->username;
        }
        exit('No admin exist. Why So?');
    }
}