<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\LegalCase;
use App\Models\Invoice;
use App\Models\Payment; // New: For cash flow
use App\Models\ChartOfAccount; // New: For Ledger
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;


class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        // --- CLIENT DASHBOARD LOGIC (Keep as is) ---
        if ($user->hasRole('client')) {
            $cases = LegalCase::where('client_id', $user->id)->latest()->get();

            $pendingInvoices = Invoice::whereHas('case', function ($q) use ($user) {
                $q->where('client_id', $user->id);
            })->where('status', '!=', 'paid')->get();

            $nextHearing = LegalCase::where('client_id', $user->id)
                ->whereNotNull('court_date')
                ->where('court_date', '>=', now())
                ->orderBy('court_date', 'asc')
                ->first();

            return view('dashboard', compact('cases', 'pendingInvoices', 'nextHearing'));
        }

        // --- SUPER ADMIN DASHBOARD LOGIC (Updated for Finance Module) ---

        // 1. FINANCIAL HEALTH (Real Cash Flow)
        // We calculate based on actual Payments recorded against specific Account Types
        $totalIncome   = Payment::whereHas('account', fn($q) => $q->where('type', 'income'))->sum('amount');
        $totalExpenses = Payment::whereHas('account', fn($q) => $q->where('type', 'expense'))->sum('amount');
        $clientFunds   = Payment::whereHas('account', fn($q) => $q->where('type', 'liability'))->sum('amount'); // Trust/Client Money

        $netProfit     = $totalIncome - $totalExpenses;

        // 2. OPERATIONAL METRICS
        $activeCases = LegalCase::where('status', 'open')->count();
        $hearingsThisWeek = LegalCase::whereBetween('court_date', [now(), now()->addDays(7)])->count();

        // Keep these invoice stats for the side widgets
        $pendingRevenue = Invoice::where('status', '!=', 'paid')->sum('total_amount');
        $overdueInvoices = Invoice::where('status', 'overdue')->count();

        // 3. CHART DATA GENERATION (Last 6 Months: Income vs Expenses)
        $months = [];
        $incomeData = [];
        $expenseData = [];

        for ($i = 5; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $monthName = $date->format('M');
            $months[] = $monthName;

            // Sum Income for this specific month
            $incomeData[] = Payment::whereHas('account', fn($q) => $q->where('type', 'income'))
                ->whereYear('payment_date', $date->year)
                ->whereMonth('payment_date', $date->month)
                ->sum('amount');

            // Sum Expenses for this specific month
            $expenseData[] = Payment::whereHas('account', fn($q) => $q->where('type', 'expense'))
                ->whereYear('payment_date', $date->year)
                ->whereMonth('payment_date', $date->month)
                ->sum('amount');
        }

        // 4. TOP ACCOUNTS SNAPSHOT (For the side widget)
        // Shows where money is coming from or going to most frequently
        $topAccounts = ChartOfAccount::withSum('payments', 'amount')
            ->orderByDesc('payments_sum_amount')
            ->take(5)
            ->get();

        // 5. ACTIVITY LOGS
        $activities = [];
        if (class_exists('\App\Models\ActivityLog')) {
            $activities = \App\Models\ActivityLog::with('user')->latest()->take(8)->get();
        } elseif (class_exists('\Spatie\Activitylog\Models\Activity')) {
            $activities = \Spatie\Activitylog\Models\Activity::with('causer')->latest()->take(8)->get();
        }

        return view('super-admin.index', compact(
            'totalIncome',
            'totalExpenses',
            'netProfit',
            'clientFunds',
            'pendingRevenue',
            'overdueInvoices',
            'activeCases',
            'hearingsThisWeek',
            'months',      // Chart Labels
            'incomeData',  // Chart Dataset 1
            'expenseData', // Chart Dataset 2
            'topAccounts', // For Widget
            'activities'
        ));
    }
}
