<?php

namespace App\Http\Controllers;

use App\Models\Activity;
use App\Models\ActivityNotificationRead;
use Illuminate\Http\Request;

class ActivityNotificationController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        $data = $request->validate([
            'activity_id' => ['sometimes', 'integer', 'exists:activities,id'],
            'activity_ids' => ['sometimes', 'array', 'min:1'],
            'activity_ids.*' => ['integer', 'exists:activities,id'],
        ]);

        $userId = optional($request->user())->id;
        if (! $userId) {
            abort(403);
        }

        $ids = [];
        if (!empty($data['activity_id'])) {
            $ids[] = $data['activity_id'];
        }
        if (!empty($data['activity_ids'])) {
            $ids = array_merge($ids, $data['activity_ids']);
        }
        $ids = array_unique($ids);

        $activities = Activity::query()->select(['id', 'due_date'])->whereIn('id', $ids)->get();
        foreach ($activities as $activity) {
            $due = optional($activity->due_date) ? date('Y-m-d', strtotime($activity->due_date)) : now()->toDateString();
            ActivityNotificationRead::query()->updateOrCreate(
                [
                    'user_id' => $userId,
                    'activity_id' => $activity->id,
                    'due_date' => $due,
                ],
                [
                    'read_at' => now(),
                ]
            );
        }

        return back();
    }
}
