<?php

declare(strict_types=1);

namespace App\Http\Controllers\Pages;

use Hypervel\Http\Request;
use App\Models\User;
use Hypervel\Support\Facades\Auth;

use Hypervel\Support\Facades\Response;
use App\Enums\UserTypes;

use App\Http\Controllers\Pages\PageController;

class UserListPageController
{
    public static function ListChildren($id)
    {
        $users = User::findOrFail($id);
        $children = $users->getAllDescendants()->map(function ($child) {
            $store_hashkey = null;
            if ($child->hasRole(['store owner', 'store manager'])) {
                $store = \App\Models\Market\Store::where('owner_id', $child->id)
                    ->orWhere('manager_id', $child->id)
                    ->first();
                $store_hashkey = $store?->hashkey;
            }

            return [
                'id' => $child->id,
                'hashkey' => $child->hashkey,
                'mobile_number' => $child->mobile_number,
                'total_balance' => $child->total_balance,
                'acct_type' => $child->acct_type,
                'is_active' => (bool)$child->active,
                'name' => $child->name,
                'fullname' => $child->fullname,
                'nickname' => $child->nickname,
                'username' => $child->username,
                'store_hashkey' => $store_hashkey,
            ];
        });

        return $children;
    }

    public static function ListChildrenofCurrentUser()
    {
        if (Auth::user()->acct_type === UserTypes::ULTIMATE) {
            return User::all()->map(function ($user) {
                $store_hashkey = null;
                if ($user->hasRole(['store owner', 'store manager'])) {
                    $store = \App\Models\Market\Store::where('owner_id', $user->id)
                        ->orWhere('manager_id', $user->id)
                        ->first();
                    $store_hashkey = $store?->hashkey;
                }

                return [
                    'id' => $user->id,
                    'hashkey' => $user->hashkey,
                    'mobile_number' => $user->mobile_number,
                    'total_balance' => $user->total_balance,
                    'acct_type' => $user->acct_type,
                    'is_active' => (bool)$user->active,
                    'name' => $user->name,
                    'fullname' => $user->fullname,
                    'nickname' => $user->nickname,
                    'username' => $user->username,
                    'store_hashkey' => $store_hashkey,
                ];
            });
        } else {
            return self::ListChildren(Auth::id());
        }
    }

    public static function Response_ListChildrenofCurrentUser()
    {
        $currentuser_children = self::ListChildrenofCurrentUser();
        
        return Response::json([
            'success' => true,
            'users' => $currentuser_children
        ], 200);
    }

}
