<?php

namespace BitApps\PiPro\src\Integrations\FluentAffiliate;

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

use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\Services\FlowService;
use BitApps\PiPro\src\Integrations\IntegrationHelper;

final class FluentAffiliateTrigger
{
    public static function affiliateCreated($affiliateModel)
    {
        $data = Utility::jsonEncodeDecode($affiliateModel);

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

    public static function affiliateUpdated($affiliateModel, $updatedBy, $updatedData)
    {
        $data = [
            'affiliate'    => Utility::jsonEncodeDecode($affiliateModel),
            'updated_by'   => $updatedBy,
            'updated_data' => $updatedData,
        ];

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

    public static function affiliateApproved($affiliateModel)
    {
        $data = Utility::jsonEncodeDecode($affiliateModel);

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

    public static function affiliatePending($affiliateModel, $oldStatus)
    {
        $data = [
            'affiliate'  => Utility::jsonEncodeDecode($affiliateModel),
            'old_status' => $oldStatus,
        ];

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

    public static function affiliateInactivate($affiliateModel, $oldStatus)
    {
        $data = [
            'affiliate'  => Utility::jsonEncodeDecode($affiliateModel),
            'old_status' => $oldStatus,
        ];

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

    public static function affiliateDeleted($affiliateModel)
    {
        $data = Utility::jsonEncodeDecode($affiliateModel);

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

    public static function referralCreated($referralModel)
    {
        $data = Utility::jsonEncodeDecode($referralModel);

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

    public static function referralDeleted($referralModel)
    {
        $data = Utility::jsonEncodeDecode($referralModel);

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

    private static function execute($machineSlug, $data)
    {
        $flows = FlowService::exists('fluentAffiliate', $machineSlug);

        if (!$flows) {
            return;
        }

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

    // TODO:: need to implement
    private static function isPluginInstalled()
    {
        return \defined('FLUENT_AFFILIATE_VERSION');
    }
}
