<?php

namespace App\Http\Controllers\API\v1\Admin\Allowance;

use App\AllowancePayout;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class VoidController extends Controller
{
    public function __invoke(Request $request, $id)
    {
        $this->validate($request, [
            'note' => 'nullable|string|max:2000',
        ]);

        $payout = AllowancePayout::find($id);
        if (!$payout) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Payout not found.',
            ], 404);
        }

        $note = trim((string) $request->input('note', ''));
        if ($note !== '') {
            $payout->note = $payout->note ? ($payout->note . "\n\nVOID NOTE: " . $note) : ("VOID NOTE: " . $note);
        }

        $payout->status = 'void';
        $payout->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Payout voided.',
            'payout' => $payout,
            'voided_at' => Carbon::now(),
        ]);
    }
}

