<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SuperAdminFinancial extends Model
{
    use HasFactory;

    protected $fillable = [
        'year_month',
        'revenue',
        'expenses',
        'net_profit',
        'cash_balance',
    ];

    protected $casts = [
        'revenue' => 'decimal:2',
        'expenses' => 'decimal:2',
        'net_profit' => 'decimal:2',
        'cash_balance' => 'decimal:2',
    ];

    /**
     * Recalculate financials for a given month
     */
    public static function recalculateMonth(string $yearMonth): self
    {
        $financial = self::firstOrCreate(['year_month' => $yearMonth]);
        
        // Revenue comes from profit sweeps + loan repayments (money coming in)
        $profitSweeps = \App\Models\ProfitSweepTransaction::where('is_super_admin_recipient', true)
            ->whereYear('sweep_date', substr($yearMonth, 0, 4))
            ->whereMonth('sweep_date', substr($yearMonth, 5, 2))
            ->sum('actual_amount');
        
        $loanRepayments = \App\Models\LoanRepayment::join('intercompany_loans', 'loan_repayments.loan_id', '=', 'intercompany_loans.id')
            ->where('intercompany_loans.is_super_admin_lender', true)
            ->whereYear('loan_repayments.paid_at', substr($yearMonth, 0, 4))
            ->whereMonth('loan_repayments.paid_at', substr($yearMonth, 5, 2))
            ->where('loan_repayments.status', 'paid')
            ->sum('loan_repayments.total_amount');
        
        $revenue = $profitSweeps + $loanRepayments;
        
        // Expenses come from loan disbursements (money going out)
        $expenses = \App\Models\IntercompanyLoan::where('is_super_admin_lender', true)
            ->whereYear('disbursement_date', substr($yearMonth, 0, 4))
            ->whereMonth('disbursement_date', substr($yearMonth, 5, 2))
            ->where('status', 'approved')
            ->sum('principal_amount');
        
        $financial->revenue = $revenue;
        $financial->expenses = $expenses;
        $financial->net_profit = $revenue - $expenses;
        
        // Cash balance comes from actual bank accounts
        $bankBalance = \App\Models\SuperAdminBankAccount::sum('current_balance');
        
        $financial->cash_balance = $bankBalance;
        $financial->save();
        
        return $financial;
    }

    /**
     * Get current month financials
     */
    public static function getCurrent(): self
    {
        return self::recalculateMonth(now()->format('Y-m'));
    }
}
