<?php

namespace BitApps\PiPro\src\Integrations\GeoDirectory;

// 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 GeoDirectoryTrigger
{
    public static function newPlaceAdded($postData, $additionalData)
    {
        if (empty($postData) || empty($postData->ID)) {
            return;
        }

        $flows = FlowService::exists('GeoDirectory', 'newPlaceAdded');

        if (!$flows) {
            return;
        }

        $postType = $postData->post_type;
        $postId = $postData->ID;

        if (!\function_exists('geodir_is_gd_post_type') || !geodir_is_gd_post_type($postType)) {
            return;
        }

        $data = [
            'user_data'   => Utility::getUserInfo($postData->post_author),
            'post_data'   => $postData,
            'categories'  => self::getTermByTaxonomy($postId, $postType . 'category'),
            'tags'        => self::getTermByTaxonomy($postId, $postType . '_tags'),
            'attachments' => self::getAttachments($postId),
            'data'        => $additionalData,

        ];


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

    private static function isPluginInstalled()
    {
        return class_exists('GeoDirectory');
    }

    private static function getTermByTaxonomy($postId, $taxonomy)
    {
        if (!taxonomy_exists($taxonomy)) {
            return [];
        }

        $postTerms = wp_get_post_terms($postId, $taxonomy);

        if (is_wp_error($postTerms) || empty($postTerms)) {
            return [];
        }

        return array_map(
            function ($term) {
                return $term->name;
            },
            $postTerms
        );
    }

    private static function getAttachments($postId)
    {
        $attachments = [];

        if (!\function_exists('geodir_get_images')) {
            return $attachments;
        }

        $images = geodir_get_images($postId);

        if (empty($images)) {
            return $attachments;
        }

        foreach ($images as $image) {
            if (!empty($image->file)) {
                $attachments[] = $image->file;
            }
        }

        return $attachments;
    }
}
