<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;

final class PortalAccess
{
    public const PAGES = [
        'home' => 'Home',
        'invoices' => 'Invoices',
        'documents' => 'Documents',
        'sign' => 'Sign a paper',
        'orders' => 'My orders',
        'contract' => 'My contract',
        'service_request' => 'Service request',
        'equipment' => 'My equipment',
    ];

    public static function settings(int $tenantId): array
    {
        $row = Database::instance()->fetch(
            'SELECT * FROM tenant_commerce WHERE tenant_id = :tid',
            ['tid' => $tenantId]
        );
        if (!$row) {
            return ['customer_portal_on' => 0, 'customer_pages' => []];
        }
        $pages = [];
        if (!empty($row['customer_pages'])) {
            $d = json_decode((string) $row['customer_pages'], true);
            $pages = is_array($d) ? $d : [];
        }
        return [
            'customer_portal_on' => (int) $row['customer_portal_on'],
            'customer_pages' => $pages,
        ];
    }

    public static function portalOn(int $tenantId): bool
    {
        return !empty(self::settings($tenantId)['customer_portal_on']);
    }

    /**
     * @param array<string, mixed> $user
     * @param array<string, mixed> $tenant
     */
    public static function allows(string $page, array $user, array $tenant): bool
    {
        if ($page === 'home') {
            return true;
        }
        if (!isset(self::PAGES[$page])) {
            return false;
        }
        $settings = self::settings((int) $tenant['id']);
        if (empty($settings['customer_portal_on'])) {
            return false;
        }
        $pages = $settings['customer_pages'];
        if ($pages === []) {
            $code = (string) ($tenant['industry_code'] ?? 'distribution');
            $pages = self::defaults($code);
        }
        $override = [];
        if (!empty($user['pages'])) {
            $d = is_array($user['pages']) ? $user['pages'] : json_decode((string) $user['pages'], true);
            $override = is_array($d) ? $d : [];
        }
        if (array_key_exists($page, $override)) {
            return !empty($override[$page]);
        }
        return !empty($pages[$page]);
    }

    /** @return array<string, bool> */
    public static function defaults(string $industry): array
    {
        return [
            'invoices' => true,
            'documents' => true,
            'sign' => true,
            'orders' => $industry === 'distribution',
            'contract' => in_array($industry, ['software', 'contract'], true),
            'service_request' => $industry === 'service',
            'equipment' => $industry === 'service',
        ];
    }
}
