<?php

namespace App\Http\Controllers\Api\Administrator;

use App\Http\Controllers\Controller;
use App\Services\Administrator\AdministratorNotificationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdministratorNotificationController extends Controller
{
    public function __construct(
        protected AdministratorNotificationService $service
    ) {
    }

    public function alerts(): JsonResponse
    {
        return response()->json($this->service->notificationsAlertsData());
    }

    public function saveAlerts(Request $request): JsonResponse
    {
        $payload = $request->all();
        if (!array_key_exists('subjects', $payload)) {
            $json = json_decode($request->getContent() ?: '', true);
            if (is_array($json)) {
                $payload = array_merge($payload, $json);
            }
        }

        $validator = Validator::make($payload, [
            'subjects' => ['required', 'array'],
        ], [
            'subjects.required' => 'Subjects payload is required.',
            'subjects.array' => 'Subjects payload must be an array.',
        ]);

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

        $data = $validator->validated();
        $result = $this->service->saveNotificationSubjects(
            (array) ($data['subjects'] ?? [])
        );

        return response()->json(['message' => $result['message']], $result['status']);
    }

    public function printRecipients(): JsonResponse
    {
        return response()->json($this->service->printNotificationRecipientsData());
    }

    public function savePrintRecipients(Request $request): JsonResponse
    {
        $payload = $request->all();
        if (!array_key_exists('notify', $payload)) {
            $json = json_decode($request->getContent() ?: '', true);
            if (is_array($json)) {
                $payload = array_merge($payload, $json);
            }
        }

        $validator = Validator::make($payload, [
            'notify' => ['required', 'array'],
        ], [
            'notify.required' => 'Notify payload is required.',
            'notify.array' => 'Notify payload must be an array.',
        ]);

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

        $data = $validator->validated();
        $result = $this->service->savePrintNotificationRecipients(
            (array) ($data['notify'] ?? [])
        );

        return response()->json(['message' => $result['message']], $result['status']);
    }
}
