<?php

declare(strict_types=1);

use WHMCS\Database\Capsule;

final class HexaGameCloudProductMappingStorage
{
    public function listMappings(): array
    {
        return Capsule::table('mod_hexagamecloud_product_mappings')
            ->orderBy('whmcs_product_id', 'asc')
            ->get()
            ->map(static fn ($row) => (array) $row)
            ->all();
    }

    public function upsertMapping(array $input): void
    {
        Capsule::table('mod_hexagamecloud_product_mappings')->updateOrInsert(
            ['whmcs_product_id' => (int) $input['whmcs_product_id']],
            [
                'whmcs_product_name' => (string) ($input['whmcs_product_name'] ?? ''),
                'plan_slug' => (string) $input['plan_slug'],
                'default_edition' => (string) ($input['default_edition'] ?? 'JAVA'),
                'default_software' => (string) ($input['default_software'] ?? 'VANILLA'),
                'default_version' => (string) ($input['default_version'] ?? '1.21.1'),
                'is_active' => !empty($input['is_active']) ? 1 : 0,
                'updated_at' => gmdate('Y-m-d H:i:s'),
            ]
        );
    }

    public function deleteMapping(int $productId): void
    {
        Capsule::table('mod_hexagamecloud_product_mappings')
            ->where('whmcs_product_id', $productId)
            ->delete();
    }

    public function listWhmcsProducts(): array
    {
        return Capsule::table('tblproducts')
            ->where('servertype', 'hexagamecloud')
            ->orderBy('name', 'asc')
            ->get(['id', 'name', 'gid'])
            ->map(static fn ($row) => (array) $row)
            ->all();
    }
}
