<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DebtPayment;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DebtPaymentController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'transaction_id' => [
                'required',
                'integer',
                'exists:transactions,id',
            ],
            'amount' => [
                'required',
                'integer',
                'min:1',
            ],
            'note' => [
                'nullable',
                'string',
                'max:255',
            ],
        ]);

        try {
            $result = DB::transaction(function () use ($validated) {

                $transaction = Transaction::find(
                    $validated['transaction_id']
                );

                if (!$transaction) {
                    throw new \Exception(
                        'Transaksi tidak ditemukan'
                    );
                }

                if ($transaction->payment_status !== 'debt') {
                    throw new \Exception(
                        'Transaksi ini bukan transaksi hutang'
                    );
                }

                $remaining =
                    $transaction->total -
                    $transaction->paid_amount;

                if ($validated['amount'] > $remaining) {
                    throw new \Exception(
                        'Jumlah pembayaran melebihi sisa hutang'
                    );
                }

                $payment = DebtPayment::create([
                    'transaction_id' =>
                        $transaction->id,
                    'payment_date' => now(),
                    'amount' =>
                        $validated['amount'],
                    'note' =>
                        $validated['note'] ?? null,
                ]);

                $newPaidAmount =
                    $transaction->paid_amount +
                    $validated['amount'];

                $transaction->paid_amount =
                    $newPaidAmount;

                if ($newPaidAmount >= $transaction->total) {
                    $transaction->payment_status = 'paid';
                    $transaction->change_amount = 0;
                }

                $transaction->save();

                return [
                    'payment' => $payment,
                    'transaction' => $transaction,
                    'remaining' =>
                        $transaction->total -
                        $transaction->paid_amount,
                ];
            });

            return response()->json([
                'success' => true,
                'message' =>
                    'Pembayaran hutang berhasil disimpan',
                'data' => $result,
            ], 201);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 422);
        }
    }
}