<?php

namespace BitApps\PiPro\src\Integrations\FluentCommunity;

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

use FluentCommunity\App\Models\BaseSpace;
use FluentCommunity\App\Models\Course;

final class FluentCommunityHelper
{
    private const FLUENT_COMMUNITY_PLUGIN_INDEX = 'fluent-community/fluent-community.php';

    public static function getFeedData($feed)
    {
        if (!$feed) {
            return [];
        }

        return [
            'feed_id'              => $feed->id,
            'feed_title'           => $feed->title,
            'feed_message'         => $feed->message,
            'feed_slug'            => $feed->slug,
            'feed_type'            => $feed->type,
            'feed_content_type'    => $feed->content_type,
            'feed_privacy'         => $feed->privacy,
            'feed_status'          => $feed->status,
            'feed_is_sticky'       => $feed->is_sticky,
            'feed_comments_count'  => $feed->comments_count,
            'feed_reactions_count' => $feed->reactions_count,
            'feed_created_at'      => $feed->created_at,
            'feed_updated_at'      => $feed->updated_at,
            'feed_permalink'       => $feed->permalink ?? '',
        ];
    }

    public static function getUserData($userId)
    {
        if (!$userId) {
            return [];
        }

        $user = get_user_by('ID', $userId);
        if (!$user) {
            return [];
        }

        return [
            'user_id'           => $user->ID,
            'user_login'        => $user->user_login,
            'user_email'        => $user->user_email,
            'user_nicename'     => $user->user_nicename,
            'user_url'          => $user->user_url,
            'user_registered'   => $user->user_registered,
            'user_display_name' => $user->display_name,
            'user_avatar_url'   => get_avatar_url($user->ID),
            'user_first_name'   => $user->first_name,
            'user_last_name'    => $user->last_name,
        ];
    }

    public static function getSpaceData($spaceId)
    {
        if (!$spaceId) {
            return [];
        }

        if (!class_exists('\FluentCommunity\App\Models\BaseSpace')) {
            return [];
        }

        $space = BaseSpace::find($spaceId);
        if (!$space) {
            return [];
        }

        return [
            'space_id'           => $space->id,
            'space_title'        => $space->title,
            'space_slug'         => $space->slug,
            'space_description'  => $space->description,
            'space_privacy'      => $space->privacy,
            'space_status'       => $space->status,
            'space_member_count' => $space->member_count,
            'space_created_at'   => $space->created_at,
            'space_updated_at'   => $space->updated_at,
        ];
    }

    public static function getCommentData($comment)
    {
        if (!$comment) {
            return [];
        }

        return [
            'comment_id'         => $comment->id,
            'comment_content'    => $comment->content,
            'comment_author_id'  => $comment->user_id,
            'comment_created_at' => $comment->created_at,
            'comment_updated_at' => $comment->updated_at,
        ];
    }

    public static function getReactionData($reaction)
    {
        if (!$reaction) {
            return [];
        }

        return [
            'reaction_id'         => $reaction->id,
            'reaction_type'       => $reaction->type,
            'reaction_user_id'    => $reaction->user_id,
            'reaction_created_at' => $reaction->created_at,
        ];
    }

    // Space Event Helpers
    public static function getUserJoinsSpaceData($space, $userId, $by)
    {
        $user = get_user_by('ID', $userId);
        $spaceAttributes = $space->getAttributes();
        unset($spaceAttributes['settings']);

        $eventData = [
            'space'     => $spaceAttributes,
            'user'      => self::getUserData($userId),
            'joined_by' => $by,
            'joined_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getUserRequestsSpaceJoinData($space, $userId)
    {
        $user = get_user_by('ID', $userId);
        $spaceAttributes = $space->getAttributes();
        unset($spaceAttributes['settings']);

        $eventData = [
            'space'        => $spaceAttributes,
            'user'         => self::getUserData($userId),
            'requested_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getUserLeavesSpaceData($space, $userId, $by)
    {
        $user = get_user_by('ID', $userId);
        $spaceAttributes = $space->getAttributes();
        unset($spaceAttributes['settings']);

        $eventData = [
            'space'   => $spaceAttributes,
            'user'    => self::getUserData($userId),
            'left_by' => $by,
            'left_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getNewSpaceCreatedData($space, $data)
    {
        $spaceAttributes = $space->getAttributes();
        unset($spaceAttributes['settings']);

        $eventData = [
            'space'      => $spaceAttributes,
            'created_by' => $data['created_by'] ?? null,
            'created_at' => current_time('mysql'),
        ];

        if (isset($data['created_by'])) {
            $eventData['creator'] = self::getUserData($data['created_by']);
        }

        return $eventData;
    }

    public static function getAfterSpaceDeletedData($spaceId)
    {
        return [
            'space_id'   => $spaceId,
            'deleted_at' => current_time('mysql'),
        ];
    }

    public static function getAfterSpaceUpdatedData($space, $args)
    {
        $spaceAttributes = $space->getAttributes();
        unset($spaceAttributes['settings']);

        return [
            'space'          => $spaceAttributes,
            'updated_fields' => $args,
            'updated_at'     => current_time('mysql'),
        ];
    }

    // Feed Event Helpers
    public static function getNewFeedCreatedData($feed)
    {
        $feedData = self::getFeedData($feed);
        $feedData['space'] = self::getSpaceData($feed->space_id);
        $feedData['author'] = self::getUserData($feed->user_id);

        return $feedData;
    }

    public static function getNewSpaceFeedCreatedData($feed)
    {
        $feedData = self::getFeedData($feed);
        $feedData['space'] = self::getSpaceData($feed->space_id);
        $feedData['author'] = self::getUserData($feed->user_id);

        return $feedData;
    }

    public static function getFeedUpdatedData($feed, $args)
    {
        $feedData = self::getFeedData($feed);
        $feedData['space'] = self::getSpaceData($feed->space_id);
        $feedData['author'] = self::getUserData($feed->user_id);
        $feedData['updated_fields'] = $args;
        $feedData['updated_at'] = current_time('mysql');

        return $feedData;
    }

    public static function getFeedMentionsUserData($feed, $users)
    {
        $feedData = self::getFeedData($feed);
        $feedData['space'] = self::getSpaceData($feed->space_id);
        $feedData['author'] = self::getUserData($feed->user_id);
        $feedData['mentioned_users'] = [];

        foreach ($users as $userId) {
            $feedData['mentioned_users'][] = self::getUserData($userId);
        }

        return $feedData;
    }

    public static function getBeforeFeedDeletedData($feed)
    {
        $feedData = self::getFeedData($feed);
        $feedData['space'] = self::getSpaceData($feed->space_id);
        $feedData['author'] = self::getUserData($feed->user_id);

        return $feedData;
    }

    public static function getAfterFeedDeletedData($feedId)
    {
        return [
            'feed_id'    => $feedId,
            'deleted_at' => current_time('mysql'),
        ];
    }

    public static function getFeedReactionAddedData($reaction, $feed)
    {
        $reactionData = self::getReactionData($reaction);
        $reactionData['feed'] = self::getFeedData($feed);
        $reactionData['user'] = self::getUserData($reaction->user_id);
        $reactionData['space'] = self::getSpaceData($feed->space_id);

        return $reactionData;
    }

    // Comment Event Helpers
    public static function getNewCommentAddedData($comment, $feed)
    {
        $commentData = self::getCommentData($comment);
        $commentData['feed'] = self::getFeedData($feed);
        $commentData['author'] = self::getUserData($comment->user_id);
        $commentData['space'] = self::getSpaceData($feed->space_id);

        return $commentData;
    }

    public static function getCommentUpdatedData($comment, $feed)
    {
        $commentData = self::getCommentData($comment);
        $commentData['feed'] = self::getFeedData($feed);
        $commentData['author'] = self::getUserData($comment->user_id);
        $commentData['space'] = self::getSpaceData($feed->space_id);
        $commentData['updated_at'] = current_time('mysql');

        return $commentData;
    }

    public static function getCommentDeletedData($commentId, $feed)
    {
        return [
            'comment_id' => $commentId,
            'feed'       => self::getFeedData($feed),
            'space'      => self::getSpaceData($feed->space_id),
            'deleted_at' => current_time('mysql'),
        ];
    }

    // Course Event Helpers
    public static function getUserEnrollsInCourseData($course, $userId, $by)
    {
        $user = get_user_by('ID', $userId);
        $courseAttributes = $course->getAttributes();

        $eventData = [
            'course'      => $courseAttributes,
            'user'        => self::getUserData($userId),
            'enrolled_by' => $by,
            'enrolled_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getUserUnenrollsFromCourseData($course, $userId, $by)
    {
        $user = get_user_by('ID', $userId);
        $courseAttributes = $course->getAttributes();

        $eventData = [
            'course'        => $courseAttributes,
            'user'          => self::getUserData($userId),
            'unenrolled_by' => $by,
            'unenrolled_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getUserCompletesCourseData($course, $userId)
    {
        $user = get_user_by('ID', $userId);
        $courseAttributes = $course->getAttributes();

        $eventData = [
            'course'       => $courseAttributes,
            'user'         => self::getUserData($userId),
            'completed_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getUserCompletesLessonData($lesson, $userId)
    {
        $user = get_user_by('ID', $userId);
        $lessonAttributes = $lesson->getAttributes();

        $eventData = [
            'lesson'       => $lessonAttributes,
            'user'         => self::getUserData($userId),
            'completed_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }

    public static function getCourseCreatedData($course)
    {
        $courseAttributes = $course->getAttributes();

        return [
            'course'     => $courseAttributes,
            'created_at' => current_time('mysql'),
        ];
    }

    public static function getCourseUpdatedData($course, $args)
    {
        $courseAttributes = $course->getAttributes();

        return [
            'course'         => $courseAttributes,
            'updated_fields' => $args,
            'updated_at'     => current_time('mysql'),
        ];
    }

    public static function getCoursePublishedData($course)
    {
        $courseAttributes = $course->getAttributes();

        return [
            'course'       => $courseAttributes,
            'published_at' => current_time('mysql'),
        ];
    }

    public static function getCourseDeletedData($courseId)
    {
        return [
            'course_id'  => $courseId,
            'deleted_at' => current_time('mysql'),
        ];
    }

    public static function getLessonUpdatedData($lesson, $updatedData, $isNewlyPublished)
    {
        $lessonAttributes = $lesson->getAttributes();

        return [
            'lesson'             => $lessonAttributes,
            'updated_fields'     => $updatedData,
            'is_newly_published' => $isNewlyPublished,
            'updated_at'         => current_time('mysql'),
        ];
    }

    // User Event Helpers
    public static function getUserLeveledUpData($xprofile, $newLevel, $oldLevel)
    {
        $userId = $xprofile->user_id;
        $user = get_user_by('ID', $userId);

        $eventData = [
            'user'          => self::getUserData($userId),
            'new_level'     => $newLevel,
            'old_level'     => $oldLevel,
            'leveled_up_at' => current_time('mysql'),
        ];

        if ($user) {
            $eventData['user']['user_meta'] = wp_json_encode(get_user_meta($userId));
        }

        return $eventData;
    }
}
