<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TransactionController extends Controller
{
    public function index()
    {
        $transactions = Transaction::with(['member', 'recorder'])
            ->latest()
            ->paginate(25);
            
        return view('transactions.index', compact('transactions'));
    }
    
    public function create()
    {
        $members = Member::active()->get();
        $types = [
            'contribution' => 'Member Contribution',
            'withdrawal' => 'Savings Withdrawal',
            'loan_payment' => 'Loan Payment',
            'dividend' => 'Dividend Payment',
            'fee' => 'Penalty Fee'
        ];
        
        return view('transactions.create', compact('members', 'types'));
    }
    
    public function store(Request $request)
    {

        // dd($request(amount));
        $validated = $request->validate([
            'member_id' => 'required|exists:members,id',
            'transaction_type' => 'required|in:contribution,withdrawal,loan_payment,dividend,fee',
            'amount' => 'required|numeric|min:0',
            'payment_method' => 'required|in:mpesa,cash,bank_transfer,cheque',
            'mpesa_receipt' => 'required_if:payment_method,mpesa|nullable|string',
            'description' => 'nullable|string|max:255',
            'transaction_date' => 'required|date'
        ]);

        // dd($request($validated));
        
        // Get member's current balance
        $member = Member::find($request->member_id);
        $balanceBefore = $member->current_balance;
        
        // Calculate new balance
        if(in_array($request->transaction_type, ['contribution', 'dividend'])) {
            $balanceAfter = $balanceBefore + $request->amount;
        } else {
            $balanceAfter = $balanceBefore - $request->amount;
        }
        
        // Create transaction
        $transaction = Transaction::create([
            'member_id' => $request->member_id,
            'transaction_reference' => 'TRX-' . time() . rand(100,999),
            'transaction_type' => $request->transaction_type,
            'amount' => $request->amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'payment_method' => $request->payment_method,
            'mpesa_receipt' => $request->mpesa_receipt,
            'description' => $request->description,
            'transaction_date' => $request->transaction_date,
            'recorded_by' => auth()->id()
        ]);
        
        // Update member balance
        $member->update(['current_balance' => $balanceAfter]);
        
        return redirect()->route('transactions.index')
            ->with('success', 'Transaction recorded successfully!');
    }
    
    public function show(Transaction $transaction)
    {
        return view('transactions.show', compact('transaction'));
    }

        public function reverse(Transaction $transaction)
    {
        // Verify transaction isn't already reversed
        if($transaction->reversed) {
            return back()->with('error', 'Transaction already reversed');
        }
        
        DB::transaction(function() use ($transaction) {
            // Create reversal transaction
            $reversal = $transaction->replicate();
            $reversal->transaction_reference = 'REV-' . $transaction->transaction_reference;
            $reversal->amount = $transaction->amount;
            $reversal->balance_before = $transaction->balance_after;
            $reversal->balance_after = $transaction->balance_before;
            $reversal->transaction_type = 'reversal';
            $reversal->description = 'Reversal of ' . $transaction->transaction_reference;
            $reversal->recorded_by = auth()->id();
            $reversal->save();
            
            // Update original transaction
            $transaction->update(['reversed' => true]);
            
            // Update member balance
            $transaction->member->update([
                'current_balance' => $transaction->balance_before
            ]);
        });
        
        return back()->with('success', 'Transaction reversed successfully');
    }
    public function dailySummary()
    {
        $summary = Transaction::selectRaw('
            DATE(transaction_date) as date,
            COUNT(*) as total_transactions,
            SUM(CASE WHEN transaction_type IN ("contribution", "dividend") THEN amount ELSE 0 END) as total_income,
            SUM(CASE WHEN transaction_type IN ("withdrawal", "fee", "loan_payment") THEN amount ELSE 0 END) as total_expenses
        ')
        ->groupBy('date')
        ->orderBy('date', 'desc')
        ->paginate(15);
        
        return view('transactions.daily-summary', compact('summary'));
    }
}