<?php

namespace PloverCRM\Core\Services;

use PloverCRM\Common\LicenseChecker;
use PloverCRM\Common\Permissions;
use PloverCRM\Common\RoleManager;
use PloverCRM\Common\Utils;
use PloverCRM\Common\AdvocateProgram;
use PloverCRM\Core\Container;
use PloverCRM\Core\CRM\Schemas\ActivityTypeSchema;

/**
 * Builds the canonical workspace payload used by the app host and v2 APIs.
 */
class WorkspacePayloadBuilder
{
    private const ACTIVE_COLUMNS_OPTION = 'plover_crm_active_columns';

    private const DEFAULT_ACTIVE_COLUMNS = [
        'full_name',
        'email',
        'phone',
        'city',
        'country',
        'created_at',
        'stage-plover-crm',
    ];

    public static function build(Container $container, bool $public = false): array
    {
        $crm = $container->get('crm');
        $user = self::getCurrentUserInfo();
        $license = LicenseChecker::getStatus();

        if ($public) {
            return self::buildPublicWorkspacePayload($license, $user);
        }

        if (!$crm || !$crm->isAvailable()) {
            return [
                'id' => self::getWorkspaceId(),
                'url' => get_site_url(),
                'displayName' => get_bloginfo('name'),
                'username' => '',
                'password' => '',
                'authMode' => 'wordpressCookie',
                'hostMode' => 'wordpress',
                'lists' => [],
                'tags' => [],
                'customFields' => [],
                'activityTypes' => [],
                'standardFields' => [],
                'selectedColumns' => self::getSelectedColumns(),
                'user' => $user,
                'license' => $license,
                'setup' => WorkspaceSetupService::getState(),
                'businessInformation' => null,
                'advocateProgram' => null,
            ];
        }

        return [
            'id' => self::getWorkspaceId(),
            'url' => get_site_url(),
            'displayName' => get_bloginfo('name'),
            'username' => '',
            'password' => '',
            'authMode' => 'wordpressCookie',
            'hostMode' => 'wordpress',
            'lists' => self::getLists($crm),
            'tags' => self::getTags($crm),
            'customFields' => self::getCustomFields($crm),
            'activityTypes' => self::getActivityTypes($crm),
            'standardFields' => self::getStandardFields($crm),
            'selectedColumns' => self::getSelectedColumns(),
            'user' => $user,
            'license' => $license,
            'setup' => WorkspaceSetupService::getState(),
            'businessInformation' => Permissions::canAccessSetting('business_information', 'view')
                ? BusinessInformationService::get()
                : null,
            'advocateProgram' => AdvocateProgram::getPayload(),
        ];
    }

    private static function buildPublicWorkspacePayload(array $license, ?array $user): array
    {
        return [
            'id' => self::getWorkspaceId(),
            'url' => get_site_url(),
            'displayName' => get_bloginfo('name'),
            'username' => '',
            'password' => '',
            'authMode' => 'wordpressCookie',
            'hostMode' => 'wordpress',
            'lists' => [],
            'tags' => [],
            'customFields' => [],
            'activityTypes' => [],
            'standardFields' => [],
            'selectedColumns' => self::DEFAULT_ACTIVE_COLUMNS,
            'user' => $user,
            'license' => $license,
            'setup' => WorkspaceSetupService::getState(),
            'businessInformation' => null,
            'advocateProgram' => null,
        ];
    }

    public static function getWorkspaceId(): string
    {
        return 'wp:' . get_current_blog_id();
    }

    private static function getCurrentUserInfo(): ?array
    {
        return CurrentUserPayloadBuilder::build();
    }

    private static function getLists($crm): array
    {
        $lists = [];

        foreach ((array) $crm->getAllLists() as $list) {
            $title = (string) ($list['title'] ?? '');
            $id = (int) ($list['id'] ?? 0);

            if ($title === '' || $id <= 0) {
                continue;
            }

            $lists[$title] = $id;
        }

        return $lists;
    }

    private static function getTags($crm): array
    {
        $tags = [];

        foreach ((array) $crm->getAllTags() as $tag) {
            $title = (string) ($tag['title'] ?? '');
            $id = (int) ($tag['id'] ?? 0);

            if ($title === '' || $id <= 0) {
                continue;
            }

            $tags[$title] = $id;
        }

        return $tags;
    }

    private static function getCustomFields($crm): array
    {
        $customFields = $crm->getAllCustomFields();

        if (!is_array($customFields)) {
            return [];
        }

        foreach ($customFields as &$field) {
            $field = Utils::enhanceStageFieldWithColors($field);
        }

        return $customFields;
    }

    private static function getActivityTypes($crm): array
    {
        $crmTypes = (array) $crm->getActivityTypes();
        $crmTypeIds = array_column($crmTypes, 'id');

        $extraTypes = array_filter(
            ActivityTypeSchema::getExtraTypes(),
            static fn($type) => !in_array($type['id'], $crmTypeIds, true)
        );

        return array_values(array_merge($crmTypes, array_map(static function ($type) {
            $type['isExtra'] = true;
            return $type;
        }, $extraTypes)));
    }

    private static function getSelectedColumns(): array
    {
        $activeColumns = get_option(self::ACTIVE_COLUMNS_OPTION, self::DEFAULT_ACTIVE_COLUMNS);

        if (!is_array($activeColumns)) {
            $activeColumns = self::DEFAULT_ACTIVE_COLUMNS;
        }

        $user = wp_get_current_user();
        if (!$user || !$user->ID) {
            return array_values($activeColumns);
        }

        if (RoleManager::isSuperAdmin($user->ID)) {
            return array_values($activeColumns);
        }

        return array_values(array_filter($activeColumns, static function ($column) use ($user) {
            return RoleManager::checkFieldPermission($user->ID, (string) $column, 'read');
        }));
    }

    private static function getStandardFields($crm): array
    {
        $fields = [];

        if ($crm->getName() === 'FluentCRM') {
            global $wpdb;

            $tableName = $wpdb->prefix . 'fc_subscribers';
            $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'");

            if ($tableExists) {
                $query = "SELECT COLUMN_NAME
                          FROM INFORMATION_SCHEMA.COLUMNS
                          WHERE TABLE_NAME = '" . $tableName . "'
                          AND TABLE_SCHEMA = '" . DB_NAME . "'";

                $fields = $wpdb->get_col($query);
            }
        } else {
            $standardFields = $crm->getStandardFields();
            $fields = array_merge(
                ['id'],
                array_keys($standardFields),
                ['status', 'hash', 'created_at', 'updated_at']
            );
        }

        $fields[] = 'lists';
        $fields[] = 'tags';
        $fields[] = 'last_note';
        $fields[] = 'plover_crm_avatar';

        return array_values(array_unique($fields));
    }
}
