<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Models\MoneyMarketAccount;
use Illuminate\Http\Request;

class MoneyMarketController extends Controller
{
    /**
     * Display a listing of the member's money market accounts.
     */
    public function index()
    {
        $user = auth()->user();
        $moneyMarketAccounts = MoneyMarketAccount::where('membership_id', $user->membership->id ?? null)
            ->orderBy('created_at', 'desc')
            ->get();

        // Calculate summary statistics
        $stats = [
            'total_accounts' => $moneyMarketAccounts->count(),
            'active_accounts' => $moneyMarketAccounts->where('status', 'active')->count(),
            'matured_accounts' => $moneyMarketAccounts->where('status', 'matured')->count(),
            'total_principal' => $moneyMarketAccounts->sum('principal_amount'),
            'total_interest_earned' => $moneyMarketAccounts->sum('interest_earned'),
            'total_value' => $moneyMarketAccounts->sum('total_amount'),
        ];

        return view('member.money-market.index', compact('moneyMarketAccounts', 'stats'));
    }

    /**
     * Display the specified money market account.
     */
    public function show(MoneyMarketAccount $moneyMarketAccount)
    {
        // Ensure the account belongs to the current user
        if ($moneyMarketAccount->membership_id !== auth()->user()->membership->id) {
            abort(403, 'Unauthorized access to money market account.');
        }

        return view('member.money-market.show', compact('moneyMarketAccount'));
    }

    /**
     * Request withdrawal from money market account.
     */
    public function requestWithdrawal(Request $request, MoneyMarketAccount $moneyMarketAccount)
    {
        // Ensure the account belongs to the current user
        if ($moneyMarketAccount->membership_id !== auth()->user()->membership->id) {
            abort(403, 'Unauthorized access to money market account.');
        }

        $validated = $request->validate([
            'withdrawal_amount' => 'required|numeric|min:0',
            'reason' => 'nullable|string|max:500',
        ]);

        // For members, we don't actually process the withdrawal immediately
        // Instead, we create a withdrawal request that needs admin approval
        // For now, we'll just show a message that the request has been submitted

        return redirect()->back()->with('info',
            'Your withdrawal request for ' . \App\Helpers\CurrencyHelper::format($validated['withdrawal_amount'], $moneyMarketAccount->currency_code) .
            ' has been submitted and is pending approval. You will be notified once it is processed.'
        );
    }

    /**
     * Show investment calculator (for planning purposes).
     */
    public function calculator()
    {
        return view('member.money-market.calculator');
    }

    /**
     * Calculate investment returns (AJAX endpoint).
     */
    public function calculate(Request $request)
    {
        $validated = $request->validate([
            'principal' => 'required|numeric|min:1000',
            'rate' => 'required|numeric|min:0|max:50',
            'term_months' => 'required|integer|min:1|max:120',
        ]);

        $principal = $validated['principal'];
        $rate = $validated['rate'];
        $termMonths = $validated['term_months'];

        $years = $termMonths / 12;
        $interest = $principal * ($rate / 100) * $years;
        $total = $principal + $interest;

        return response()->json([
            'principal' => $principal,
            'interest' => round($interest, 2),
            'total' => round($total, 2),
            'monthly_interest' => round($interest / $termMonths, 2),
        ]);
    }
}
