<?php

namespace BitApps\PiPro\src\Integrations\MailMint;

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

use BitApps\Pi\Services\FlowService;
use BitApps\PiPro\src\Integrations\IntegrationHelper;
use Mint\MRM\DataBase\Models\ContactGroupModel;
use Mint\MRM\DataBase\Models\ContactModel;

final class MailMintTrigger
{
    /**
     * Handle form submission trigger.
     *
     * @param int $formId    The form ID
     * @param int $contactId The contact ID
     */
    public static function formSubmitted($formId, $contactId)
    {
        if (!self::isValidFormSubmission($formId, $contactId)) {
            return;
        }


        $data = [
            'form_id'    => $formId,
            'contact_id' => $contactId,
            'contact'    => ContactModel::get($contactId),
        ];

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

    /**
     * Handle contact created trigger.
     *
     * @param int $contactId The contact ID
     */
    public static function contactCreated($contactId)
    {
        if (!self::isValidContactId($contactId)) {
            return;
        }

        return self::execute('contactCreated', ContactModel::get($contactId));
    }

    /**
     * Handle contact deleted trigger.
     *
     * @param int $contactId The contact ID
     */
    public static function contactDeleted($contactId)
    {
        if (!class_exists('Mint\MRM\DataBase\Models\ContactModel')) {
            return;
        }

        return self::execute('contactDeleted', ContactModel::get($contactId));
    }

    /**
     * Handle tags added to contact trigger.
     *
     * @param array $tags
     * @param int $contactId The contact ID
     */
    public static function tagsAddedToContact($tags, $contactId)
    {
        if (!self::isValidTagsOrListsData($tags, $contactId)) {
            return;
        }

        $data = [
            'tags'    => self::getTagsOrListsData($tags),
            'contact' => ContactModel::get($contactId),
        ];

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

    /**
     * Handle tags added to contact trigger.
     *
     * @param array $lists
     * @param int $contactId The contact ID
     */
    public static function listsAddedToContact($lists, $contactId)
    {
        if (!self::isValidTagsOrListsData($lists, $contactId)) {
            return;
        }

        $data = [
            'lists'   => self::getTagsOrListsData($lists),
            'contact' => ContactModel::get($contactId),
        ];

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

    /**
     * Handle campaign created trigger.
     *
     * @param int $campaignId
     * @param array $campaignData
     */
    public static function campaignCreated($campaignId, $campaignData)
    {
        $campaignData['campaign_id'] = $campaignId;

        return self::execute('campaignCreated', $campaignData);
    }

    /**
     * Handle campaign start trigger.
     *
     * @param array $data
     */
    public static function campaignEmailSent($data)
    {
        return self::execute('campaignEmailSent', $data);
    }

    /**
     * Execute the trigger.
     *
     * @param string $machineSlug
     * @param array  $data
     */
    private static function execute($machineSlug, $data)
    {
        $flows = FlowService::exists('MailMint', $machineSlug);
        if (!$flows) {
            return;
        }

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

    /**
     * Validate form submission data.
     *
     * @param int $formId    The form ID
     * @param int $contactId The contact ID
     *
     * @return bool True if valid
     */
    private static function isValidFormSubmission($formId, $contactId): bool
    {
        return !empty($formId)
            && class_exists('Mint\MRM\DataBase\Models\ContactModel')
            && ContactModel::is_contact_ids_exists([$contactId]);
    }

    /**
     * Validate contact ID.
     *
     * @param int $contactId The contact ID
     *
     * @return bool True if valid
     */
    private static function isValidContactId($contactId): bool
    {
        return class_exists('Mint\MRM\DataBase\Models\ContactModel')
            && ContactModel::is_contact_ids_exists([$contactId]);
    }

    /**
     * Validate tags or lists data with contact ID.
     *
     * @param array $items     Array of tags or lists
     * @param int   $contactId The contact ID
     *
     * @return bool True if valid
     */
    private static function isValidTagsOrListsData($items, $contactId): bool
    {
        return !empty($items)
            && class_exists('Mint\MRM\DataBase\Models\ContactGroupModel')
            && class_exists('Mint\MRM\DataBase\Models\ContactModel')
            && ContactModel::is_contact_ids_exists([$contactId]);
    }

    /**
     * Get tags or lists data.
     *
     * @param array $items Array of tags or lists
     *
     * @return array
     */
    private static function getTagsOrListsData($items)
    {
        $data = [];

        foreach ($items as $item) {
            if (isset($item['created_at']) || empty($item['id'])) {
                continue;
            }

            $data[] = ContactGroupModel::get($item['id']);
        }

        return $data;
    }
}
