<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MemberTreeClosure;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class InternalController extends Controller
{
    public function dashboardSummary(Request $request): JsonResponse
    {
        $user = $request->user();

        $payload = [
            'wallet' => DB::table('wallet_balances')->where('user_id', $user->id)->first(),
            'today_income' => (float) DB::table('wallet_transactions')
                ->where('user_id', $user->id)
                ->whereDate('transacted_at', now()->toDateString())
                ->where('wallet_type', 'income')
                ->where('direction', 'credit')
                ->sum('amount'),
            'team_count' => (int) DB::table('users')->where('sponsor_id', $user->id)->count(),
        ];

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

    public function treeNode(int $userId): JsonResponse
    {
        $children = DB::table('users')->where('placement_parent_id', $userId)->get();
        $ancestors = MemberTreeClosure::query()
            ->where('descendant_id', $userId)
            ->where('depth', '>', 0)
            ->orderBy('depth')
            ->get(['ancestor_id', 'depth', 'path_leg']);

        return response()->json([
            'children' => $children,
            'ancestors' => $ancestors,
        ]);
    }
}
