<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Payments\PaymentByParentRequest;
use App\Http\Resources\Payments\PaymentResource;
use App\Services\Payments\PaymentBalanceService;
use App\Services\Payments\PaymentLookupService;
use App\Services\Payments\PaymentPlanService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PaymentController extends BaseApiController
{
    public function __construct(
        private PaymentPlanService $planService,
        private PaymentLookupService $lookupService,
        private PaymentBalanceService $balanceService
    ) {
        parent::__construct();
    }

    public function store(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'parent_id' => ['required', 'integer', 'exists:users,id'],
            'invoice_id' => ['nullable', 'integer', 'exists:invoices,id'],
            'total_amount' => ['required', 'numeric', 'min:0.01'],
            'number_of_installments' => ['required', 'integer', 'min:1'],
            'payment_date' => ['nullable', 'date'],
            'payment_method' => ['nullable', 'string', 'max:50'],
            'payment_type' => ['nullable', 'string', 'max:50'],
            'status' => ['nullable', 'string', 'max:50'],
            'semester' => ['nullable', 'string', 'max:50'],
            'school_year' => ['nullable', 'string', 'max:50'],
        ]);

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

        $payload = $validator->validated();
        $payment = $this->planService->createPlan($payload);

        return response()->json([
            'ok' => true,
            'payment' => new PaymentResource($payment),
        ], 201);
    }

    public function byParent(PaymentByParentRequest $request, int $parentId): JsonResponse
    {
        $payload = $request->validated();
        $payments = $this->lookupService->getByParent($parentId, $payload['school_year'] ?? null);

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

    public function updateBalance(Request $request, int $paymentId): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'paid_amount' => ['required', 'numeric', 'min:0.01'],
        ]);

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

        $payload = $validator->validated();
        $updated = $this->balanceService->updateBalance($paymentId, (float) $payload['paid_amount']);

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

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