<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\IntercompanyLoan;
use App\Models\ProfitSweepTransaction;
use App\Models\SuperAdminFinancial;
use App\Models\SuperAdminBankAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SuperAdminDashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        if (!$user->isSuperAdmin()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        // Handle date range filtering
        $fromDate = $request->input('from_date');
        $toDate = $request->input('to_date');
        
        // Build loan query with date filtering
        $loanQuery = IntercompanyLoan::where('is_super_admin_lender', true);
        if ($fromDate && $toDate) {
            $loanQuery->whereBetween('created_at', [$fromDate, $toDate]);
        }
        
        // Build sweep query with date filtering
        $sweepQuery = ProfitSweepTransaction::where('is_super_admin_recipient', true);
        if ($fromDate && $toDate) {
            $sweepQuery->whereBetween('sweep_date', [$fromDate, $toDate]);
        }
        
        if ($fromDate && $toDate) {
            // Calculate financials for the date range using direct aggregation
            $fromDateObj = \Carbon\Carbon::parse($fromDate)->startOfDay();
            $toDateObj = \Carbon\Carbon::parse($toDate)->endOfDay();

            // Revenue: profit sweeps + loan repayments within range
            $profitSweepsRange = ProfitSweepTransaction::where('is_super_admin_recipient', true)
                ->whereBetween('sweep_date', [$fromDateObj, $toDateObj])
                ->whereIn('status', ['completed', 'processed'])
                ->sum('actual_amount');

            $loanRepaymentsRange = DB::table('loan_repayments')
                ->join('intercompany_loans', 'loan_repayments.loan_id', '=', 'intercompany_loans.id')
                ->where('intercompany_loans.is_super_admin_lender', true)
                ->whereBetween('loan_repayments.paid_at', [$fromDateObj, $toDateObj])
                ->whereIn('loan_repayments.status', ['paid', 'confirmed'])
                ->sum('loan_repayments.total_amount');

            $totalRevenue = (float)$profitSweepsRange + (float)$loanRepaymentsRange;

            // Expenses: loan disbursements within range + any payable invoices (if applicable)
            $disbursementsRange = IntercompanyLoan::where('is_super_admin_lender', true)
                ->whereBetween('disbursement_date', [$fromDateObj, $toDateObj])
                ->where('status', 'approved')
                ->sum('principal_amount');

            $totalExpenses = (float)$disbursementsRange;

            $financials = (object) [
                'year_month' => $fromDate . ' to ' . $toDate,
                'revenue' => $totalRevenue,
                'expenses' => $totalExpenses,
                'net_profit' => $totalRevenue - $totalExpenses,
                'cash_balance' => (float) SuperAdminBankAccount::sum('current_balance'),
            ];
        } else {
            // Get Super Admin current month financials
            $currentMonth = now()->format('Y-m');
            $financials = SuperAdminFinancial::recalculateMonth($currentMonth);
        }

        // Get all companies cash balance
        $totalCompaniesCash = Company::sum('cash_balance');

        // Get Super Admin bank accounts
        $bankAccounts = SuperAdminBankAccount::getActive();
        $totalBankBalance = $bankAccounts->sum('current_balance');

        // Loan statistics
        $loansGiven = (clone $loanQuery)->count();
        $activeLoans = (clone $loanQuery)
            ->where('status', 'approved')
            ->count();
        $totalLoaned = (clone $loanQuery)
            ->sum('principal_amount');
        
        // Calculate total repaid from actual confirmed repayments (including partial payments)
        $totalRepaid = DB::table('loan_repayments')
            ->join('intercompany_loans', 'loan_repayments.loan_id', '=', 'intercompany_loans.id')
            ->where('intercompany_loans.is_super_admin_lender', true)
            ->whereIn('loan_repayments.status', ['confirmed', 'paid']);
        
        if ($fromDate && $toDate) {
            $totalRepaid->whereBetween('loan_repayments.payment_date', [$fromDate, $toDate]);
        }
        
        $totalRepaid = $totalRepaid->sum('loan_repayments.total_amount');

        // Calculate total interest earned from repayments in the filtered range
        $totalInterestQ = DB::table('loan_repayments')
            ->join('intercompany_loans', 'loan_repayments.loan_id', '=', 'intercompany_loans.id')
            ->where('intercompany_loans.is_super_admin_lender', true)
            ->whereIn('loan_repayments.status', ['confirmed', 'paid']);
        if ($fromDate && $toDate) {
            $totalInterestQ->whereBetween('loan_repayments.paid_at', [$fromDate, $toDate]);
        }
        $totalInterest = (float) $totalInterestQ->sum('loan_repayments.interest_amount');

        // Profit sweep statistics
        $sweepsReceived = (clone $sweepQuery)->count();
        $totalSwept = (clone $sweepQuery)
            ->whereIn('status', ['completed', 'processed'])
            ->sum('actual_amount');

        // Recent loans
        $recentLoans = (clone $loanQuery)
            ->with('borrower')
            ->latest()
            ->take(5)
            ->get();

        // Recent sweeps (ordered by sweep_date desc)
        $recentSweeps = (clone $sweepQuery)
            ->with('fromCompany')
            ->orderBy('sweep_date', 'desc')
            ->take(5)
            ->get();

        // Companies overview
        $companies = Company::select('id', 'name', 'cash_balance', 'revenue', 'expenses_manual', 'net_profit')
            ->get()
            ->map(function ($c) {
                return [
                    'id' => $c->id,
                    'name' => $c->name,
                    'cash_balance' => (float) $c->cash_balance,
                    'revenue' => (float) $c->revenue,
                    'expenses' => (float) $c->expenses_manual,
                    'net_profit' => (float) $c->net_profit,
                ];
            });

        // Historical financial data for charts (last 6 months)
        $historicalData = [];
        for ($i = 5; $i >= 0; $i--) {
            $month = now()->subMonths($i)->format('Y-m');
            $financial = SuperAdminFinancial::recalculateMonth($month);
            $historicalData[] = [
                'month' => now()->subMonths($i)->format('M Y'),
                'revenue' => (float) $financial->revenue,
                'expenses' => (float) $financial->expenses,
                'net_profit' => (float) $financial->net_profit,
            ];
        }

        return response()->json([
            'financials' => [
                'year_month' => $financials->year_month,
                'revenue' => (float) $financials->revenue,
                'expenses' => (float) $financials->expenses,
                'net_profit' => (float) $financials->net_profit,
                'cash_balance' => (float) $financials->cash_balance,
            ],
            'bank_accounts' => [
                'accounts' => $bankAccounts,
                'total_balance' => (float) $totalBankBalance,
            ],
            'companies' => [
                'total_cash' => (float) $totalCompaniesCash,
                'companies' => $companies,
            ],
            'loans' => [
                'total_given' => $loansGiven,
                'active' => $activeLoans,
                'total_loaned' => (float) $totalLoaned,
                'total_repaid' => (float) $totalRepaid,
                'total_interest' => (float) $totalInterest,
                'outstanding' => (float) ($totalLoaned - $totalRepaid),
                'recent' => $recentLoans,
            ],
            'sweeps' => [
                'total_received' => $sweepsReceived,
                'total_swept' => (float) $totalSwept,
                'recent' => $recentSweeps,
            ],
            'historical' => $historicalData,
        ]);
    }
}
