<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\CalendarService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MobileCalendarController extends Controller
{
    public function __construct(protected CalendarService $calendar) {}

    public function index(Request $request): JsonResponse
    {
        $siswa = $request->attributes->get('auth_siswa');
        $nouid = $siswa->indentitas?->nouid ?: $siswa->nis;

        if (!$nouid) {
            return response()->json([
                'success' => false,
                'message' => 'UID siswa aktif tidak valid.',
            ], 400);
        }

        $start = $request->input('start');
        $end = $request->input('end');
        $search = $request->input('search');
        $categorySlugs = $request->input('categories');

        if (is_string($categorySlugs)) {
            $categorySlugs = explode(',', $categorySlugs);
        }

        $categories = $this->calendar->getCategories();
        $events = $this->calendar->getEvents($nouid, $start, $end, $categorySlugs, $search);

        return response()->json([
            'success' => true,
            'message' => 'Kalender akademik berhasil diambil.',
            'data' => [
                'categories' => $categories->map(fn ($c) => [
                    'id' => (int) $c->id,
                    'slug' => (string) ($c->slug ?? ''),
                    'name' => (string) ($c->name ?? ''),
                    'color' => (string) ($c->color ?? '#d1d5db'),
                    'icon' => $c->icon ? (string) $c->icon : null,
                ])->values()->all(),
                'events' => $events->map(fn ($e) => [
                    'id' => (int) $e->id,
                    'title' => (string) ($e->judul ?? ''),
                    'start' => $e->start_at ? $e->start_at->toIso8601String() : null,
                    'end' => $e->end_at ? $e->end_at->toIso8601String() : null,
                    'all_day' => (bool) $e->fullday,
                    'description' => $e->desk ? (string) $e->desk : null,
                    'location' => $e->lokasi ? (string) $e->lokasi : null,
                    'status' => (string) ($e->sifat_label ?? 'opsional'),
                    'is_important' => (bool) $e->penting,
                    'category' => $e->category ? [
                        'id' => (int) $e->category->id,
                        'slug' => (string) ($e->category->slug ?? ''),
                        'name' => (string) ($e->category->name ?? ''),
                        'color' => (string) ($e->category->color ?? '#d1d5db'),
                        'icon' => $e->category->icon ? (string) $e->category->icon : null,
                    ] : null,
                ])->values()->all(),
            ],
        ]);
    }
}
