<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\CommitteeApproval;
use App\Models\CreditsDeductable; // Import the correct model
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PaymentController extends Controller
{
   public function store(Request $request)
{
    $validated = $request->validate([
        'approval_id' => 'required|exists:creditcommittee_approvals,id',
        'amount' => 'required|numeric|min:0.01',
        'payment_date' => 'required|date',
        'method' => 'required|string|max:50',
        'notes' => 'nullable|string',
        'reference_number' => 'nullable|string|max:100',
    ]);

    // Retrieve approval record
    $approval = CommitteeApproval::findOrFail($validated['approval_id']);

    // Require reference number for non-cash payments
    if ($validated['method'] !== 'cash' && empty($validated['reference_number'])) {
        return response()->json([
            'message' => 'Reference number is required for non-cash payments.'
        ], 422);
    }

    // Convert payedAmount safely to numeric
    $currentPaid = (float) $approval->payedAmount;
    $totalRepayable = (float) $approval->total_repayable;

    // Calculate new total after payment
    $newTotalPaid = $currentPaid + (float) $validated['amount'];

    // Check if new total exceeds repayable amount
    if ($newTotalPaid > $totalRepayable) {
        return response()->json([
            'message' => 'Payment exceeds total repayable amount.',
            'total_repayable' => $totalRepayable,
            'already_paid' => $currentPaid,
            'attempted_payment' => (float) $validated['amount'],
            'remaining_balance' => $totalRepayable - $currentPaid,
        ], 422);
    }

    // Save the payment record
    $payment = Payment::create([
        'credit_id' => $approval->id,
        'client_id' => $approval->client_id,
        'amount' => $validated['amount'],
        'payment_date' => $validated['payment_date'],
        'payment_method' => $validated['method'],
        'reference_number' => $validated['reference_number'] ?? null,
        'notes' => $validated['notes'] ?? null,
        'status' => 'completed',
        'createdby' => Auth::id(),
    ]);

    // Update payedAmount field in creditcommittee_approvals
    $approval->update(['payedAmount' => $newTotalPaid]);

    // Calculate remaining balance
    $remainingBalance = $totalRepayable - $newTotalPaid;

    return response()->json([
        'message' => 'Payment recorded successfully.',
        'payment' => $payment,
        'summary' => [
            'total_repayable' => $totalRepayable,
            'total_paid' => $newTotalPaid,
            'remaining_balance' => $remainingBalance,
        ]
    ], 201);
}

    public function history($approvalId)
    {
        $payments = CommitteeApproval::where('id', $approvalId)
            ->with('client')
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($payments);
    }
}