<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use Illuminate\Http\Request;

class WorkerAnnouncementController extends Controller
{
    /**
     * Get all announcements for workers.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAnnouncements(Request $request)
    {
        try {
            $announcements = Announcement::with('employer.employerProfile')
                ->latest()
                ->get()
                ->map(function ($announcement) {
                    return [
                        'id' => $announcement->id,
                        'title' => $announcement->title,
                        'body' => $announcement->body,
                        'type' => $announcement->type,
                        'employer_name' => $announcement->employer->name ?? 'System',
                        'company_name' => $announcement->employer->employerProfile->company_name ?? 'Migrant Support',
                        'created_at' => $announcement->created_at->toISOString(),
                        'time_ago' => $announcement->created_at->diffForHumans(),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'announcements' => $announcements
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Worker Get Announcements Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching announcements.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }
}
