<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\WalletTransaction;
use App\Models\User;
use Illuminate\Support\Carbon;

class FinanceController extends Controller
{
    public function index()
    {
        // Revenue statistics
        $totalRevenue = WalletTransaction::where('type', 'credit')
            ->where('status', 'completed')
            ->sum('amount');
        
        $todayRevenue = WalletTransaction::where('type', 'credit')
            ->where('status', 'completed')
            ->whereDate('created_at', Carbon::today())
            ->sum('amount');
        
        $thisMonthRevenue = WalletTransaction::where('type', 'credit')
            ->where('status', 'completed')
            ->whereMonth('created_at', Carbon::now()->month)
            ->sum('amount');
        
        $thisWeekRevenue = WalletTransaction::where('type', 'credit')
            ->where('status', 'completed')
            ->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
            ->sum('amount');
        
        // Current balance (sum of all user wallet balances)
        $currentBalance = User::sum('wallet_balance');
        
        // Total expenses (debit transactions)
        $totalExpenses = WalletTransaction::where('type', 'debit')
            ->where('status', 'completed')
            ->sum('amount');
        
        $thisWeekExpenses = WalletTransaction::where('type', 'debit')
            ->where('status', 'completed')
            ->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
            ->sum('amount');
        
        // Pending payments (failed or pending transactions)
        $pendingPayments = WalletTransaction::where('type', 'credit')
            ->whereIn('status', ['pending', 'failed'])
            ->sum('amount');
        
        $pendingCount = WalletTransaction::where('type', 'credit')
            ->whereIn('status', ['pending', 'failed'])
            ->count();
        
        // Revenue data for charts (last 30 days)
        $revenueData = $this->getRevenueData();
        $paymentMethodData = $this->getPaymentMethodData();
        
        // Recent transactions
        $recentTransactions = WalletTransaction::with('user')
            ->latest()
            ->take(20)
            ->get();
        
        return view('admin.finance.index', compact(
            'totalRevenue',
            'todayRevenue',
            'thisMonthRevenue',
            'thisWeekRevenue',
            'currentBalance',
            'totalExpenses',
            'thisWeekExpenses',
            'pendingPayments',
            'pendingCount',
            'revenueData',
            'paymentMethodData',
            'recentTransactions'
        ));
    }
    
    private function getRevenueData()
    {
        $startDate = Carbon::now()->subDays(29)->startOfDay();
        $endDate = Carbon::now()->endOfDay();
        
        $revenue = WalletTransaction::where('type', 'credit')
            ->where('status', 'completed')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, SUM(amount) as total')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $labels = [];
        $data = [];
        
        for ($i = 0; $i < 30; $i++) {
            $day = Carbon::now()->subDays(29 - $i)->format('Y-m-d');
            $labels[] = Carbon::parse($day)->format('d M');
            $data[] = $revenue->get($day)->total ?? 0;
        }

        return ['labels' => $labels, 'data' => $data];
    }
    
    private function getPaymentMethodData()
    {
        // This would typically come from payment gateway data
        // For now, we'll use mock data based on transaction meta
        $paymentMethods = WalletTransaction::where('type', 'credit')
            ->where('status', 'completed')
            ->whereNotNull('meta')
            ->get()
            ->groupBy(function($transaction) {
                return $transaction->meta['payment_method'] ?? 'Unknown';
            })
            ->map(function($group) {
                return $group->sum('amount');
            });
        
        // If no payment method data, return default
        if ($paymentMethods->isEmpty()) {
            return [
                'labels' => ['Credit Card', 'Debit Card', 'Net Banking', 'UPI'],
                'data' => [40, 30, 20, 10]
            ];
        }
        
        return [
            'labels' => $paymentMethods->keys()->toArray(),
            'data' => $paymentMethods->values()->toArray()
        ];
    }
}