<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Resources\Payments\PaymentTransactionResource;
use App\Services\Payments\PaymentTransactionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PaymentTransactionController extends BaseApiController
{
    public function __construct(private PaymentTransactionService $service)
    {
        parent::__construct();
    }

    public function store(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'transaction_id' => ['required', 'string', 'max:100'],
            'payment_id' => ['required', 'integer', 'min:1'],
            'transaction_date' => ['nullable', 'date'],
            'amount' => ['required', 'numeric', 'min:0.01'],
            'payment_method' => ['required', 'string', 'max:50'],
            'payment_status' => ['nullable', 'string', 'max:50'],
            'transaction_fee' => ['nullable', 'numeric', 'min:0'],
            'payment_reference' => ['nullable', 'string', 'max:100'],
            'is_full_payment' => ['nullable', 'boolean'],
            'school_year' => ['nullable', 'string', 'max:50'],
            'semester' => ['nullable', 'string', 'max:50'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $payload = $validator->validated();
        $transaction = $this->service->create($payload);

        return response()->json([
            'ok' => true,
            'transaction' => new PaymentTransactionResource($transaction->toArray()),
        ], 201);
    }

    public function byPayment(int $paymentId): JsonResponse
    {
        $transactions = $this->service->getByPayment($paymentId);

        return response()->json([
            'ok' => true,
            'transactions' => PaymentTransactionResource::collection($transactions),
        ]);
    }

    public function updateStatus(Request $request, string $transactionId): JsonResponse
    {
        $status = $request->input('status');
        if ($status === null) {
            $raw = $request->getContent() ?: '';
            $json = json_decode($raw, true);
            if (is_array($json) && array_key_exists('status', $json)) {
                $status = $json['status'];
            } else {
                $parsed = [];
                parse_str($raw, $parsed);
                $status = $parsed['status'] ?? null;
            }
        }

        if ($status === null || trim((string) $status) === '') {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => ['status' => ['The status field is required.']],
            ], 422);
        }

        $updated = $this->service->updateStatus($transactionId, (string) $status);

        if (!$updated) {
            return response()->json(['ok' => false, 'message' => 'Transaction not found.'], 404);
        }

        return response()->json(['ok' => true]);
    }
}
