Files
alrahma_sunday_school_api/app/Http/Controllers/Api/EmergencyContactController.php
T
2026-03-05 12:29:37 -05:00

252 lines
9.0 KiB
PHP
Executable File

<?php
namespace App\Http\Controllers\Api;
use App\Models\Configuration;
use App\Models\EmergencyContact;
use App\Models\Student;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class EmergencyContactController extends BaseApiController
{
protected EmergencyContact $emergencyContact;
protected Configuration $config;
protected Student $student;
protected User $user;
public function __construct()
{
parent::__construct();
$this->emergencyContact = model(EmergencyContact::class);
$this->config = model(Configuration::class);
$this->student = model(Student::class);
$this->user = model(User::class);
}
public function index()
{
$parentId = $this->request->getGet('parent_id');
$schoolYear = $this->config->getConfig('school_year');
$semester = $this->config->getConfig('semester');
$query = $this->emergencyContact->newQuery();
if ($parentId) {
$query->where('parent_id', $parentId);
}
if ($schoolYear) {
$query->where('school_year', $schoolYear);
}
if ($semester) {
$query->where('semester', $semester);
}
$contacts = $query->get()->toArray();
return $this->success($contacts, 'Emergency contacts retrieved successfully');
}
public function show($id = null)
{
$contact = $this->emergencyContact->find($id);
if (!$contact) {
return $this->respondError('Emergency contact not found', Response::HTTP_NOT_FOUND);
}
return $this->success($contact, 'Emergency contact retrieved successfully');
}
public function getByParent($id = null)
{
$schoolYear = $this->config->getConfig('school_year');
$semester = $this->config->getConfig('semester');
$contacts = $this->emergencyContact->newQuery()
->where('parent_id', $id);
if ($schoolYear) {
$contacts->where('school_year', $schoolYear);
}
if ($semester) {
$contacts->where('semester', $semester);
}
return $this->success($contacts->get()->toArray(), 'Emergency contacts retrieved successfully');
}
public function create()
{
$data = $this->payloadData();
if (empty($data)) {
return $this->respondError('Invalid request data', Response::HTTP_BAD_REQUEST);
}
$rules = [
'parent_id' => 'required|integer',
'emergency_contact_name' => 'required|max_length[255]',
'cellphone' => 'required|max_length[20]',
'relation' => 'required|max_length[50]',
];
$errors = $this->validateRequest($data, $rules);
if (!empty($errors)) {
return $this->respondValidationError($errors);
}
$payload = [
'parent_id' => $data['parent_id'],
'emergency_contact_name'=> $data['emergency_contact_name'],
'cellphone' => $data['cellphone'],
'email' => $data['email'] ?? null,
'relation' => $data['relation'],
'school_year' => $this->config->getConfig('school_year'),
'semester' => $this->config->getConfig('semester'),
];
try {
$contact = $this->emergencyContact->create($payload);
return $this->respondCreated([
'id' => $contact->id,
'data' => $contact,
], 'Emergency contact created successfully');
} catch (\Throwable $e) {
Log::error('Emergency contact creation error: ' . $e->getMessage());
return $this->respondError('Failed to create emergency contact', Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
public function update($id = null)
{
$contact = $this->emergencyContact->find($id);
if (!$contact) {
return $this->respondError('Emergency contact not found', Response::HTTP_NOT_FOUND);
}
$data = $this->payloadData();
if (empty($data)) {
return $this->respondError('Invalid request data', Response::HTTP_BAD_REQUEST);
}
$allowed = ['emergency_contact_name', 'cellphone', 'email', 'relation'];
$updateData = [];
foreach ($allowed as $field) {
if (array_key_exists($field, $data)) {
$updateData[$field] = $data[$field];
}
}
if (empty($updateData)) {
return $this->respondError('No valid fields to update', Response::HTTP_BAD_REQUEST);
}
try {
$contact->fill($updateData);
$contact->save();
return $this->success($contact->fresh(), 'Emergency contact updated successfully');
} catch (\Throwable $e) {
Log::error('Emergency contact update error: ' . $e->getMessage());
return $this->respondError('Failed to update emergency contact', Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
public function delete($id = null)
{
$contact = $this->emergencyContact->find($id);
if (!$contact) {
return $this->respondError('Emergency contact not found', Response::HTTP_NOT_FOUND);
}
try {
$contact->delete();
return $this->success(null, 'Emergency contact deleted successfully');
} catch (\Throwable $e) {
Log::error('Emergency contact deletion error: ' . $e->getMessage());
return $this->respondError('Failed to delete emergency contact', Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* GET /api/v1/emergency-contacts/data
* Returns JSON payload for emergency contacts grouped by parent with parent info, students, and contacts.
*/
public function data()
{
try {
// Get distinct parent IDs from emergency contacts
$parentRows = $this->emergencyContact->newQuery()
->distinct()
->select('parent_id')
->get()
->toArray();
$groups = [];
foreach ($parentRows as $row) {
$parentId = (int)($row['parent_id'] ?? 0);
if ($parentId <= 0) {
continue;
}
// Get parent info
$parent = $this->user->find($parentId);
$parentName = 'Unknown Parent';
$parentPhone = '';
if ($parent) {
$parentName = trim(($parent['firstname'] ?? '') . ' ' . ($parent['lastname'] ?? '')) ?: 'Unknown Parent';
$parentPhone = (string)($parent['cellphone'] ?? '');
}
// Try to load second parent phone from parents table
$secondPhone = '';
try {
$secondParentRow = DB::table('parents')
->select('secondparent_phone')
->where('firstparent_id', $parentId)
->orderBy('updated_at', 'DESC')
->first();
if ($secondParentRow && !empty($secondParentRow->secondparent_phone)) {
$secondPhone = (string)$secondParentRow->secondparent_phone;
}
} catch (\Throwable $e) {
Log::debug('EmergencyContactController: could not load second parent phone: ' . $e->getMessage());
}
// Get students for this parent
$students = $this->student->newQuery()
->select('id', 'firstname', 'lastname', 'school_id')
->where('parent_id', $parentId)
->get()
->toArray();
// Get emergency contacts for this parent
$contacts = $this->emergencyContact->newQuery()
->where('parent_id', $parentId)
->orderBy('updated_at', 'DESC')
->get()
->toArray();
// Filter out empty phone numbers
$parentPhones = array_values(array_filter([$parentPhone, $secondPhone], static fn($v) => (string)$v !== ''));
$groups[] = [
'parent_id' => $parentId,
'parent_name' => $parentName,
'students' => $students,
'contacts' => $contacts,
'parent_phones' => $parentPhones,
];
}
return $this->success([
'groups' => $groups,
], 'Emergency contacts grouped by parent retrieved successfully');
} catch (\Throwable $e) {
Log::error('Emergency contact data error: ' . $e->getMessage());
return $this->respondError('Failed to retrieve emergency contact data', Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
}