<?php

namespace BitApps\PiPro\src\Integrations\MailerPress;

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

use BitApps\Pi\Deps\BitApps\WPValidator\Validator;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Response;
use MailerPress\Core\Kernel;
use MailerPress\Models\Contacts;

final class MailerPressHelper
{
    /**
     * Get all MailerPress lists.
     */
    public static function getLists()
    {
        if (!class_exists('\MailerPress\Core\Kernel')) {
            return Response::error(__('MailerPress is not installed or activated', 'bit-pi'));
        }

        $lists = [];

        if (\function_exists('mailerpress_get_lists')) {
            $lists = array_map(
                function ($list) {
                    return [
                        'value' => $list->list_id ?? $list['list_id'],
                        'label' => $list->name ?? $list['name'],
                    ];
                },
                mailerpress_get_lists()
            );
        }

        if (empty($lists)) {
            global $wpdb;
            $tableName = $wpdb->prefix . 'mailerpress_lists';

            $tableExists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tableName));

            if ($tableExists) {
                $lists = array_map(
                    function ($list) {
                        return [
                            'value' => $list['list_id'],
                            'label' => $list['name'],
                        ];
                    },
                    $wpdb->get_results("SELECT list_id, name FROM {$tableName}", ARRAY_A)
                );
            }
        }

        return Response::success($lists);
    }

    /**
     * Get all MailerPress tags.
     */
    public static function getTags()
    {
        if (!class_exists('\MailerPress\Core\Kernel')) {
            return Response::error(__('MailerPress is not installed or activated', 'bit-pi'));
        }

        $tags = [];

        if (\function_exists('mailerpress_get_tags')) {
            $tags = array_map(
                function ($tag) {
                    return [
                        'value' => $tag->tag_id ?? $tag['tag_id'],
                        'label' => $tag->name ?? $tag['name'],
                    ];
                },
                mailerpress_get_tags()
            );
        }

        if (empty($tags)) {
            global $wpdb;
            $tableName = $wpdb->prefix . 'mailerpress_tags';

            $tableExists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tableName));

            if ($tableExists) {
                $tags = array_map(
                    function ($tag) {
                        return [
                            'value' => $tag['tag_id'],
                            'label' => $tag['name'],
                        ];
                    },
                    $wpdb->get_results("SELECT tag_id, name FROM {$tableName}", ARRAY_A)
                );
            }
        }

        return Response::success($tags);
    }

    /**
     * Convert string to array.
     *
     * @param array|string  $value
     * @param string $separator
     *
     * @return array
     */
    public static function convertStringToArray($value, $separator = ',')
    {
        return \is_array($value) ? $value : array_map('intval', array_filter(explode($separator, $value)));
    }

    /**
     * Get contact data by email.
     *
     * @param string $email
     *
     * @return null|array
     */
    public static function getContactData($email)
    {
        if (class_exists('\MailerPress\Core\Kernel') && class_exists('\MailerPress\Models\Contacts')) {
            $contactsModel = Kernel::getContainer()->get(Contacts::class);
            $contact = $contactsModel->getContactByEmail($email);

            if ($contact) {
                return (array) $contact;
            }
        }

        global $wpdb;
        $tableName = $wpdb->prefix . 'mailerpress_contact';

        $contact = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$tableName} WHERE email = %s",
                $email
            ),
            ARRAY_A
        );

        return $contact ? $contact : null;
    }

    /**
     * Get contact data by ID.
     *
     * @param int $contactId
     *
     * @return null|array
     */
    public static function getContactDataById($contactId)
    {
        if (class_exists('\MailerPress\Core\Kernel') && class_exists('\MailerPress\Models\Contacts')) {
            $contactsModel = Kernel::getContainer()->get(Contacts::class);
            $contact = $contactsModel->get((int) $contactId);

            if ($contact) {
                return (array) $contact;
            }
        }

        global $wpdb;
        $tableName = $wpdb->prefix . 'mailerpress_contact';

        $contact = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$tableName} WHERE contact_id = %d",
                $contactId
            ),
            ARRAY_A
        );

        return $contact ?? null;
    }

    /**
     * Validate field map.
     *
     * @param array $fieldMappings
     * @param array $validationRules
     * @param null|array $payload
     *
     * @return null|array
     */
    public static function validateFieldMap($fieldMappings, $validationRules, $payload = null)
    {
        $validator = new Validator();
        $validation = $validator->make($fieldMappings, $validationRules);

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

    /**
     * Process tags or lists.
     *
     * @param array $data
     *
     * @return array
     */
    public static function processTagsOrLists($data)
    {
        return array_map(
            function ($id) {
                return ['id' => $id];
            },
            self::convertStringToArray($data)
        );
    }
}
