<?php

namespace App\Http\Controllers;

use App\Models\Supplier;
use App\Models\SupplierPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SupplierPaymentController extends Controller
{
    public function create(Supplier $supplier)
    {
        return view('suppliers.payment', compact('supplier'));
    }

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

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

            $supplier->recalculateBalance();
        });

        return redirect()->route('suppliers.show', $supplier)->with('success', 'Payment recorded.');
    }
}
