<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\CustomerPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CustomerPaymentController extends Controller
{
    public function create(Customer $customer)
    {
        return view('customers.payment', compact('customer'));
    }

    public function store(Request $request, Customer $customer)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'date' => 'required|date',
            'notes' => 'nullable|string',
        ]);

        DB::transaction(function () use ($validated, $customer) {
            CustomerPayment::create([
                'customer_id' => $customer->id,
                'amount' => $validated['amount'],
                'date' => $validated['date'],
                'notes' => $validated['notes'] ?? null,
            ]);

            $customer->recalculateBalance();
        });

        return redirect()->route('customers.show', $customer)->with('success', 'Payment of Rs. ' . number_format($validated['amount'], 2) . ' recorded. New balance: Rs. ' . number_format($customer->fresh()->balance, 2));
    }
}
