<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Contact;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function birthdays(Request $request): JsonResponse
    {
        $user  = $request->user();
        $tz    = $user->timezone;
        $today = now($tz)->format('m-d');

        $all = Contact::where('user_id', $user->id)
            ->whereNotNull('birthday')
            ->get();

        $birthdaysToday = $all
            ->filter(fn ($c) => Carbon::parse($c->birthday)->format('m-d') === $today)
            ->values()
            ->map(fn ($c) => [
                'id'       => $c->id,
                'name'     => $c->name,
                'birthday' => $c->birthday,
                'age'      => Carbon::parse($c->birthday)->year > 1900
                    ? now()->year - Carbon::parse($c->birthday)->year
                    : null,
            ]);

        $birthdaysSoon = $all
            ->filter(function ($c) use ($tz) {
                $days = now($tz)->diffInDays(
                    Carbon::parse($c->birthday)->setYear(now($tz)->year),
                    false
                );
                return $days > 0 && $days <= 7;
            })
            ->sortBy(fn ($c) => Carbon::parse($c->birthday)->format('m-d'))
            ->values()
            ->map(fn ($c) => [
                'id'         => $c->id,
                'name'       => $c->name,
                'birthday'   => $c->birthday,
                'days_until' => (int) now($tz)->diffInDays(
                    Carbon::parse($c->birthday)->setYear(now($tz)->year),
                    false
                ),
            ]);

        return response()->json([
            'success' => true,
            'data'    => [
                'today' => $birthdaysToday,
                'soon'  => $birthdaysSoon,
            ],
        ]);
    }
}
