<?php

namespace App\Http\Controllers\API\Chat;

use Illuminate\Support\Facades\DB;

use App\Http\Controllers\API\ApiController;
use App\Models\Group;

/**
 * Class Groups
 *
 * @package App\Http\Controllers\API\Chat
 */
class Groups extends ApiController
{

    /**
     * Returns a list with usergroups
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $results = [];
        $this->syncGroups();
        $this->user = $this->user->fresh();

        foreach ($this->user->groups as $group) {
            $users = [];

            if (count($group->users) > 2 || $group->groupname === 'one2one') {
                foreach ($group->users as $user) {
                    $users[] = [
                        'oid'         => $user->oid,
                        'firstname'   => $user->firstname,
                        'lastname'    => $user->lastname,
                        'mobile'      => $user->mobile,
                        'picture'     => $user->getAvatar([ 'width' => 40, 'height' => 40 ]),
                        'is_employee' => $user->is_employee ? true : false
                    ];
                }

                $employeeUsers = $group->users->filter(function ($user) {
                    return $user->is_employee;
                });

                $groupInfo = $this->getGroupInfo($group);
                $lastMessage = $group->messages()->orderBy('created_at', 'DESC')->first();

                $results[] = [
                    'oid'           => $group->oid,
                    'name'          => $groupInfo['group_name'],
                    'avatar'        => $groupInfo['group_avatar'],
                    'mobile'        => $groupInfo['mobile'],
                    'lastmessage'   => ($lastMessage) ? $lastMessage->apiOutputData() : null,
                    'users'         => $users,
                    'onlyemployees' => ($group->users->count() === $employeeUsers->count()) ? true : false
                ];
            }
        }

        return $this->response
            ->setResponse([
                'groups' => $results
            ])
            ->setSuccess(true)
            ->toJson();
    }

    /**
     * Sync users groups
     */
    private function syncGroups()
    {
        foreach ($this->getGroupUsersIds() as $userId) {
            $groupExists = DB::table('user2group AS firstRel')
                ->select(DB::raw('COUNT(1) as total'))
                ->leftJoin('user2group as secondRel', 'firstRel.groupoid', '=', 'secondRel.groupoid')
                ->leftJoin('group as groupTbl', 'groupTbl.oid', '=', 'firstRel.groupoid')
                ->where('firstRel.useroid', $this->user->oid)
                ->where('secondRel.useroid', $userId)
                ->where('groupTbl.groupname', 'one2one')
                ->first();

            if ($groupExists->total == 0) {
                $group = Group::create([
                    'groupname' => 'one2one',
                    'groupid'   => microtime()
                ]);
                $group->users()->sync([ $this->user->oid, $userId ]);
            }
        }
    }

    /**
     * Get group users ids, unique
     *
     * @return array
     */
    private function getGroupUsersIds()
    {
        $ids = [];
        foreach ($this->user->groups as $group) {
            foreach ($group->users as $user) {
                if ($user->oid !== $this->user->oid && null !== $group->groupname) {
                    $ids[] = $user->oid;
                }
            }
        }

        return array_unique($ids);
    }

    /**
     * Get group additional infos from user
     *
     * @param \App\Models\Group $group
     * @return array
     */
    protected function getGroupInfo(Group $group)
    {
        $groupInfo = [
            'group_name'   => $group->groupname,
            'group_avatar' => '',
            'mobile'       => null
        ];

        // If the group is one to one
        if ($group->users->count() === 2) {
            $usersWithoutLoggedUser = $group->users->keyBy('oid');
            $usersWithoutLoggedUser->forget($this->user->oid);
            $otherUser = $usersWithoutLoggedUser->first();
            $groupInfo['group_name'] = ($groupInfo['group_name'] === 'one2one') ? $otherUser->fullname() : $groupInfo['group_name'];
            $groupInfo['group_avatar'] = $otherUser->getAvatar([ 'width' => 40, 'height' => 40 ]);
            ( ! $otherUser->mobile) ?: $groupInfo['mobile'] = $otherUser->mobile;
        }

        return $groupInfo;
    }
}