<?php

namespace App\Http\Controllers;

use App\Models\SavingsTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TransactionController extends Controller
{
    public function index()
    {
        $transactions = SavingsTransaction::with(['savingsAccount.client'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('transactions.index', compact('transactions'));
    }

    public function create()
    {
        return view('transactions.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'savings_account_id' => 'required|exists:savings_accounts,id',
            'type' => 'required|in:deposit,withdrawal',
            'amount' => 'required|numeric|min:0.01',
            'description' => 'nullable|string|max:255',
        ]);

        // Get the savings account to calculate balance
        $savingsAccount = \App\Models\SavingsAccount::findOrFail($request->savings_account_id);

        $balanceBefore = $savingsAccount->current_balance;
        $balanceAfter = $request->type === 'deposit'
            ? $balanceBefore + $request->amount
            : $balanceBefore - $request->amount;

        SavingsTransaction::create([
            'savings_account_id' => $request->savings_account_id,
            'transaction_number' => 'TXN' . date('YmdHis') . strtoupper(\Illuminate\Support\Str::random(4)),
            'type' => $request->type,
            'amount' => $request->amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'description' => $request->description,
            'transaction_date' => now(),
            'created_by' => Auth::id(),
        ]);

        // Update account balance
        $savingsAccount->update(['current_balance' => $balanceAfter]);

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

    public function show(SavingsTransaction $transaction)
    {
        $transaction->load(['savingsAccount.client']);
        return view('transactions.show', compact('transaction'));
    }

    public function edit(SavingsTransaction $transaction)
    {
        return view('transactions.edit', compact('transaction'));
    }

    public function update(Request $request, SavingsTransaction $transaction)
    {
        $request->validate([
            'type' => 'required|in:deposit,withdrawal',
            'amount' => 'required|numeric|min:0.01',
            'description' => 'nullable|string|max:255',
        ]);

        $transaction->update($request->only(['type', 'amount', 'description']));

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

    public function destroy(SavingsTransaction $transaction)
    {
        $transaction->delete();
        return redirect()->route('transactions.index')->with('success', 'Transaction deleted successfully.');
    }

    public function receipts()
    {
        $receipts = SavingsTransaction::where('type', 'deposit')
            ->with(['savingsAccount.client'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('receipts.index', compact('receipts'));
    }

    public function showReceipt($receipt)
    {
        $transaction = SavingsTransaction::with(['savingsAccount.client'])
            ->findOrFail($receipt);

        return view('receipts.show', compact('transaction'));
    }

    public function storeReceipt(Request $request)
    {
        $request->validate([
            'customer_id' => 'required|exists:clients,id',
            'receipt_number' => 'required|string|unique:receipts',
            'receipt_date' => 'required|date',
            'payment_type_id' => 'required|exists:payment_providers,id',
            'lines' => 'required|array|min:1',
            'lines.*.description' => 'required|string|max:255',
            'lines.*.invoice_id' => 'nullable|exists:invoices,id',
            'lines.*.deposit_account_id' => 'required|exists:chart_of_accounts,id',
            'lines.*.amount' => 'required|numeric|min:0.01',
        ]);

        // Calculate total amount
        $totalAmount = collect($request->lines)->sum('amount');

        // Create the receipt
        $receipt = \App\Models\Receipt::create([
            'receipt_number' => $request->receipt_number,
            'client_id' => $request->customer_id,
            'receipt_date' => $request->receipt_date,
            'payment_method' => $request->payment_type_id, // Assuming payment_method stores the ID
            'amount' => $totalAmount,
            'currency' => 'KES',
            'exchange_rate' => 1.0,
            'collected_by' => Auth::id(),
            'status' => 'completed',
        ]);

        // Create receipt items/details if needed (you might need a separate table for receipt items)
        // For now, we'll store the lines data in notes or create a simple implementation

        $notes = [];
        foreach ($request->lines as $line) {
            $notes[] = $line['description'] . ' - $' . number_format($line['amount'], 2);
        }
        $receipt->update(['notes' => implode('; ', $notes)]);

        return redirect()->route('accounts.receipts.create')->with('success', 'Receipt created successfully.');
    }

    public function payments()
    {
        $payments = SavingsTransaction::where('type', 'withdrawal')
            ->with(['savingsAccount.client'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('payments.index', compact('payments'));
    }

    public function storePayment(Request $request)
    {
        $request->validate([
            'savings_account_id' => 'required|exists:savings_accounts,id',
            'amount' => 'required|numeric|min:0.01',
            'description' => 'nullable|string|max:255',
        ]);

        // Get the savings account to calculate balance
        $savingsAccount = \App\Models\SavingsAccount::findOrFail($request->savings_account_id);

        $balanceBefore = $savingsAccount->current_balance;
        $balanceAfter = $balanceBefore - $request->amount;

        SavingsTransaction::create([
            'savings_account_id' => $request->savings_account_id,
            'transaction_number' => 'TXN' . date('YmdHis') . strtoupper(\Illuminate\Support\Str::random(4)),
            'type' => 'withdrawal',
            'amount' => $request->amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'description' => $request->description,
            'transaction_date' => now(),
            'created_by' => Auth::id(),
        ]);

        // Update account balance
        $savingsAccount->update(['current_balance' => $balanceAfter]);

        return redirect()->route('payments.index')->with('success', 'Payment processed successfully.');
    }
}
