<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Payments\PaymentManualEditRequest;
use App\Http\Requests\Payments\PaymentManualUpdateRequest;
use App\Services\Payments\PaymentManualService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

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

    public function search(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'search_term' => ['nullable', 'string', 'max:255'],
            'school_year' => ['nullable', 'string', 'max:50'],
        ]);

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

        $payload = $validator->validated();
        $data = $this->service->search(
            (string) ($payload['search_term'] ?? ''),
            $payload['school_year'] ?? null
        );

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

    public function suggest(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'q' => ['required', 'string', 'max:255'],
        ]);

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

        $payload = $validator->validated();
        $items = $this->service->suggest((string) ($payload['q'] ?? ''));

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

    public function record(PaymentManualUpdateRequest $request, int $invoiceId): JsonResponse
    {
        $payload = $request->validated();

        $result = $this->service->recordPayment(
            $invoiceId,
            (float) $payload['amount'],
            (string) $payload['payment_method'],
            $payload['payment_date'] ?? null,
            $payload['check_number'] ?? null,
            $payload['payment_type'] ?? null,
            $request->file('payment_file'),
            $payload['school_year'] ?? null,
            $payload['semester'] ?? null,
            (int) (auth()->id() ?? 0)
        );

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

    public function edit(PaymentManualEditRequest $request, int $paymentId): JsonResponse
    {
        $payload = $request->validated();

        $this->service->editPayment(
            $paymentId,
            (float) $payload['paid_amount'],
            (string) $payload['payment_method'],
            $payload['check_number'] ?? null,
            $request->file('payment_file'),
            (int) (auth()->id() ?? 0)
        );

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

    public function file(Request $request, string $filename)
    {
        $mode = (string) ($request->query('mode') ?? 'download');
        return $this->service->serveCheckFile($filename, $mode);
    }
}
