<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\User;
use App\Models\Saving;
use App\Models\Loan;
use App\Models\Share;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\TransactionsExport;

class TransactionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // Get comprehensive system activities
        $activities = $this->getSystemActivities($request);

        // Get filter options for the activity types
        $activityTypes = [
            'transaction' => 'Financial Transactions',
            'savings' => 'Savings Activities',
            'loan' => 'Loan Activities',
            'shares' => 'Shares Activities',
            'membership' => 'Membership Activities',
            'login' => 'Login Activities',
            'system' => 'System Activities',
            'all' => 'All Activities'
        ];

        $users = User::whereHas('membership')->get();

        // Collect real-time data from savings and loan modules
        $realTimeData = $this->getRealTimeFinancialData();

        return view('adminlte.transactions.index', compact('activities', 'activityTypes', 'users', 'realTimeData'));
    }

    /**
     * Get comprehensive real-time financial data from all system modules
     */
    private function getRealTimeFinancialData()
    {
        // Real-time savings data with current balances
        $activeSavingsAccounts = Saving::where('status', 'active')->count();
        $totalSavingsBalance = Saving::where('status', 'active')->sum('amount');
        $withdrawnSavingsAccounts = Saving::where('status', 'withdrawn')->count();
        $totalWithdrawnAmount = Saving::where('status', 'withdrawn')->sum('amount');

        // Real-time loan data
        $activeLoans = Loan::where('status', 'active')->count();
        $totalLoanAmount = Loan::whereIn('status', ['active', 'approved'])->sum('amount');
        $totalLoanInterest = Loan::whereIn('status', ['active', 'approved'])->get()->sum(function($loan) {
            return $loan->amount * ($loan->interest_rate / 100);
        });
        $pendingLoans = Loan::where('status', 'pending')->count();
        $approvedLoans = Loan::where('status', 'approved')->count();
        $paidLoans = Loan::where('status', 'paid')->count();

        // Real-time shares data
        $totalShares = Share::sum('number_of_shares');
        $totalSharesValue = Share::sum('total_value');
        $totalShareholders = Share::distinct('user_id')->count('user_id');
        $recentSharesPurchased = Share::where('purchase_date', '>=', now()->subDays(30))->sum('number_of_shares');

        // Real-time transaction summaries (from actual transaction records)
        $totalDeposits = Transaction::whereIn('type', ['mpesa_deposit', 'savings_deposit'])
                                   ->where('status', 'completed')
                                   ->sum('amount');

        $totalWithdrawals = Transaction::whereIn('type', ['mpesa_withdrawal', 'savings_withdrawal'])
                                      ->where('status', 'completed')
                                      ->sum('amount');

        $totalFees = Transaction::where('status', 'completed')->sum('fee_amount');

        $netAmount = $totalDeposits - $totalWithdrawals;

        // Loan performance metrics
        $totalLoanRepayments = Transaction::where('type', 'loan_repayment')
                                         ->where('status', 'completed')
                                         ->sum('amount');

        $totalLoanDisbursements = Transaction::where('type', 'loan_disbursement')
                                            ->where('status', 'completed')
                                            ->sum('amount');

        // Recent activities from all modules (last 24 hours)
        $recentActivities = $this->getRecentActivities();

        // Monthly trends (last 6 months)
        $monthlyTrends = $this->getMonthlyTrends();

        // Loan distribution by members
        $loanMemberData = $this->getLoanMemberData();

        // System health metrics
        $systemHealth = $this->getSystemHealthMetrics();

        return [
            // Savings Module Data
            'active_savings_accounts' => $activeSavingsAccounts,
            'total_savings_balance' => $totalSavingsBalance,
            'withdrawn_savings_accounts' => $withdrawnSavingsAccounts,
            'total_withdrawn_amount' => $totalWithdrawnAmount,

            // Loan Module Data
            'active_loans' => $activeLoans,
            'total_loan_amount' => $totalLoanAmount,
            'total_loan_interest' => $totalLoanInterest,
            'pending_loans' => $pendingLoans,
            'approved_loans' => $approvedLoans,
            'paid_loans' => $paidLoans,

            // Shares Module Data
            'total_shares' => $totalShares,
            'total_shares_value' => $totalSharesValue,
            'total_shareholders' => $totalShareholders,
            'recent_shares_purchased' => $recentSharesPurchased,

            // Transaction Summary Data
            'total_deposits' => $totalDeposits,
            'total_withdrawals' => $totalWithdrawals,
            'total_fees' => $totalFees,
            'net_amount' => $netAmount,

            // Loan Performance Data
            'total_loan_repayments' => $totalLoanRepayments,
            'total_loan_disbursements' => $totalLoanDisbursements,

            // Dynamic Activity Data
            'recent_activities' => $recentActivities,
            'monthly_trends' => $monthlyTrends,
            'loan_member_data' => $loanMemberData,
            'system_health' => $systemHealth,
        ];
    }

    /**
     * Get recent activities from all system modules
     */
    private function getRecentActivities()
    {
        $activities = collect();

        // Recent savings transactions
        $savingsTransactions = \App\Models\SavingsTransaction::join('savings', 'savings_transactions.saving_id', '=', 'savings.id')
            ->join('users', 'savings.user_id', '=', 'users.id')
            ->where('savings_transactions.transaction_date', '>=', now()->subHours(24))
            ->orderBy('savings_transactions.transaction_date', 'desc')
            ->take(10)
            ->select('savings_transactions.*', 'users.first_name', 'users.second_name')
            ->get()
            ->map(function ($transaction) {
                return [
                    'type' => 'savings',
                    'action' => $transaction->type,
                    'amount' => $transaction->amount,
                    'member' => $transaction->first_name . ' ' . $transaction->second_name,
                    'timestamp' => $transaction->transaction_date,
                    'icon' => $transaction->type === 'deposit' ? 'fas fa-arrow-up text-success' : 'fas fa-arrow-down text-danger',
                    'description' => ucfirst($transaction->type) . ' of KSh ' . number_format($transaction->amount, 2)
                ];
            });

        // Recent loan activities
        $loanActivities = Loan::join('users', 'loans.user_id', '=', 'users.id')
            ->where('loans.updated_at', '>=', now()->subHours(24))
            ->orderBy('loans.updated_at', 'desc')
            ->take(5)
            ->select('loans.*', 'users.first_name', 'users.second_name')
            ->get()
            ->map(function ($loan) {
                $action = match($loan->status) {
                    'pending' => 'applied',
                    'approved' => 'approved',
                    'active' => 'disbursed',
                    'paid' => 'repaid',
                    default => 'updated'
                };
                return [
                    'type' => 'loan',
                    'action' => $action,
                    'amount' => $loan->amount,
                    'member' => $loan->first_name . ' ' . $loan->second_name,
                    'timestamp' => $loan->updated_at,
                    'icon' => 'fas fa-money-bill-wave text-warning',
                    'description' => 'Loan ' . $action . ' for KSh ' . number_format($loan->amount, 2)
                ];
            });

        // Recent membership activities
        $membershipActivities = \App\Models\Membership::join('users', 'memberships.user_id', '=', 'users.id')
            ->where('memberships.created_at', '>=', now()->subHours(24))
            ->orderBy('memberships.created_at', 'desc')
            ->take(3)
            ->select('memberships.*', 'users.first_name', 'users.second_name')
            ->get()
            ->map(function ($membership) {
                return [
                    'type' => 'membership',
                    'action' => 'registered',
                    'amount' => $membership->share_capital,
                    'member' => $membership->first_name . ' ' . $membership->second_name,
                    'timestamp' => $membership->created_at,
                    'icon' => 'fas fa-user-plus text-primary',
                    'description' => 'New member registration'
                ];
            });

        // Recent shares activities
        $sharesActivities = Share::join('users', 'shares.user_id', '=', 'users.id')
            ->where('shares.purchase_date', '>=', now()->subDays(1))
            ->orderBy('shares.purchase_date', 'desc')
            ->take(5)
            ->select('shares.*', 'users.first_name', 'users.second_name')
            ->get()
            ->map(function ($share) {
                return [
                    'type' => 'shares',
                    'action' => 'purchased',
                    'amount' => $share->total_value,
                    'member' => $share->first_name . ' ' . $share->second_name,
                    'timestamp' => $share->purchase_date,
                    'icon' => 'fas fa-share-alt text-info',
                    'description' => 'Purchased ' . number_format($share->number_of_shares) . ' shares'
                ];
            });

        // Combine and sort all activities
        $activities = $activities->concat($savingsTransactions)
                                ->concat($loanActivities)
                                ->concat($sharesActivities)
                                ->concat($membershipActivities)
                                ->sortByDesc('timestamp')
                                ->take(15);

        return $activities;
    }

    /**
     * Get daily trends for the current month
     */
    private function getMonthlyTrends()
    {
        $currentMonth = now();
        $monthStart = $currentMonth->copy()->startOfMonth();
        $monthEnd = $currentMonth->copy()->endOfMonth();
        $daysInMonth = $currentMonth->daysInMonth;

        $trends = [];

        for ($day = 1; $day <= $daysInMonth; $day++) {
            $date = $monthStart->copy()->addDays($day - 1);
            $dayStart = $date->copy()->startOfDay();
            $dayEnd = $date->copy()->endOfDay();

            // Only include days up to today for current month
            if ($date->isFuture()) {
                break;
            }

            $deposits = Transaction::whereIn('type', ['mpesa_deposit', 'savings_deposit'])
                                   ->whereBetween('created_at', [$dayStart, $dayEnd])
                                   ->where('status', 'completed')
                                   ->sum('amount');

            $withdrawals = Transaction::whereIn('type', ['mpesa_withdrawal', 'savings_withdrawal'])
                                      ->whereBetween('created_at', [$dayStart, $dayEnd])
                                      ->where('status', 'completed')
                                      ->sum('amount');

            $loans = Transaction::where('type', 'loan_disbursement')
                                ->whereBetween('created_at', [$dayStart, $dayEnd])
                                ->where('status', 'completed')
                                ->sum('amount');

            $trends[] = [
                'day' => $date->format('d M'),
                'deposits' => $deposits,
                'withdrawals' => $withdrawals,
                'loans' => $loans,
                'net' => $deposits - $withdrawals,
                'date' => $date->format('Y-m-d')
            ];
        }

        return $trends;
    }

    /**
     * Get loan distribution data by members
     */
    private function getLoanMemberData()
    {
        // Get loans grouped by members with loan counts and total amounts
        $loanData = Loan::join('users', 'loans.user_id', '=', 'users.id')
            ->select(
                'users.first_name',
                'users.second_name',
                \DB::raw('COUNT(loans.id) as loan_count'),
                \DB::raw('SUM(loans.amount) as total_loan_amount'),
                \DB::raw('AVG(loans.amount) as avg_loan_amount')
            )
            ->whereIn('loans.status', ['active', 'approved', 'paid'])
            ->groupBy('users.id', 'users.first_name', 'users.second_name')
            ->orderBy('total_loan_amount', 'desc')
            ->take(10) // Top 10 members with loans
            ->get()
            ->map(function ($member) {
                return [
                    'member_name' => $member->first_name . ' ' . $member->second_name,
                    'loan_count' => $member->loan_count,
                    'total_amount' => $member->total_loan_amount,
                    'avg_amount' => $member->avg_loan_amount
                ];
            });

        // Get loan status distribution
        $loanStatusData = Loan::select('status', \DB::raw('COUNT(*) as count'), \DB::raw('SUM(amount) as total_amount'))
            ->groupBy('status')
            ->get()
            ->map(function ($status) {
                return [
                    'status' => ucfirst($status->status),
                    'count' => $status->count,
                    'total_amount' => $status->total_amount
                ];
            });

        // Get loan status distribution (since there's no type column)
        $loanStatusData = Loan::select('status', \DB::raw('COUNT(*) as count'), \DB::raw('SUM(amount) as total_amount'))
            ->groupBy('status')
            ->get()
            ->map(function ($status) {
                return [
                    'status' => ucfirst($status->status),
                    'count' => $status->count,
                    'total_amount' => $status->total_amount
                ];
            });

        return [
            'member_loans' => $loanData,
            'status_distribution' => $loanStatusData,
            'type_distribution' => $loanStatusData // Using status as type for now
        ];
    }

    /**
     * Get system health metrics
     */
    private function getSystemHealthMetrics()
    {
        $totalMembers = \App\Models\Membership::count();
        $activeMembers = \App\Models\Membership::where('status', 'active')->count();
        $totalTransactions = Transaction::count();
        $completedTransactions = Transaction::where('status', 'completed')->count();
        $pendingTransactions = Transaction::where('status', 'pending')->count();

        $successRate = $totalTransactions > 0 ? ($completedTransactions / $totalTransactions) * 100 : 0;

        return [
            'total_members' => $totalMembers,
            'active_members' => $activeMembers,
            'total_transactions' => $totalTransactions,
            'completed_transactions' => $completedTransactions,
            'pending_transactions' => $pendingTransactions,
            'success_rate' => round($successRate, 1)
        ];
    }

    /**
     * Get comprehensive system activities from all modules
     */
    private function getSystemActivities(Request $request)
    {
        $activities = collect();

        // Apply date filters
        $dateFrom = $request->filled('date_from') ? $request->date_from : now()->subDays(30)->format('Y-m-d');
        $dateTo = $request->filled('date_to') ? $request->date_to : now()->format('Y-m-d');

        // Filter by activity type
        $activityType = $request->get('activity_type', 'all');
        $userId = $request->get('user_id');

        // 1. Financial Transactions
        if ($activityType === 'all' || $activityType === 'transaction') {
            $transactions = Transaction::with(['user', 'fromUser', 'toUser'])
                ->when($userId, function($query) use ($userId) {
                    return $query->where('user_id', $userId);
                })
                ->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59'])
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($transaction) {
                    return [
                        'id' => $transaction->id,
                        'type' => 'transaction',
                        'subtype' => $transaction->type,
                        'title' => $this->getTransactionTitle($transaction),
                        'description' => $transaction->description ?: 'Transaction processed',
                        'amount' => $transaction->amount,
                        'member' => $transaction->user->full_name,
                        'status' => $transaction->status,
                        'timestamp' => $transaction->created_at,
                        'icon' => $this->getTransactionIcon($transaction->type),
                        'color' => $this->getTransactionColor($transaction->status),
                        'reference' => $transaction->reference_number,
                        'module' => 'Transactions'
                    ];
                });

            $activities = $activities->concat($transactions);
        }

        // 2. Savings Activities
        if ($activityType === 'all' || $activityType === 'savings') {
            $savingsActivities = \App\Models\SavingsTransaction::join('savings', 'savings_transactions.saving_id', '=', 'savings.id')
                ->join('users', 'savings.user_id', '=', 'users.id')
                ->when($userId, function($query) use ($userId) {
                    return $query->where('savings.user_id', $userId);
                })
                ->whereBetween('savings_transactions.transaction_date', [$dateFrom, $dateTo])
                ->orderBy('savings_transactions.transaction_date', 'desc')
                ->select('savings_transactions.*', 'users.first_name', 'users.second_name', 'savings.type as savings_type')
                ->get()
                ->map(function ($transaction) {
                    return [
                        'id' => $transaction->id,
                        'type' => 'savings',
                        'subtype' => $transaction->type,
                        'title' => ucfirst($transaction->type) . ' - ' . ucfirst($transaction->savings_type) . ' Account',
                        'description' => ucfirst($transaction->type) . ' transaction processed',
                        'amount' => $transaction->amount,
                        'member' => $transaction->first_name . ' ' . $transaction->second_name,
                        'status' => 'completed',
                        'timestamp' => $transaction->transaction_date,
                        'icon' => $transaction->type === 'deposit' ? 'fas fa-arrow-up text-success' : 'fas fa-arrow-down text-danger',
                        'color' => 'success',
                        'reference' => 'ST-' . $transaction->id,
                        'module' => 'Savings'
                    ];
                });

            $activities = $activities->concat($savingsActivities);
        }

        // 3. Loan Activities
        if ($activityType === 'all' || $activityType === 'loan') {
            $loanActivities = Loan::join('users', 'loans.user_id', '=', 'users.id')
                ->when($userId, function($query) use ($userId) {
                    return $query->where('loans.user_id', $userId);
                })
                ->whereBetween('loans.created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59'])
                ->orderBy('loans.created_at', 'desc')
                ->select('loans.*', 'users.first_name', 'users.second_name')
                ->get()
                ->map(function ($loan) {
                    $action = match($loan->status) {
                        'pending' => 'Loan Application Submitted',
                        'approved' => 'Loan Approved',
                        'active' => 'Loan Disbursed',
                        'paid' => 'Loan Fully Repaid',
                        'rejected' => 'Loan Application Rejected',
                        default => 'Loan Updated'
                    };

                    return [
                        'id' => $loan->id,
                        'type' => 'loan',
                        'subtype' => $loan->status,
                        'title' => $action,
                        'description' => 'Loan amount: KSh ' . number_format($loan->amount, 2),
                        'amount' => $loan->amount,
                        'member' => $loan->first_name . ' ' . $loan->second_name,
                        'status' => $loan->status,
                        'timestamp' => $loan->created_at,
                        'icon' => 'fas fa-money-bill-wave text-warning',
                        'color' => $this->getLoanStatusColor($loan->status),
                        'reference' => 'LN-' . $loan->id,
                        'module' => 'Loans'
                    ];
                });

            $activities = $activities->concat($loanActivities);
        }

        // 4. Shares Activities
        if ($activityType === 'all' || $activityType === 'shares') {
            $sharesActivities = Share::join('users', 'shares.user_id', '=', 'users.id')
                ->when($userId, function($query) use ($userId) {
                    return $query->where('shares.user_id', $userId);
                })
                ->whereBetween('shares.purchase_date', [$dateFrom, $dateTo])
                ->orderBy('shares.purchase_date', 'desc')
                ->select('shares.*', 'users.first_name', 'users.second_name')
                ->get()
                ->map(function ($share) {
                    return [
                        'id' => $share->id,
                        'type' => 'shares',
                        'subtype' => 'purchase',
                        'title' => 'Share Purchase',
                        'description' => number_format($share->number_of_shares) . ' shares purchased at KSh ' . number_format($share->share_value, 2) . ' each',
                        'amount' => $share->total_value,
                        'member' => $share->first_name . ' ' . $share->second_name,
                        'status' => 'completed',
                        'timestamp' => $share->purchase_date,
                        'icon' => 'fas fa-share-alt text-info',
                        'color' => 'info',
                        'reference' => 'SHR-' . $share->id,
                        'module' => 'Shares'
                    ];
                });

            $activities = $activities->concat($sharesActivities);
        }

        // 5. Membership Activities
        if ($activityType === 'all' || $activityType === 'membership') {
            $membershipActivities = \App\Models\Membership::join('users', 'memberships.user_id', '=', 'users.id')
                ->when($userId, function($query) use ($userId) {
                    return $query->where('memberships.user_id', $userId);
                })
                ->whereBetween('memberships.created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59'])
                ->orderBy('memberships.created_at', 'desc')
                ->select('memberships.*', 'users.first_name', 'users.second_name')
                ->get()
                ->map(function ($membership) {
                    return [
                        'id' => $membership->id,
                        'type' => 'membership',
                        'subtype' => 'registration',
                        'title' => 'New Member Registration',
                        'description' => 'Membership number: ' . $membership->membership_number,
                        'amount' => $membership->share_capital,
                        'member' => $membership->first_name . ' ' . $membership->second_name,
                        'status' => $membership->status,
                        'timestamp' => $membership->created_at,
                        'icon' => 'fas fa-user-plus text-primary',
                        'color' => $membership->status === 'active' ? 'success' : 'warning',
                        'reference' => $membership->membership_number,
                        'module' => 'Membership'
                    ];
                });

            $activities = $activities->concat($membershipActivities);
        }

        // 5. Login Activities (from system logs or custom tracking)
        if ($activityType === 'all' || $activityType === 'login') {
            // For now, we'll simulate login activities - in a real system you'd have a login_logs table
            $loginActivities = collect([
                [
                    'id' => 'login-1',
                    'type' => 'login',
                    'subtype' => 'successful',
                    'title' => 'Successful Login',
                    'description' => 'User logged into the system',
                    'amount' => 0,
                    'member' => 'System User',
                    'status' => 'completed',
                    'timestamp' => now()->subMinutes(15),
                    'icon' => 'fas fa-sign-in-alt text-success',
                    'color' => 'success',
                    'reference' => 'LOGIN-' . date('YmdHis'),
                    'module' => 'Authentication'
                ],
                [
                    'id' => 'login-2',
                    'type' => 'login',
                    'subtype' => 'failed',
                    'title' => 'Failed Login Attempt',
                    'description' => 'Invalid credentials provided',
                    'amount' => 0,
                    'member' => 'Unknown User',
                    'status' => 'failed',
                    'timestamp' => now()->subHours(2),
                    'icon' => 'fas fa-exclamation-triangle text-danger',
                    'color' => 'danger',
                    'reference' => 'LOGIN-FAIL-' . date('YmdHis'),
                    'module' => 'Authentication'
                ]
            ]);

            $activities = $activities->concat($loginActivities);
        }

        // 6. System Activities (exports, configuration changes, etc.)
        if ($activityType === 'all' || $activityType === 'system') {
            $systemActivities = collect([
                [
                    'id' => 'sys-1',
                    'type' => 'system',
                    'subtype' => 'export',
                    'title' => 'Data Export Completed',
                    'description' => 'Transactions report exported to PDF',
                    'amount' => 0,
                    'member' => 'Admin User',
                    'status' => 'completed',
                    'timestamp' => now()->subMinutes(30),
                    'icon' => 'fas fa-file-download text-info',
                    'color' => 'info',
                    'reference' => 'EXPORT-' . date('YmdHis'),
                    'module' => 'System'
                ],
                [
                    'id' => 'sys-2',
                    'type' => 'system',
                    'subtype' => 'config',
                    'title' => 'System Configuration Updated',
                    'description' => 'M-Pesa credentials updated',
                    'amount' => 0,
                    'member' => 'System Administrator',
                    'status' => 'completed',
                    'timestamp' => now()->subHours(1),
                    'icon' => 'fas fa-cogs text-warning',
                    'color' => 'warning',
                    'reference' => 'CONFIG-' . date('YmdHis'),
                    'module' => 'System'
                ],
                [
                    'id' => 'sys-3',
                    'type' => 'system',
                    'subtype' => 'backup',
                    'title' => 'Database Backup Completed',
                    'description' => 'Automated daily backup successful',
                    'amount' => 0,
                    'member' => 'System',
                    'status' => 'completed',
                    'timestamp' => now()->subHours(6),
                    'icon' => 'fas fa-database text-success',
                    'color' => 'success',
                    'reference' => 'BACKUP-' . date('YmdHis'),
                    'module' => 'System'
                ]
            ]);

            $activities = $activities->concat($systemActivities);
        }

        // Sort all activities by timestamp (most recent first) and paginate
        $sortedActivities = $activities->sortByDesc('timestamp')->values();

        // Manual pagination
        $perPage = 20;
        $page = $request->get('page', 1);
        $offset = ($page - 1) * $perPage;
        $paginatedActivities = $sortedActivities->slice($offset, $perPage);

        // Create a LengthAwarePaginator manually
        $paginator = new \Illuminate\Pagination\LengthAwarePaginator(
            $paginatedActivities,
            $sortedActivities->count(),
            $perPage,
            $page,
            ['path' => $request->url(), 'pageName' => 'page']
        );

        return $paginator;
    }

    /**
     * Get real-time activities via AJAX
     */
    public function getRealTimeActivities(Request $request)
    {
        $since = $request->get('since', now()->subMinutes(5)->toISOString());

        // Get activities from the last 5 minutes
        $activities = $this->getSystemActivities($request);

        // Filter for very recent activities
        $recentActivities = $activities->filter(function ($activity) use ($since) {
            return $activity['timestamp'] > $since;
        })->take(10)->values();

        return response()->json([
            'success' => true,
            'activities' => $recentActivities,
            'count' => $recentActivities->count(),
            'timestamp' => now()->toISOString()
        ]);
    }

    /**
     * Get transaction title
     */
    private function getTransactionTitle($transaction)
    {
        $titles = [
            'mpesa_deposit' => 'M-Pesa Deposit',
            'mpesa_withdrawal' => 'M-Pesa Withdrawal',
            'account_transfer' => 'Account Transfer',
            'loan_disbursement' => 'Loan Disbursement',
            'loan_repayment' => 'Loan Repayment',
            'savings_deposit' => 'Savings Deposit',
            'savings_withdrawal' => 'Savings Withdrawal',
            'registration_fee' => 'Registration Fee Payment',
            'share_purchase' => 'Share Purchase',
            'dividend_payment' => 'Dividend Payment',
            'interest_payment' => 'Interest Payment',
            'fee_payment' => 'Fee Payment',
            'other' => 'Other Transaction',
        ];

        return $titles[$transaction->type] ?? 'Transaction';
    }

    /**
     * Get transaction icon
     */
    private function getTransactionIcon($type)
    {
        $icons = [
            'mpesa_deposit' => 'fas fa-mobile-alt text-success',
            'mpesa_withdrawal' => 'fas fa-mobile-alt text-danger',
            'account_transfer' => 'fas fa-exchange-alt text-info',
            'loan_disbursement' => 'fas fa-hand-holding-usd text-success',
            'loan_repayment' => 'fas fa-hand-holding-usd text-primary',
            'savings_deposit' => 'fas fa-piggy-bank text-success',
            'savings_withdrawal' => 'fas fa-piggy-bank text-danger',
            'registration_fee' => 'fas fa-user-plus text-warning',
            'share_purchase' => 'fas fa-chart-line text-info',
            'dividend_payment' => 'fas fa-money-bill-wave text-success',
            'interest_payment' => 'fas fa-percentage text-info',
            'fee_payment' => 'fas fa-receipt text-warning',
            'other' => 'fas fa-cog text-secondary',
        ];

        return $icons[$type] ?? 'fas fa-cog text-secondary';
    }

    /**
     * Get transaction status color
     */
    private function getTransactionColor($status)
    {
        return match($status) {
            'completed' => 'success',
            'pending' => 'warning',
            'failed' => 'danger',
            default => 'secondary'
        };
    }

    /**
     * Get loan status color
     */
    private function getLoanStatusColor($status)
    {
        return match($status) {
            'active' => 'success',
            'approved' => 'info',
            'pending' => 'warning',
            'paid' => 'primary',
            'rejected' => 'danger',
            default => 'secondary'
        };
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $users = User::whereHas('membership')->get();
        $transactionTypes = [
            'mpesa_deposit' => 'M-Pesa Deposit',
            'mpesa_withdrawal' => 'M-Pesa Withdrawal',
            'account_transfer' => 'Account Transfer',
            'loan_disbursement' => 'Loan Disbursement',
            'loan_repayment' => 'Loan Repayment',
            'savings_deposit' => 'Savings Deposit',
            'savings_withdrawal' => 'Savings Withdrawal',
            'registration_fee' => 'Registration Fee',
            'share_purchase' => 'Share Purchase',
            'dividend_payment' => 'Dividend Payment',
            'interest_payment' => 'Interest Payment',
            'fee_payment' => 'Fee Payment',
            'other' => 'Other Transaction',
        ];

        return view('adminlte.transactions.create', compact('users', 'transactionTypes'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'type' => 'required|in:mpesa_deposit,mpesa_withdrawal,account_transfer,loan_disbursement,loan_repayment,savings_deposit,savings_withdrawal,registration_fee,share_purchase,dividend_payment,interest_payment,fee_payment,other',
            'amount' => 'required|numeric|min:0.01',
            'fee_amount' => 'nullable|numeric|min:0',
            'tax_amount' => 'nullable|numeric|min:0',
            'currency' => 'required|string|size:3',
            'from_user_id' => 'nullable|exists:users,id',
            'to_user_id' => 'nullable|exists:users,id',
            'payment_method' => 'nullable|string|max:255',
            'transaction_category' => 'nullable|string|max:255',
            'mpesa_transaction_id' => 'nullable|string|max:255',
            'reference_number' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:1000',
            'notes' => 'nullable|string|max:1000',
            'status' => 'required|in:pending,completed,failed',
        ]);

        $transaction = Transaction::create([
            'user_id' => $request->user_id,
            'type' => $request->type,
            'amount' => $request->amount,
            'fee_amount' => $request->fee_amount ?? 0,
            'tax_amount' => $request->tax_amount ?? 0,
            'currency' => $request->currency ?? 'KES',
            'from_user_id' => $request->from_user_id,
            'to_user_id' => $request->to_user_id,
            'payment_method' => $request->payment_method,
            'transaction_category' => $request->transaction_category,
            'mpesa_transaction_id' => $request->mpesa_transaction_id,
            'reference_number' => $request->reference_number ?? 'TXN-' . date('YmdHis') . '-' . rand(1000, 9999),
            'description' => $request->description,
            'notes' => $request->notes,
            'status' => $request->status,
            'processed_at' => $request->status === 'completed' ? now() : null,
        ]);

        return redirect()->route('transactions.index')
                        ->with('success', 'Transaction created successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show(Transaction $transaction)
    {
        $transaction->load(['user', 'fromUser', 'toUser']);
        return view('adminlte.transactions.show', compact('transaction'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Transaction $transaction)
    {
        $users = User::whereHas('membership')->get();
        $transactionTypes = [
            'mpesa_deposit' => 'M-Pesa Deposit',
            'mpesa_withdrawal' => 'M-Pesa Withdrawal',
            'account_transfer' => 'Account Transfer',
            'loan_disbursement' => 'Loan Disbursement',
            'loan_repayment' => 'Loan Repayment',
            'savings_deposit' => 'Savings Deposit',
            'savings_withdrawal' => 'Savings Withdrawal',
            'registration_fee' => 'Registration Fee',
            'share_purchase' => 'Share Purchase',
            'dividend_payment' => 'Dividend Payment',
            'interest_payment' => 'Interest Payment',
            'fee_payment' => 'Fee Payment',
            'other' => 'Other Transaction',
        ];

        return view('adminlte.transactions.edit', compact('transaction', 'users', 'transactionTypes'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Transaction $transaction)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'type' => 'required|in:mpesa_deposit,mpesa_withdrawal,account_transfer,loan_disbursement,loan_repayment,savings_deposit,savings_withdrawal,registration_fee,share_purchase,dividend_payment,interest_payment,fee_payment,other',
            'amount' => 'required|numeric|min:0.01',
            'fee_amount' => 'nullable|numeric|min:0',
            'tax_amount' => 'nullable|numeric|min:0',
            'currency' => 'required|string|size:3',
            'from_user_id' => 'nullable|exists:users,id',
            'to_user_id' => 'nullable|exists:users,id',
            'payment_method' => 'nullable|string|max:255',
            'transaction_category' => 'nullable|string|max:255',
            'mpesa_transaction_id' => 'nullable|string|max:255',
            'reference_number' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:1000',
            'notes' => 'nullable|string|max:1000',
            'status' => 'required|in:pending,completed,failed',
        ]);

        $transaction->update([
            'user_id' => $request->user_id,
            'type' => $request->type,
            'amount' => $request->amount,
            'fee_amount' => $request->fee_amount ?? 0,
            'tax_amount' => $request->tax_amount ?? 0,
            'currency' => $request->currency ?? 'KES',
            'from_user_id' => $request->from_user_id,
            'to_user_id' => $request->to_user_id,
            'payment_method' => $request->payment_method,
            'transaction_category' => $request->transaction_category,
            'mpesa_transaction_id' => $request->mpesa_transaction_id,
            'reference_number' => $request->reference_number,
            'description' => $request->description,
            'notes' => $request->notes,
            'status' => $request->status,
            'processed_at' => $request->status === 'completed' && $transaction->status !== 'completed' ? now() : $transaction->processed_at,
        ]);

        return redirect()->route('transactions.index')
                        ->with('success', 'Transaction updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Transaction $transaction)
    {
        $transaction->delete();

        return redirect()->route('transactions.index')
                        ->with('success', 'Transaction deleted successfully!');
    }

    /**
     * Export transactions to CSV.
     */
    public function exportCsv(Request $request)
    {
        $filename = 'transactions_' . date('Y-m-d_H-i-s') . '.csv';
        return Excel::download(new TransactionsExport($request->all()), $filename, \Maatwebsite\Excel\Excel::CSV);
    }

    /**
     * Export transactions to Excel.
     */
    public function exportExcel(Request $request)
    {
        $filename = 'transactions_' . date('Y-m-d_H-i-s') . '.xlsx';
        return Excel::download(new TransactionsExport($request->all()), $filename, \Maatwebsite\Excel\Excel::XLSX);
    }

    /**
     * Export transactions to PDF.
     */
    public function exportPdf(Request $request)
    {
        $query = Transaction::with(['user', 'fromUser', 'toUser']);

        // Apply same filters as index
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $transactions = $query->orderBy('created_at', 'desc')->get();

        $pdf = Pdf::loadView('adminlte.transactions.exports.pdf', compact('transactions'))
                  ->setPaper('a4', 'landscape');

        $filename = 'transactions_' . date('Y-m-d_H-i-s') . '.pdf';
        return $pdf->download($filename);
    }
}
