<?php

namespace App\Http\Controllers;

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

class PenaltyController extends Controller
{
    public function index()
    {
        $penalties = Penalty::with(['member', 'issuer'])
            ->latest()
            ->paginate(20);
            
        return view('penalties.index', compact('penalties'));
    }

    public function create(Request $request)
    {
        $members = Member::active()->get();
        $selectedMember = $request->member_id ? Member::find($request->member_id) : null;
        
        return view('penalties.create', compact('members', 'selectedMember'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'member_id' => 'required|exists:members,id',
            'amount' => 'required|numeric|min:0',
            'reason' => 'required|string|max:255',
        ]);

        Penalty::create([
            'member_id' => $validated['member_id'],
            'amount' => $validated['amount'],
            'reason' => $validated['reason'],
            'status' => 'pending',
            'issued_by' => auth()->id(),
        ]);

        return redirect()->route('penalties.index')
            ->with('success', 'Penalty issued successfully.');
    }

    public function pay(Penalty $penalty)
    {
        if ($penalty->isPaid()) {
            return back()->with('error', 'This penalty is already paid.');
        }

        return view('penalties.pay', compact('penalty'));
    }

    public function processPayment(Request $request, Penalty $penalty)
    {
        if ($penalty->isPaid()) {
            return back()->with('error', 'This penalty is already paid.');
        }

        $validated = $request->validate([
            'payment_method' => 'required|in:mpesa,cash,bank_transfer,cheque',
            'mpesa_receipt' => 'required_if:payment_method,mpesa|nullable|string',
        ]);

        DB::transaction(function () use ($penalty, $validated) {
            // 1. Create a transaction
            $transaction = Transaction::create([
                'member_id' => $penalty->member_id,
                'transaction_reference' => 'PEN-' . time() . rand(100, 999),
                'transaction_type' => 'fee',
                'amount' => $penalty->amount,
                'balance_before' => $penalty->member->current_balance,
                'balance_after' => $penalty->member->current_balance - $penalty->amount,
                'payment_method' => $validated['payment_method'],
                'mpesa_receipt' => $validated['mpesa_receipt'] ?? null,
                'description' => 'Payment for penalty: ' . $penalty->reason,
                'transaction_date' => now(),
                'recorded_by' => auth()->id(),
            ]);

            // 2. Update member balance
            $penalty->member->decrement('current_balance', $penalty->amount);

            // 3. Update penalty record
            $penalty->update([
                'status' => 'paid',
                'paid_at' => now(),
                'transaction_id' => $transaction->id,
            ]);
        });

        return redirect()->route('penalties.index')
            ->with('success', 'Penalty payment recorded successfully.');
    }
}
