<?php

namespace BitApps\PiPro\src\Integrations\FluentCommunity;

use Exception;
use FluentCommunity\App\Functions\Utility;
use FluentCommunity\App\Models\User;
use FluentCommunity\App\Services\FeedsHelper;
use FluentCommunity\App\Services\Helper;
use FluentCommunity\App\Services\ProfileHelper;
use FluentCommunity\Modules\Course\Services\CourseHelper;

if (!\defined('ABSPATH')) {
    exit;
}

class FluentCommunityService
{
    private $nodeInfoProvider;

    public function __construct($nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function addUserToSpace()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $spaceId = $fields['space_id'];
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];
            $role = $fields['role'] ?? 'member';
            $by = 'by_automation';

            // Use FluentCommunity Helper
            Helper::addToSpace($spaceId, $userId, $role, $by);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'   => true,
                    'message'  => __('User added to space successfully', 'bit-pi'),
                    'space_id' => $spaceId,
                    'user_id'  => $userId,
                    'role'     => $role,
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function removeUserFromSpace()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();

        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $spaceId = $fields['space_id'];
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];
            $by = 'by_automation';
            // Use FluentCommunity Helper
            Helper::removeFromSpace($spaceId, $userId, $by);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'   => true,
                    'message'  => __('User removed from space successfully', 'bit-pi'),
                    'space_id' => $spaceId,
                    'user_id'  => $userId,
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function getUserSpaceList()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            // Use FluentCommunity Helper
            $spaces = Helper::getUserSpaceIds($userId);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'    => true,
                    'message'   => __('User spaces list fetched successfully', 'bit-pi'),
                    'user_id'   => $userId,
                    'space_ids' => wp_json_encode($spaces),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function getAllSpacesList()
    {
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            // Use FluentCommunity Utility
            $spaces = Utility::getSpaces();

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'  => true,
                    'message' => __('All spaces list fetched successfully', 'bit-pi'),
                    'spaces'  => wp_json_encode($spaces),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function getSpaceUsersList()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $spaceId = $fields['space_id'];

            // Use FluentCommunity Model
            $users = User::whereHas(
                'space_pivot',
                function ($q) use ($spaceId) {
                    $q->where('space_id', $spaceId);
                }
            )->get();

            $spaceUsers = [];
            foreach ($users as $user) {
                $spaceUsers[] = [
                    'user_id'      => $user->ID,
                    'user_email'   => $user->user_email,
                    'display_name' => $user->display_name,
                    'user_login'   => $user->user_login,
                ];
            }

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'   => true,
                    'message'  => __('Space users list fetched successfully', 'bit-pi'),
                    'space_id' => $spaceId,
                    'users'    => wp_json_encode($spaceUsers),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function addUserToCourse()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $courseId = $fields['course_id'];
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            // Use FluentCommunity CourseHelper
            CourseHelper::enrollCourse($courseId, $userId);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'    => true,
                    'message'   => __('User enrolled in course successfully', 'bit-pi'),
                    'course_id' => $courseId,
                    'user_id'   => $userId,
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function removeUserFromCourse()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $courseId = $fields['course_id'];
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            // Use FluentCommunity CourseHelper
            CourseHelper::leaveCourse($courseId, $userId);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'    => true,
                    'message'   => __('User unenrolled from course successfully', 'bit-pi'),
                    'course_id' => $courseId,
                    'user_id'   => $userId,
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function addUserToMultipleCourses()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $courseIds = explode(',', $fields['course_ids']);
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            // Use FluentCommunity CourseHelper
            CourseHelper::enrollCourses($courseIds, $userId);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'     => true,
                    'message'    => __('User enrolled in multiple courses successfully', 'bit-pi'),
                    'course_ids' => $fields['course_ids'],
                    'user_id'    => $userId,
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function removeUserFromMultipleCourses()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $courseIds = explode(',', $fields['course_ids']);
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            // Use FluentCommunity CourseHelper
            CourseHelper::leaveCourses($courseIds, $userId);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'     => true,
                    'message'    => __('User unenrolled from multiple courses successfully', 'bit-pi'),
                    'course_ids' => $fields['course_ids'],
                    'user_id'    => $userId,
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function getUserCoursesList()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            // Use FluentCommunity CourseHelper
            $courseHelper = new CourseHelper();
            $courses = $courseHelper->getUserCourses($userId);

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'  => true,
                    'message' => __('User courses list fetched successfully', 'bit-pi'),
                    'user_id' => $userId,
                    'courses' => wp_json_encode($courses),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function getAllCoursesList()
    {
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            // Use FluentCommunity Utility
            $courses = Utility::getCourses();

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'  => true,
                    'message' => __('All courses list fetched successfully', 'bit-pi'),
                    'courses' => wp_json_encode($courses),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function createNewPostInFeed()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $spaceId = $fields['space_id'];
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];
            $title = $fields['title'];
            $message = $fields['message'];
            $image = isset($fields['image_url']) ? $fields['image_url'] : '';
            $sendAnnouncement = isset($fields['announcement_email']) ? $fields['announcement_email'] : 'no';
            $embedContentType = isset($fields['embed_content_type']) ? $fields['embed_content_type'] : 'image';
            $iframeHtml = isset($fields['iframe_html']) ? $fields['iframe_html'] : '';

            $feedData = [
                'message'  => stripslashes($message),
                'title'    => stripslashes($title),
                'space_id' => (int) $spaceId,
                'user_id'  => $userId,
            ];

            // Handle media URL
            if (!empty($image) && $embedContentType !== 'iframe_html' && $embedContentType !== 'giphy') {
                $supportedImages = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg'];
                if (\in_array(strtolower(substr($image, -4)), $supportedImages)) {
                    $feedData['message'] = $message . "\n\n ![]({$image})";
                } else {
                    $feedData['media'] = [
                        'url'  => $image,
                        'type' => 'oembed',
                    ];
                }
            }

            // Handle iframe HTML embed
            if ($embedContentType === 'iframe_html' && $iframeHtml !== '') {
                $feedData['media'] = [
                    'url'          => $image,
                    'type'         => 'iframe_html',
                    'html'         => stripslashes($iframeHtml),
                    'content_type' => 'video',
                ];
            }

            // Handle scheduled post
            if (isset($fields['scheduled_at']) && $fields['scheduled_at'] !== '') {
                $feedData['scheduled_at'] = $fields['scheduled_at'];
                $feed = $this->createScheduledFeed($feedData);
            } else {
                $feed = FeedsHelper::createFeed($feedData);
            }

            if (is_wp_error($feed)) {
                return [
                    'status_code' => 400,
                    'payload'     => [],
                    'response'    => [
                        'status'  => false,
                        'message' => $feed->get_error_message(),
                    ],
                ];
            }

            // Handle Giphy media
            if ($embedContentType === 'giphy' && $image !== '') {
                $feedMeta = $feed->getAttributes();
                $feedMeta = maybe_unserialize($feedMeta['meta']);

                $giphyMeta = [
                    'image'    => $image,
                    'height'   => '500',
                    'width'    => '500',
                    'type'     => 'image',
                    'provider' => 'giphy'
                ];

                $feedMeta['media_preview'] = $giphyMeta;
                $feed->setMetaAttribute($feedMeta);
                $feed->save();
            }

            // Handle announcement email
            if ($sendAnnouncement === 'yes') {
                $feedMeta = $feed->getAttributes();
                $feedMeta = maybe_unserialize($feedMeta['meta']);
                $feedMeta['send_announcement_email'] = 'yes';
                $feed->setMetaAttribute($feedMeta);
                $feed->save();
            }

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'   => true,
                    'message'  => __('Post created in feed successfully', 'bit-pi'),
                    'space_id' => $spaceId,
                    'user_id'  => $userId,
                    'feed_id'  => $feed->id,
                    'title'    => $title,
                    'feed_url' => $feed->getPermalink(),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function createNewPollInFeed()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $spaceId = $fields['space_id'];
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];
            $title = $fields['title'];
            $message = $fields['message'];
            $pollOptions = array_map('trim', explode(',', $fields['poll_options']));

            $feedData = [
                'message'  => stripslashes($message),
                'title'    => stripslashes($title),
                'space_id' => (int) $spaceId,
                'user_id'  => $userId,
                'survey'   => 'survey',
            ];

            // Use FluentCommunity FeedsHelper
            $feed = FeedsHelper::createFeed($feedData);

            if (is_wp_error($feed)) {
                return [
                    'status_code' => 400,
                    'payload'     => [],
                    'response'    => [
                        'status'  => false,
                        'message' => $feed->get_error_message(),
                    ],
                ];
            }

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'        => true,
                    'message'       => __('Poll created in feed successfully', 'bit-pi'),
                    'space_id'      => $spaceId,
                    'user_id'       => $userId,
                    'feed_id'       => $feed->id,
                    'poll_question' => $title,
                    'poll_options'  => $pollOptions,
                    'feed_url'      => $feed->getPermalink(),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function getUserCommunityProfile()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            $user = get_user_by('ID', $userId);
            if (!$user) {
                return [
                    'status_code' => 404,
                    'payload'     => [],
                    'response'    => [
                        'status'  => false,
                        'message' => __('User not found', 'bit-pi'),
                    ],
                ];
            }

            // Get user spaces
            $spaces = Helper::getUserSpaces($userId);

            // Get user courses
            $courseHelper = new CourseHelper();
            $courses = $courseHelper->getUserCourses($userId);

            $profile = [
                'user_id'         => $user->ID,
                'user_login'      => $user->user_login,
                'user_email'      => $user->user_email,
                'display_name'    => $user->display_name,
                'first_name'      => $user->first_name,
                'last_name'       => $user->last_name,
                'user_registered' => $user->user_registered,
                'avatar_url'      => get_avatar_url($user->ID),
                'spaces'          => $spaces,
                'courses'         => $courses,
            ];

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'  => true,
                    'message' => __('User community profile retrieved successfully', 'bit-pi'),
                    'profile' => wp_json_encode($profile),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function verifyUserProfile()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];

            $user = get_user_by('ID', $userId);
            if (!$user) {
                return [
                    'status_code' => 404,
                    'payload'     => [],
                    'response'    => [
                        'status'  => false,
                        'message' => __('User not found', 'bit-pi'),
                    ],
                ];
            }

            // Update user meta to mark as verified
            update_user_meta($userId, 'fluent_community_verified', true);
            update_user_meta($userId, 'fluent_community_verified_at', current_time('mysql'));

            return [
                'status_code' => 200,
                'payload'     => [],
                'response'    => [
                    'status'      => true,
                    'message'     => __('User profile verified successfully', 'bit-pi'),
                    'user_id'     => $userId,
                    'verified_at' => current_time('mysql'),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    public function changeMemberStatus()
    {
        $fields = $this->nodeInfoProvider->getFieldMapData();
        $pluginCheck = $this->checkPluginActive();
        if ($pluginCheck) {
            return $pluginCheck;
        }

        try {
            $userId = isset($fields['user_id']) && is_email($fields['user_id']) ? email_exists($fields['user_id']) : (int) $fields['user_id'];
            $status = $fields['status'];

            // Get user profile using FluentCommunity ProfileHelper
            $profile = ProfileHelper::getProfile($userId);

            if ($profile) {
                $profile->status = $status;
                $profile->save();

                return [
                    'status_code' => 200,
                    'payload'     => [],
                    'response'    => [
                        'message' => __('Member status updated successfully', 'bit-pi'),
                        'user_id' => $userId,
                        'status'  => $status,
                    ],
                ];
            }

            return [
                'status_code' => 404,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => __('User profile not found', 'bit-pi'),
                ],
            ];
        } catch (Exception $e) {
            return [
                'status_code' => 500,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => $e->getMessage(),
                ],
            ];
        }
    }

    private function createScheduledFeed($feedData)
    {
        // This method should use the FlowMattic createScheduledFeed method
        // For now, we'll use the regular createFeed method
        return FeedsHelper::createFeed($feedData);
    }

    /**
     * Check if Fluent Community plugin is active.
     *
     * @return null|array Returns error response array if plugin is not active, null if active
     */
    private function checkPluginActive()
    {
        if (!is_plugin_active('fluent-community/fluent-community.php')) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => [
                    'status'  => false,
                    'message' => __('Fluent Community plugin is not active', 'bit-pi'),
                ],
            ];
        }
    }
}
