<?php

namespace App\Http\Controllers\Api\Administrator;

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

class AdministratorAbsenceController extends Controller
{
    public function __construct(
        protected AdministratorAbsenceService $service
    ) {
    }

    public function index(): JsonResponse
    {
        $userId = (int) Auth::id();
        if ($userId <= 0) {
            return response()->json(['message' => 'Please log in first.'], 401);
        }

        return response()->json($this->service->getAbsenceFormData($userId));
    }

    public function store(Request $request): JsonResponse
    {
        $userId = (int) Auth::id();
        if ($userId <= 0) {
            return response()->json(['message' => 'Please log in first.'], 401);
        }

        $payload = $request->all();
        if (!array_key_exists('dates', $payload) || !array_key_exists('reason', $payload)) {
            $json = json_decode($request->getContent() ?: '', true);
            if (is_array($json)) {
                $payload = array_merge($payload, $json);
            }
        }

        $validator = Validator::make($payload, [
            'dates' => ['required', 'array', 'min:1'],
            'dates.*' => ['required', 'date_format:Y-m-d'],
            'reason_type' => ['nullable', 'string', 'max:100'],
            'reason' => ['required', 'string', 'max:2000'],
        ], [
            'dates.required' => 'At least one date is required.',
            'dates.array' => 'Dates must be submitted as an array.',
            'dates.min' => 'At least one date is required.',
            'dates.*.date_format' => 'Each date must be in Y-m-d format.',
            'reason.required' => 'Reason is required.',
        ]);

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

        $request->merge($validator->validated());
        $result = $this->service->submit($request, $userId);

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