migrant-web/app/Http/Controllers/Api/EmployerAnnouncementController.php

266 lines
10 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class EmployerAnnouncementController extends Controller
{
/**
* Get all approved announcements for employers.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function getAnnouncements(Request $request)
{
try {
$page = (int)$request->input('page', 1);
$perPage = (int)$request->input('per_page', 15);
$query = Announcement::with(['employer.employerProfile', 'sponsor'])->where('status', 'approved')->latest();
$total = $query->count();
$offset = ($page - 1) * $perPage;
$announcements = $query->skip($offset)->take($perPage)->get()
->map(function ($announcement) {
$postedBy = 'System';
$organization = 'Migrant Support';
if ($announcement->sponsor_id) {
$postedBy = $announcement->sponsor->full_name;
$organization = $announcement->sponsor->organization_name;
} elseif ($announcement->employer_id) {
$postedBy = $announcement->employer->name;
$organization = $announcement->employer->employerProfile->company_name ?? 'Employer';
}
// Decode charity details if they exist in json
$charityDetails = null;
$content = $announcement->body;
if (strpos($announcement->body, '{"type":"Charity"') === 0) {
$decoded = json_decode($announcement->body, true);
if ($decoded) {
$charityDetails = $decoded;
$content = $decoded['content'] ?? $announcement->body;
}
}
return [
'id' => $announcement->id,
'title' => $announcement->title,
'body' => $content,
'type' => $announcement->type,
'employer_name' => $postedBy,
'company_name' => $organization,
'created_at' => $announcement->created_at->toISOString(),
'time_ago' => $announcement->created_at->diffForHumans(),
'charity_details' => $charityDetails,
];
});
return response()->json([
'success' => true,
'data' => [
'announcements' => $announcements,
'pagination' => [
'total' => $total,
'per_page' => $perPage,
'current_page' => $page,
'last_page' => max(1, (int)ceil($total / $perPage)),
]
]
], 200);
} catch (\Exception $e) {
logger()->error('Mobile Employer Get All 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);
}
}
/**
* Get all announcements posted by this employer.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function getMyAnnouncements(Request $request)
{
/** @var User $employer */
$employer = $request->attributes->get('employer');
try {
$page = (int)$request->input('page', 1);
$perPage = (int)$request->input('per_page', 15);
$query = Announcement::where('employer_id', $employer->id)->latest();
$total = $query->count();
$offset = ($page - 1) * $perPage;
$announcements = $query->skip($offset)->take($perPage)->get()
->map(function ($announcement) {
return [
'id' => $announcement->id,
'title' => $announcement->title,
'body' => $announcement->body,
'type' => $announcement->type,
'status' => $announcement->status ?? 'pending',
'remarks' => $announcement->remarks,
'created_at' => $announcement->created_at->toISOString(),
'time_ago' => $announcement->created_at->diffForHumans(),
];
});
return response()->json([
'success' => true,
'data' => [
'announcements' => $announcements,
'pagination' => [
'total' => $total,
'per_page' => $perPage,
'current_page' => $page,
'last_page' => max(1, (int)ceil($total / $perPage)),
]
]
], 200);
} catch (\Exception $e) {
logger()->error('Mobile Employer Get My 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);
}
}
/**
* Create a new announcement for workers.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function createAnnouncement(Request $request)
{
/** @var User $employer */
$employer = $request->attributes->get('employer');
$validator = Validator::make($request->all(), [
'title' => 'required|string|max:255',
'body' => 'required_without:content|string|max:5000',
'content' => 'required_without:body|string|max:5000',
'type' => 'nullable|string|in:info,warning,success',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => 'Validation error.',
'errors' => $validator->errors()
], 422);
}
try {
$bodyText = $request->body ?? $request->content;
// Append extra event details if they are provided
$extras = [];
if ($request->event_date) $extras[] = "Date: " . $request->event_date;
if ($request->event_time) $extras[] = "Time: " . $request->event_time;
if ($request->location_details) $extras[] = "Location: " . $request->location_details;
if ($request->location_pin) $extras[] = "Map Pin: " . $request->location_pin;
if ($request->provided_items) $extras[] = "Provided: " . $request->provided_items;
if (!empty($extras)) {
$bodyText .= "\n\n" . implode("\n", $extras);
}
$announcement = Announcement::create([
'title' => $request->title,
'body' => $bodyText,
'type' => $request->type ?? 'info',
'employer_id' => $employer->id,
'status' => 'pending',
]);
return response()->json([
'success' => true,
'message' => 'Announcement posted successfully.',
'data' => [
'announcement' => [
'id' => $announcement->id,
'title' => $announcement->title,
'body' => $announcement->body,
'type' => $announcement->type,
'status' => $announcement->status ?? 'pending',
'remarks' => $announcement->remarks,
'created_at' => $announcement->created_at->toISOString(),
'time_ago' => $announcement->created_at->diffForHumans(),
]
]
], 201);
} catch (\Exception $e) {
logger()->error('Mobile Employer Create Announcement Failure: ' . $e->getMessage());
return response()->json([
'success' => false,
'message' => 'An error occurred while creating the announcement.',
'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
], 500);
}
}
/**
* Delete an announcement.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\JsonResponse
*/
public function deleteAnnouncement(Request $request, $id)
{
/** @var User $employer */
$employer = $request->attributes->get('employer');
try {
$announcement = Announcement::where('employer_id', $employer->id)
->where('id', $id)
->first();
if (!$announcement) {
return response()->json([
'success' => false,
'message' => 'Announcement not found or unauthorized.'
], 404);
}
$announcement->delete();
return response()->json([
'success' => true,
'message' => 'Announcement deleted successfully.'
], 200);
} catch (\Exception $e) {
logger()->error('Mobile Employer Delete Announcement Failure: ' . $e->getMessage());
return response()->json([
'success' => false,
'message' => 'An error occurred while deleting the announcement.',
'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
], 500);
}
}
}