<?php

namespace BitApps\PiPro\src\Integrations\PaidMembershipPro;

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


use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\Services\FlowService;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Response;
use BitApps\PiPro\src\Integrations\IntegrationHelper;

final class PaidMembershipProTrigger
{
    public static function afterChangeMembershipLevelByAdmin($levelId, $userId)
    {
        if (empty($levelId)) {
            return;
        }

        $levelCombineData = self::getLevelCombineData($userId, $levelId);

        return self::execute('adminChangesMembershipLevel', $levelCombineData, $levelId, 'pro-level-id');
    }

    public static function cancelMembershipLevel($levelId, $userId, $cancelLevelId)
    {
        if (absint($levelId) !== 0) {
            return;
        }

        $levelCombineData = self::getLevelCombineData($userId, $cancelLevelId);

        return self::execute('cancelMembershipLevel', $levelCombineData, $cancelLevelId, 'pro-level-id');
    }

    public static function afterCheckout($userId, $morder)
    {
        $user = $morder->getUser();
        $userId = $user->ID;
        $membership = $morder->getMembershipLevel();
        $membershipId = $membership->id;

        $levelCombineData = self::getLevelCombineData($userId, $membershipId);

        return self::execute('membershipLevelOnCheckout', $levelCombineData, $membershipId, 'pro-level-id');
    }

    public static function expiryMembershipLevel($userId, $membershipId)
    {
        $levelCombineData = self::getLevelCombineData($userId, $membershipId);

        return self::execute('membershipLevelExpiry', $levelCombineData, $membershipId, 'pro-level-id');
    }

    public static function membershipLevelChanged($oldLevelData)
    {
        if (empty($oldLevelData) || !\function_exists('pmpro_getMembershipLevelsForUser')) {
            return;
        }

        $currentIndexPosition = key($oldLevelData);

        $userId = $currentIndexPosition;

        $data = [
            'old_level_data' => $oldLevelData[$userId],
            'new_level_data' => pmpro_getMembershipLevelsForUser($userId),
            'user_data'      => Utility::getUserInfo($userId)
        ];

        return self::execute('membershipLevelChanged', $data);
    }

    public static function getAllPaidMembershipProLevel()
    {
        global $wpdb;
        $levels = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->pmpro_membership_levels} ORDER BY id ASC"
            )
        );

        $allMembership = [
            [
                'value' => 'any',
                'label' => __('Any Membership Level', 'bit-pi')
            ],
        ];

        if (empty($levels)) {
            return $allMembership;
        }

        foreach ($levels as $level) {
            $allMembership[] = [
                'value' => $level->id,
                'label' => $level->name,
            ];
        }

        return Response::success($allMembership);
    }

    private static function getLevelCombineData($userId, $levelId)
    {
        $userData = Utility::getUserInfo($userId);
        $levelData = self::getLevelInfo($levelId);

        return array_merge($userData, (array) reset($levelData));
    }

    private static function getLevelInfo($id)
    {
        global $wpdb;

        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->pmpro_membership_levels} WHERE id = %d",
                $id
            )
        );
    }

    private static function execute($machineSlug, $data, $value = null, $keyName = 'form-id')
    {
        $flows = FlowService::exists('paidMembershipPro', $machineSlug);

        if (!$flows) {
            return;
        }

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

    // TODO:: need to implement
    private static function isPluginInstalled()
    {
        return is_plugin_active('paid-memberships-pro/paid-memberships-pro.php');
    }
}
