<?php

namespace FluentCrm\App\Http\Controllers;

use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Support\Arr;
use FluentCrm\Framework\Http\Request\Request;
use FluentCrm\App\Models\Subscriber;

/**
 *  ImporterController - REST API Handler Class
 *
 *  REST API Handler
 *
 * @package FluentCrm\App\Http
 *
 * @version 1.0.0
 */
class ImporterController extends Controller
{
    public function getDrivers()
    {
        /**
         * Determine the list of contact import providers for FluentCRM.
         *
         * This filter allows you to modify the list of available import providers
         * in the FluentCRM plugin. By default, it includes CSV File and WordPress Users.
         *
         * @since 2.7.0
         *
         * @param array {
         *     An associative array of import providers.
         *
         *     @type array csv {
         *         Details for the CSV File import provider.
         *
         *         @type string $label    The label for the provider.
         *         @type string $logo     The URL to the provider's logo.
         *         @type bool   $disabled Whether the provider is disabled.
         *     }
         *     @type array users {
         *         Details for the WordPress Users import provider.
         *
         *         @type string $label    The label for the provider.
         *         @type string $logo     The URL to the provider's logo.
         *         @type bool   $disabled Whether the provider is disabled.
         *     }
         * }
         */
        $drivers = apply_filters('fluent_crm/import_providers', [
            'csv'   => [
                'label'    => __('CSV File', 'fluent-crm'),
                'logo'     => fluentCrmMix('images/csv.svg'),
                'disabled' => false
            ],
            'users' => [
                'label'    => __('WordPress Users', 'fluent-crm'),
                'logo'     => fluentCrmMix('images/wordpress.svg'),
                'disabled' => false
            ]
        ]);

        if (defined('FLUENTCART_VERSION')) {
            $drivers['fluent_cart'] = [
                'label'    => __('FluentCart', 'fluent-crm'),
                'logo'     => fluentCrmMix('images/fluent-cart-dark.svg'),
                'disabled' => false
            ];
        }   
        
        if ($proDrivers = $this->getProDrivers()) {
            $drivers = array_merge($drivers, $proDrivers);
        }

        return [
            'drivers' => $drivers
        ];
    }

    public function getDriver(Request $request, $driver)
    {
        if ($driver == 'users') {
            return $this->processUserDriver($request);
        }

        /**
         * Determine the import driver response (CSV).
         *
         * This filter allows modification of the import driver response based on the specified driver.
         *
         * @since 2.7.0
         *
         * @param bool   The response to be filtered or not. Default false.
         * @param object $request  The request object containing import data.
         */
        $response = apply_filters('fluent_crm/get_import_driver_' . $driver, false, $request);

        if (!$response || is_wp_error($response)) {
            $message = __('Sorry no driver found for this import', 'fluent-crm');
            if (is_wp_error($response)) {
                $message = $response->get_error_message();
            }
            return $this->sendError([
                'message' => $message
            ]);
        }

        return $response;
    }

    public function importData(Request $request, $driver)
    {
        $config = $request->get('config', []);
        $page = $request->getSafe('importing_page', 'intval', 1);

        if ($driver == 'users') {
            return $this->processUserImport($config, $page);
        }

        /**
         * Determine the response after importing data using a specific driver (CSV).
         *
         * This filter allows you to modify the response after the import process
         * using a specified driver.
         *
         * @since 2.7.0
         *
         * @param bool   The response to be filtered or not. Default false.
         * @param array  $config   The configuration array for the import process.
         * @param int    $page     The current page number being processed.
         */
        $response = apply_filters('fluent_crm/post_import_driver_' . $driver, false, $config, $page);

        if (!$response || is_wp_error($response)) {
            $message = __('Sorry no driver found for this import', 'fluent-crm');
            if (is_wp_error($response)) {
                $message = $response->get_error_message();
            }
            return $this->sendError([
                'message' => $message
            ]);
        }

        return $response;
    }

    private function processUserDriver($request)
    {
        $summary = $request->get('summary');

        if ($summary) {
            $config = $request->get('config');

            $userQuery = new \WP_User_Query([
                'role__in' => Arr::get($config, 'roles'),
                'number'   => 5,
                'fields'   => ['ID', 'display_name', 'user_email'],
            ]);

            $users = $userQuery->get_results();
            $total = $userQuery->get_total();

            $formattedUsers = [];

            foreach ($users as $user) {
                $formattedUsers[] = [
                    'name'  => $user->display_name,
                    'email' => $user->user_email
                ];
            }

            return $this->send([
                'import_info' => [
                    'subscribers'       => $formattedUsers,
                    'total'             => $total,
                    'has_list_config'   => true,
                    'has_tag_config'    => true,
                    'has_status_config' => true,
                    'has_update_config' => true,
                    'has_silent_config' => true
                ]]);
        }

        if (!function_exists('get_editable_roles')) {
            require_once(ABSPATH . '/wp-admin/includes/user.php');
        }
        $roles = \get_editable_roles();

        $formattedRoles = [];

        foreach ($roles as $roleKey => $role) {
            $formattedRoles[] = [
                'id'    => $roleKey,
                'label' => $role['name']
            ];
        }

        $infoSvg = '<span class="fc-inline-help-icon" aria-hidden="true" style="display:inline-flex;vertical-align:middle">'
            . '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">'
            . '<path d="M8 14C4.6862 14 2 11.3138 2 8C2 4.6862 4.6862 2 8 2C11.3138 2 14 4.6862 14 8C14 11.3138 11.3138 14 8 14ZM7.4 7.4V11H8.6V7.4H7.4ZM7.4 5V6.2H8.6V5H7.4Z" fill="currentColor"/>'
            . '</svg></span>';

        return [
            'config' => [
                'roles' => []
            ],
            'fields' => [
                'roles' => [
                    'label'              => __('Select User Roles', 'fluent-crm'),
                    'inline_help'        => $infoSvg . ' ' . __('Please check the user roles that you want to import as contact', 'fluent-crm'),
                    'type'               => 'checkbox-group',
                    'options'            => $formattedRoles,
                    'has_all_selector'   => true,
                    'all_selector_label' => __('All', 'fluent-crm')
                ]
            ],
            'labels' => [
                'step_2' => __('Next [Review Data]', 'fluent-crm'),
                'step_3' => __('Import Users Now', 'fluent-crm')
            ]
        ];
    }

    private function processUsers($users, $inputs)
    {
        $subscribers = [];
        foreach ($users as $user) {
            $subscriber = Helper::getWPMapUserInfo($user);
            $subscriber['source'] = 'wp_users';
            if (isset($subscriber['email']) && $subscriber['email']) {
                $subscribers[] = $subscriber;
            }
        }

        $sendDoubleOptin = Arr::get($inputs, 'double_optin_email') == 'yes';

        return Subscriber::import(
            $subscribers,
            Arr::get($inputs, 'tags', []),
            Arr::get($inputs, 'lists', []),
            Arr::get($inputs, 'update', ''),
            Arr::get($inputs, 'status', ''),
            $sendDoubleOptin
        );
    }

    private function processUserImport($config, $page)
    {
        $inputs = Arr::only($config, [
            'map', 'tags', 'lists', 'roles', 'update', 'status', 'double_optin_email', 'import_silently'
        ]);


        /**
         * Determine the number of subscribers to process per request while importing.
         *
         * This filter allows you to modify the number of subscribers that are processed in each request.
         *
         * @since 2.7.0
         * 
         * @param int $limit The number of subscribers to process per request. Default is 100.
         */
        $limit = apply_filters('fluent_crm/import_users_limit_per_request', 100);

        $userQuery = new \WP_User_Query([
            'role__in' => $inputs['roles'],
            'number'   => $limit,
            'offset'   => ($page - 1) * $limit
        ]);

        if (Arr::get($inputs, 'import_silently') == 'yes') {
            if (!defined('FLUENTCRM_DISABLE_TAG_LIST_EVENTS')) {
                define('FLUENTCRM_DISABLE_TAG_LIST_EVENTS', true);
            }
        }

        $total = $userQuery->get_total();
        $users = $userQuery->get_results();
        if ($users) {
            $this->processUsers($users, $inputs);
        }

        $hasRecords = !!count($users);

        return $this->sendSuccess([
            'page_total'   => ceil($total / $limit),
            'record_total' => $total,
            'has_more'     => $hasRecords,
            'current_page' => $page,
            'next_page'    => $page + 1
        ]);
    }

    private function getProDrivers()
    {
        $drivers = [];

        if (defined('FLUENTCAMPAIGN')) {
            return $drivers;
        }

        if (defined('LLMS_PLUGIN_FILE')) {
            $drivers['lifterlms'] = [
                'label'            => __('LifterLMS', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/lifterlms.png'),
                'disabled'         => true,
                'disabled_message' => __('Import LifterLMS students by course and groups then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        if (defined('LEARNDASH_VERSION')) {
            $drivers['learndash'] = [
                'label'            => __('LearnDash', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/learndash.png'),
                'disabled'         => true,
                'disabled_message' => __('Import LearnDash students by course and groups then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        if (defined('TUTOR_VERSION')) {
            $drivers['tutorlms'] = [
                'label'            => __('TutorLMS', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/tutorlms.jpg'),
                'disabled'         => true,
                'disabled_message' => __('Import TutorLMS students by course then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        if (defined('PMPRO_VERSION')) {
            $drivers['pmpro'] = [
                'label'            => __('Paid Membership Pro', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/pmpro.png'),
                'disabled'         => true,
                'disabled_message' => __('Import Paid Membership Pro members by membership levels then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        if (defined('WLM3_PLUGIN_VERSION')) {
            $drivers['wishlist_member'] = [
                'label'            => __('Wishlist member', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/wishlist_member.png'),
                'disabled'         => true,
                'disabled_message' => __('Import Wishlist members by membership levels then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        if (class_exists('\Restrict_Content_Pro')) {
            $drivers['rcp'] = [
                'label'            => __('Restrict Content Pro', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/rcp.png'),
                'disabled'         => true,
                'disabled_message' => __('Import Restrict Content Pro members by membership levels then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        if (defined('BP_REQUIRED_PHP_VERSION') && function_exists('\buddypress')) {

            $pluginName = 'BuddyPress';
            $logo = fluentCrmMix('images/buddypress.png');

            if (defined('BP_PLATFORM_VERSION')) {
                $pluginName = 'BuddyBoss';
                $logo = fluentCrmMix('images/buddyboss.svg');
            }

            $drivers['buddypress'] = [
                'label'            => $pluginName,
                'logo'             => $logo,
                'disabled'         => true,
                /* translators: %s: plugin name */
                'disabled_message' => sprintf(__('Import %s members by member groups and member types then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm'), $pluginName)
            ];
        }

        if (defined('LP_PLUGIN_FILE')) {
            $drivers['learnpress'] = [
                'label'            => __('LearnPress', 'fluent-crm'),
                'logo'             => fluentCrmMix('images/learnpress.png'),
                'disabled'         => true,
                'disabled_message' => __('Import LearnPress students by course then segment by associate tags. This is a pro feature. Please upgrade to activate this feature', 'fluent-crm')
            ];
        }

        return $drivers;
    }
}
