<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Transaction;
use App\Models\Topup;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class DashboardController extends Controller
{
    /**
     * Display the user dashboard with comprehensive statistics
     */
    public function index(): View
    {
        $user = Auth::user();
        
        $currentBalance = $user->balance ?? 0;
        
        // Define time periods for calculations
        $currentMonth = Carbon::now()->startOfMonth();
        $previousMonth = Carbon::now()->subMonth()->startOfMonth();
        $previousMonthEnd = Carbon::now()->subMonth()->endOfMonth();
        
        // Calculate transactions statistics for current month
        $transactionsThisMonth = Transaction::where('user_id', $user->id)
            ->where('created_at', '>=', $currentMonth)
            ->count();
        
        $transactionsPreviousMonth = Transaction::where('user_id', $user->id)
            ->whereBetween('created_at', [$previousMonth, $previousMonthEnd])
            ->count();
        
        $transactionsGrowth = $this->calculateGrowthPercentage(
            $transactionsPreviousMonth, 
            $transactionsThisMonth
        );
        
        // Calculate total spending for current month
        $spentThisMonth = Transaction::where('user_id', $user->id)
            ->where('created_at', '>=', $currentMonth)
            ->where('trx_status', 'Sukses')
            ->sum('total_price');
        
        $spentPreviousMonth = Transaction::where('user_id', $user->id)
            ->whereBetween('created_at', [$previousMonth, $previousMonthEnd])
            ->where('trx_status', 'Sukses')
            ->sum('total_price');
        
        $spentGrowth = $this->calculateGrowthPercentage(
            $spentPreviousMonth, 
            $spentThisMonth
        );
        
        // Calculate total topup for current month
        $topupThisMonth = Topup::where('user_id', $user->id)
            ->where('created_at', '>=', $currentMonth)
            ->where('status', 'Paid')
            ->sum('amount');
        
        $topupPreviousMonth = Topup::where('user_id', $user->id)
            ->whereBetween('created_at', [$previousMonth, $previousMonthEnd])
            ->where('status', 'Paid')
            ->sum('amount');
        
        $topupGrowth = $this->calculateGrowthPercentage(
            $topupPreviousMonth, 
            $topupThisMonth
        );
        
        // Count pending transactions
        $pendingTransactions = Transaction::where('user_id', $user->id)
            ->where('trx_status', 'Pending')
            ->count();
        
        // Retrieve recent transactions with limit of 5
        $recentTransactions = Transaction::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();
        
        // Retrieve recent topups with payment method relationship
        $recentTopups = Topup::where('user_id', $user->id)
            ->with('paymentMethod')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();
        
        // Aggregate transaction statistics by status
        $transactionStats = Transaction::where('user_id', $user->id)
            ->selectRaw('trx_status as status, count(*) as count')
            ->groupBy('trx_status')
            ->get()
            ->pluck('count', 'status')
            ->toArray();
        
        // Prepare transaction statistics with consistent keys
        $transactionStats = [
            'Sukses' => $transactionStats['Sukses'] ?? 0,
            'Pending' => $transactionStats['Pending'] ?? 0,
            'Gagal' => $transactionStats['Gagal'] ?? 0,
        ];
        
        // Generate monthly spending data for chart visualization
        $monthlySpending = [];
        for ($i = 5; $i >= 0; $i--) {
            $month = Carbon::now()->subMonths($i);
            $monthStart = $month->copy()->startOfMonth();
            $monthEnd = $month->copy()->endOfMonth();
            
            $spending = Transaction::where('user_id', $user->id)
                ->whereBetween('created_at', [$monthStart, $monthEnd])
                ->where('trx_status', 'Sukses')
                ->sum('total_price');
            
            $monthlySpending[] = [
                'month' => $month->format('M'),
                'amount' => $spending
            ];
        }
        
        return view('pages.user.dashboard', compact(
            'user',
            'currentBalance',
            'transactionsThisMonth',
            'transactionsGrowth',
            'spentThisMonth',
            'spentGrowth',
            'topupThisMonth',
            'topupGrowth',
            'pendingTransactions',
            'recentTransactions',
            'recentTopups',
            'transactionStats',
            'monthlySpending'
        ));
    }
    
    /**
     * Calculate growth percentage between two periods
     * 
     * @param float $previous Previous period value
     * @param float $current Current period value
     * @return array Growth percentage and direction
     */
    private function calculateGrowthPercentage($previous, $current): array
    {
        if ($previous == 0) {
            return [
                'value' => $current > 0 ? 100 : 0,
                'direction' => $current > 0 ? 'up' : 'neutral'
            ];
        }
        
        $percentage = (($current - $previous) / $previous) * 100;
        
        return [
            'value' => abs(round($percentage, 1)),
            'direction' => $percentage > 0 ? 'up' : ($percentage < 0 ? 'down' : 'neutral')
        ];
    }
}
