<?php

namespace App\Http\Controllers\Api\Scim;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Role;
use App\User;
use App\Models\ApiCredential;

class GroupController extends Controller
{

    /**
     * Display a listing of groups.
     *
     * @param \Illuminate\Http\Request $request The incoming HTTP request.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the paginated list of groups.
     */
    public function index(Request $request)
    {
        $groupData = $request->all();

        \Log::info('Logging group create data:', $groupData);

        $startIndex = $request->query('startIndex', 1);
        $count = $request->query('count', 2);

        $response = [
            'schemas' => ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],
            'totalResults' => 0,
            'startIndex' => $startIndex,
            'itemsPerPage' => $count,
            'Resources' => []
        ];

        return response()->json($response);
    }


    /**
     * Create a new group.
     *
     * @param \Illuminate\Http\Request $request The incoming HTTP request containing the SCIM data.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the created group data or an error response.
     */
    public function create(Request $request)
    {
        $groupData = $request->all();

        \Log::info('Logging group create data:', $groupData);

        $role = Role::where('name', $groupData['displayName'])->first();

        if (!$role) {
            return response()->json([
                'schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'],
                'status' => '404',
                'detail' => 'Group not found.',
            ], 404);
        }

        return response()->json([
            'id' => $role->id,
            'displayName' => $role->name,
            'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:Group'],
        ]);
    }


    /**
     * Update an existing group.
     *
     * @param \Illuminate\Http\Request $request The incoming HTTP request containing the SCIM data.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the updated group data or an error response.
     */
    public function update(Request $request)
    {
        $groupData = $request->all();

        \Log::info('Logging group update data:', $groupData);

        $role = Role::find($groupData['id']);

        if (!$role) {
            return response()->json([
                'schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'],
                'status' => '404',
                'detail' => 'Group not found.',
            ], 404);
        }

        $defaultRole = Role::find(ApiCredential::whereSlug('okta_scim')->value('role_id'))
            ?? Role::where('name', 'Employee')->first();

        $existingUsers = User::where('user_type_id', $role->id)->where('okta_synced', 1)->get();

        foreach ($existingUsers as $userData) {
            $userData->removeRole($role->name);
            $userData->assignRole($defaultRole->name);
            $userData->update(['user_type_id' => $defaultRole->id]);
        }

        $users = $groupData['members'];

        if (count($users) > 0) {
            foreach ($users as $user) {
                $userData = User::with('userType')->find($user['value']);

                if ($userData) {
                    if ($userData->userType->name != $role->name) {
                        $userData->removeRole($defaultRole->name);

                        $userData->assignRole($role->name);

                        $userData->update([
                            'user_type_id' => $role->id,
                        ]);
                    }
                }
            }
        }

        return response()->json([
            'id' => $role->id,
            'displayName' => $role->name,
            'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:Group'],
        ]);
    }


    /**
     * Update an existing group.
     *
     * @param \Illuminate\Http\Request $request The incoming HTTP request containing the SCIM data.
     *
     * @return void
     */
    public function updateGroup(Request $request)
    {
        $groupData = $request->all();

        \Log::info('Logging group remove data:', $groupData);
    }


    /**
     * Retrieve a group by ID.
     *
     * @param int $id The ID of the group to be retrieved.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the group data or an error response.
     */
    public function getGroup($id)
    {
        \Log::info('Logging group fetch data');

        $members = [];

        $role = Role::find($id);

        $users = User::where('user_type_id', $role->id)->get();

        foreach ($users as $user) {
            $members[] = [
                'value' => $user->id,
                "display" => $user->email
            ];
        }

        if (!$role) {
            return response()->json([
                'schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'],
                'status' => '404',
                'detail' => 'Group not found.',
            ], 404);
        }

        return response()->json([
            'id' => $role->id,
            'displayName' => $role->name,
            'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:Group'],
            'members' => $members
        ]);
    }
}
