<?php
declare(strict_types=1);

namespace App\Models;

use App\Services\CommerceService;

final class TenantCommerce extends BaseModel
{
    protected static string $table = 'tenant_commerce';

    /** @return array<string, mixed> */
    public static function current(): array
    {
        $row = static::db()->fetch(
            'SELECT * FROM tenant_commerce WHERE tenant_id = :tid',
            ['tid' => static::tenantId()]
        );
        if (!$row) {
            return [
                'tenant_id' => static::tenantId(),
                'customer_portal_on' => 0,
                'customer_pages' => CommerceService::defaultPages(\App\Industry\Catalog::currentCode()),
                'systems' => ['orders' => 'disconnected', 'accounting' => 'disconnected', 'service' => 'disconnected'],
            ];
        }
        $row['customer_pages'] = self::decode($row['customer_pages'] ?? null);
        $row['systems'] = self::decode($row['systems'] ?? null) ?: [
            'orders' => 'disconnected',
            'accounting' => 'disconnected',
            'service' => 'disconnected',
        ];
        return $row;
    }

    /** @param array<string, mixed> $pages */
    public static function save(bool $portalOn, array $pages, array $systems): void
    {
        $cleanPages = [];
        foreach (CommerceService::PAGES as $key => $_) {
            $cleanPages[$key] = !empty($pages[$key]);
        }
        $cleanSystems = [];
        foreach (CommerceService::SYSTEMS as $key => $_) {
            $cleanSystems[$key] = (($systems[$key] ?? '') === 'connected') ? 'connected' : 'disconnected';
        }
        $existing = static::db()->fetch(
            'SELECT tenant_id FROM tenant_commerce WHERE tenant_id = :tid',
            ['tid' => static::tenantId()]
        );
        $payload = [
            'customer_portal_on' => $portalOn ? 1 : 0,
            'customer_pages' => json_encode($cleanPages, JSON_UNESCAPED_UNICODE),
            'systems' => json_encode($cleanSystems, JSON_UNESCAPED_UNICODE),
        ];
        if ($existing) {
            static::db()->query(
                'UPDATE tenant_commerce SET customer_portal_on = :on, customer_pages = :pages, systems = :sys WHERE tenant_id = :tid',
                ['on' => $payload['customer_portal_on'], 'pages' => $payload['customer_pages'], 'sys' => $payload['systems'], 'tid' => static::tenantId()]
            );
            return;
        }
        static::create([
            'tenant_id' => static::tenantId(),
            'customer_portal_on' => $payload['customer_portal_on'],
            'customer_pages' => $payload['customer_pages'],
            'systems' => $payload['systems'],
        ]);
    }

    private static function decode(mixed $raw): array
    {
        if (is_array($raw)) {
            return $raw;
        }
        if (!is_string($raw) || $raw === '') {
            return [];
        }
        $d = json_decode($raw, true);
        return is_array($d) ? $d : [];
    }
}
