<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Credit;
use App\Models\Branch;
use App\Models\CreditBalance;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardController extends Controller
{
    /**
     * Get dashboard statistics
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStats(Request $request)
    {
        // Get current authenticated user
        $user = Auth::user();

        // Get total deposits and withdrawals from all credits (without any filters)
        $branchTotalWallet = 0;
        $branchTotalDeposits = 0;
        $totalWithdrawals = 0;

        if ($request->has('shareholder_id')) {
            // Get branch IDs for the shareholder
            $branchIds = DB::table('user_branch')
                ->where('user_id', $request->shareholder_id)
                ->pluck('branch_id');

            // Get branch totals for the shareholder's branches
            $branchTotalWallet = Branch::whereIn('id', $branchIds)->sum('wallet');
            $branchTotalDeposits = Branch::whereIn('id', $branchIds)->sum('total_deposit');
        }

        $userTotalWallet = 0;
        $userTotalDeposit = 0;

        if ($request->has('shareholder_id')) {
            $userTotalWallet = CreditBalance::where('shareholder_id', $request->shareholder_id)->sum('wallet');
            $userTotalDeposit = CreditBalance::where('shareholder_id', $request->shareholder_id)->sum('balance');
        }

        $totalWithdrawals = ($branchTotalDeposits + $userTotalDeposit) - ($branchTotalWallet + $userTotalWallet);

        // Get today's date
        $today = Carbon::today();

        // Today's deposits and withdrawals (with branch filter if specified)
        // $todayQuery = Credit::query()
        //     ->where('status', 'approved')
        //     ->where('active', true)
        //     ->when($request->has('branch_id'), function ($q) use ($request) {
        //         return $q->where('branch_id', $request->branch_id);
        //     })
        //     ->when($request->has('shareholder_id'), function ($q) use ($request) {
        //         return $q->where('shareholder_id', $request->shareholder_id);
        //     });

        $todayDeposits = Credit::where('type', 'deposit')
            ->where('shareholder_id', $request->shareholder_id)
            ->orWhereNull('shareholder_id')
            ->whereDate('created_at', $today)
            ->sum('amount');

        // $todayWithdrawals = (clone $todayQuery)
        //     ->where('type', 'withdrawal')
        //     ->whereDate('created_at', $today)
        //     ->sum('amount');

        // Today's credit inbound (deposits - withdrawals)
        // $todayCreditInbound = $todayDeposits - $todayWithdrawals;

        // Get user's credit balance directly from Credits table
        $userCreditBalance = 0;
        // $creditDetails = [];
        if (!$user->hasRole('staff')) {
            // For admin and shareholders, get balance directly from CreditBalance table
            $creditBalanceQuery = CreditBalance::where('shareholder_id', $user->id)
                ->when($request->has('branch_id'), function ($q) use ($request) {
                    return $q->where('branch_id', $request->branch_id);
                });

            // Get total balance
            $userCreditBalance = (clone $creditBalanceQuery)
                ->sum('wallet') ?? 0;

            // Get detailed records by branch
            // $creditDetails = (clone $creditBalanceQuery)
            //     ->select('branch_id', 'wallet')
            //     ->with('branch:id,name')
            //     ->get()
            //     ->map(function ($branchBalance) {
            //         return [
            //             'branch_id' => $branchBalance->branch_id,
            //             'branch_name' => $branchBalance->branch->name,
            //             'balance' => $branchBalance->wallet,
            //         ];
            //     })
            //     ->values()
            //     ->toArray();
        }

        // Count of deposits and withdrawals (including all statuses)
        // $depositCount = Credit::where('type', 'deposit')
        //     ->when($request->has('branch_id'), function ($q) use ($request) {
        //         return $q->where('branch_id', $request->branch_id);
        //     })
        //     ->when($user->hasRole('shareholder') && !$user->hasRole('admin'), function ($q) use ($user) {
        //         $branchIds = $user->branches()->pluck('branches.id')->toArray();
        //         if (!empty($branchIds)) {
        //             return $q->whereIn('branch_id', $branchIds);
        //         }
        //         return $q;
        //     })
        //     ->count();

        // $withdrawalCount = Credit::where('type', 'withdrawal')
        //     ->when($request->has('branch_id'), function ($q) use ($request) {
        //         return $q->where('branch_id', $request->branch_id);
        //     })
        //     ->when($user->hasRole('shareholder') && !$user->hasRole('admin'), function ($q) use ($user) {
        //         $branchIds = $user->branches()->pluck('branches.id')->toArray();
        //         if (!empty($branchIds)) {
        //             return $q->whereIn('branch_id', $branchIds);
        //         }
        //         return $q;
        //     })
        //     ->count();

        return response()->json([
            'status' => true,
            'message' => 'Dashboard statistics retrieved successfully',
            'data' => [
                'total_wallet' => number_format($branchTotalWallet + $userTotalWallet, 2),
                'total_deposits' => number_format($branchTotalDeposits + $userTotalDeposit, 2),
                'total_withdrawals' => number_format($totalWithdrawals, 2),
                'credit_balance' =>  number_format($userCreditBalance, 2),
                'today_deposits' => number_format($todayDeposits, 2),
                // 'deposit_count' => $depositCount,
                // 'withdrawal_count' => $withdrawalCount,
                // 'today_credit_inbound' => number_format($todayCreditInbound, 2),
                // 'today_withdrawals' => $todayWithdrawals,
            ]
        ]);
    }
}
