<?php

namespace BitApps\PiPro\src\Integrations\FluentCrm\helpers;

use BitApps\Pi\Deps\BitApps\WPValidator\Validator;
use FluentCrm\App\Models\Company;
use FluentCrm\App\Services\Helper;

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

class FluentCrmActionHelper
{
    /**
     * Get all data.
     */
    public static function getAllData(string $type)
    {
        if (!\function_exists('FluentCrmApi')) {
            return [];
        }

        $data = FluentCrmApi($type)->all();

        return [
            'response'    => $data->toArray() ?? [],
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get contact.
     */
    public static function getContact(string $idOrEmail)
    {
        if (!\function_exists('FluentCrmApi')) {
            return;
        }

        $contactApi = FluentCrmApi('contacts');

        return $contactApi->getContact($idOrEmail)->toArray() ?? [];
    }

    /**
     * Get all company.
     */
    public static function getAllCompany()
    {
        if (!self::isCompanyExists()) {
            return [];
        }

        $companies = Company::all();

        return $companies->toArray() ?? [];
    }

    /**
     * Check if company exists.
     */
    public static function isCompanyExists(): bool
    {
        return Helper::isCompanyEnabled() && class_exists('\FluentCrm\App\Models\Company');
    }

    /**
     * Check if fluent crm api not exists.
     *
     * @param array $payload
     *
     * @return null|array
     */
    public static function isFluentCrmApiNotExists($payload = [])
    {
        if (!\function_exists('FluentCrmApi')) {
            return [
                'response'    => __('FluentCRM is not installed', 'bit-pi'),
                'payload'     => $payload,
                'status_code' => 400
            ];
        }
    }

    /**
     * Validate field map.
     *
     * @param array $validationRules
     * @param array $fieldMappings
     * @param array $payload
     * @param bool $checkApiIsNotInstalled
     * @param bool $checkTagModuleExists
     * @param bool $checkListModuleExists
     * @param bool $checkCompanyModuleExists
     */
    public static function validateFieldMap(
        $fieldMappings,
        $validationRules,
        $payload = null,
        $checkApiIsNotInstalled = false,
        $checkTagModuleExists = false,
        $checkListModuleExists = false,
        $checkCompanyModuleExists = false
    ) {
        $validator = new Validator();
        $validation = $validator->make($fieldMappings, $validationRules);

        if ($validation->fails()) {
            return [
                'response'    => $validation->errors(),
                'payload'     => $payload ?? $fieldMappings,
                'status_code' => 400
            ];
        }

        // Check for module and function existence in sequence
        $moduleChecks = [
            'api' => [
                'check'        => $checkApiIsNotInstalled,
                'condition'    => \function_exists('FluentCrmApi'),
                'errorMessage' => __('FluentCRM is not installed', 'bit-pi')
            ],
            'tagModule' => [
                'check'        => $checkTagModuleExists,
                'condition'    => class_exists('\FluentCrm\App\Models\Tag'),
                'errorMessage' => __('FluentCRM tag module is not found', 'bit-pi')
            ],
            'listModule' => [
                'check'        => $checkListModuleExists,
                'condition'    => class_exists('\FluentCrm\App\Models\Lists'),
                'errorMessage' => __('FluentCRM list module is not found', 'bit-pi')
            ],
            'companyModule' => [
                'check'        => $checkCompanyModuleExists,
                'condition'    => self::isCompanyExists(),
                'errorMessage' => __('Company module disabled. You can add companies and assign contacts to companies only when it is enabled!!', 'bit-pi')
            ]
        ];

        // Loop through the module checks and return error response if any check fails
        foreach ($moduleChecks as $checkData) {
            if ($checkData['check'] && !$checkData['condition']) {
                return [
                    'response'    => $checkData['errorMessage'],
                    'payload'     => $payload ?? $fieldMappings,
                    'status_code' => 400
                ];
            }
        }
    }
}
