<?php

namespace App\Helpers;

use App\Auth\XenForoUser;
use App\Models\Entry;
use App\Models\News;
use App\Services\XenforoApiService;

class XenForoHelpers {

    const array XF_AVATAR_COLORS = ['#FF6B6B','#FF9F43','#48DBFB','#1DD1A1','#5F27CD','#341f97','#EE5A24','#009432'];

    /**
     * Have XenForo default profile picture letter.
     *
     * @param ?XenForoUser $user If null, default : actual user.
     *
     * @return string
     */
    public static function getAvatarLetter( ?XenForoUser $user = null ): string {
        if( $user === null ) {
            $user = \Auth::user();
            if( $user === null ) {
                return '';
            }
        }
        return strtoupper(mb_substr($user->data->username, 0, 1));
    }

    public static function getAvatarColor( ?XenForoUser $user = null ): string {
        if( $user === null ) {
            $user = \Auth::user();
            if( $user === null ) {
                return '';
            }
        }
        return self::XF_AVATAR_COLORS[ crc32( $user->data->username ) % count( self::XF_AVATAR_COLORS ) ];
    }

    public static function updateEntriesCount( int $userId ): void
    {
        $count = Entry::where('user_id', $userId)->where('state','published')->count();
        $service = app(XenforoApiService::class);
        $service->updateEntriesCount( $count, $userId );
    }

    public static function entryApproved( Entry|News $entry ): void
    {
        // 1. Update XF Entry count.
        self::updateEntriesCount( $entry->user_id );

        // 2. Send a private message
        if( \Auth::user()->user_id === $entry->user_id ) {
            return;
        }

        $moderator = \Auth::user()->username;
        $title = "Entry approved : {$entry->title}";
        $message = "Your entry {$entry->title} has been approved by {$moderator}.";

        $service = app(XenForoApiService::class);

        $service->createConversation([ $entry->user_id ], $title, $message, false, false);
    }

    public static function entryRejected( Entry|News $entry ): void
    {
        // 1. Update XF Entry count.
        self::updateEntriesCount( $entry->user_id );

        // 2. Send a private message
        /*
        if( \Auth::user()->user_id === $entry->user_id ) {
            return;
        }
        */

        $moderator = \Auth::user()->username;
        $title = "Entry rejected : {$entry->title}";
        $message = "Your entry {$entry->title} has been rejected by {$moderator}.\nReason: {$entry->staff_comment}\n\nYou have 7 days to edit your entry before it is permanently deleted.";

        $service = app(XenForoApiService::class);

        $service->createConversation([ $entry->user_id ], $title, $message, false, false);
    }
}
