<?php

namespace BitApps\PiPro\src\Integrations\EssentialAddonsElementor;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

use BitApps\Pi\Services\FlowService;
use BitApps\PiPro\src\Integrations\IntegrationHelper;
use WP_User;

final class EssentialAddonsElementorTrigger
{
    public static function userLogin(string $userLogin, object $user): void
    {
        self::execute(__FUNCTION__, $user);
    }

    public static function userRegistration(int $userId, array $userData): void
    {
        if (empty($userId)) {
            return;
        }

        $user = get_user_by('id', $userId);

        if (!$user) {
            return;
        }

        self::execute(__FUNCTION__, $user, $userData);
    }

    public static function isPluginInstalled(): bool
    {
        return is_plugin_active('essential-addons-for-elementor-lite/essential_adons_elementor.php')
            || is_plugin_active('essential-addons-elementor/essential_adons_elementor.php');
    }

    private static function formatUserData(object $user, array $additionalData = []): array
    {
        if (!$user instanceof WP_User) {
            return [];
        }

        $userData = [
            'user_id'         => $user->ID,
            'username'        => $user->user_login,
            'user_login'      => $user->user_login,
            'user_email'      => $user->user_email,
            'email'           => $user->user_email,
            'first_name'      => $user->first_name,
            'last_name'       => $user->last_name,
            'display_name'    => $user->display_name,
            'user_url'        => $user->user_url,
            'user_registered' => $user->user_registered,
            'nickname'        => get_user_meta($user->ID, 'nickname', true),
            'description'     => get_user_meta($user->ID, 'description', true),
            'roles'           => implode(', ', $user->roles),
        ];

        if ($additionalData) {
            $userData = array_merge($userData, $additionalData);
        }

        $userMeta = get_user_meta($user->ID);
        foreach ($userMeta as $key => $value) {
            if (!isset($userData[$key]) && strpos($key, '_') !== 0) {
                $userData[$key] = \is_array($value) && \count($value) === 1 ? reset($value) : $value;
            }
        }

        unset($userData['user_pass']);

        return $userData;
    }

    private static function execute(string $machineSlug, object $user, ?array $additionalData = []): void
    {
        $data = self::formatUserData($user, $additionalData);

        if (empty($data)) {
            return;
        }

        $flows = FlowService::exists('essentialAddonsElementor', $machineSlug);

        if (!$flows) {
            return;
        }

        IntegrationHelper::handleFlowForForm($flows, $data);
    }
}
