clqms-be/app/Controllers/Contact.php
2025-09-23 16:55:28 +07:00

255 lines
9.3 KiB
PHP

<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use CodeIgniter\Database\RawSql;
class Contact extends Controller {
use ResponseTrait;
public function __construct() {
$this->db = \Config\Database::connect();
$this->rulesContact = [
'NameFirst' => 'required'
];
}
public function index() {
$sql = $this->db->table('contact c')
->select("c.ContactID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty")
->join("contactdetail cd", "c.ContactID=cd.ContactID", "left")
->join("occupation o","cd.OccupationID=o.OccupationID", "left");
$rows = $sql->get()->getResultArray();
if (empty($rows)) {
return $this->respond([
'status' => 'success',
'message' => "no Data.",
'data' => $rows,
], 200);
}
return $this->respond([
'status' => 'success',
'message'=> "fetch success",
'data' => $rows,
], 200);
}
public function show($ContactID = null) {
$rows=$this->db->table('contact c')
->select("*")
->join("contactdetail cd", "c.ContactID=cd.ContactID", "left")
->join("occupation o","o.OccupationID=cd.OccupationID", "left")
->where('c.ContactID', (int) $ContactID)
->get()->getResultArray();
if (empty($rows)) {
return $this->respond([
'status' => 'success',
'message' => "Data not found.",
'data' => [],
], 200);
}
// Rebuild into nested structure
$contact = [
'ContactID' => $rows[0]['ContactID'],
'NameFirst' => $rows[0]['NameFirst'] ?? null,
'NameLast' => $rows[0]['NameLast'] ?? null,
'Title' => $rows[0]['Title'] ?? null,
'Initial' => $rows[0]['Initial'] ?? null,
'Birthdate' => $rows[0]['Birthdate'] ?? null,
'EmailAddress1' => $rows[0]['EmailAddress1'] ?? null,
'EmailAddress2' => $rows[0]['EmailAddress2'] ?? null,
'Phone' => $rows[0]['Phone'] ?? null,
'MobilePhone1' => $rows[0]['MobilePhone1'] ?? null,
'MobilePhone2' => $rows[0]['MobilePhone2'] ?? null,
'Specialty' => $rows[0]['Specialty'] ?? null,
'SubSpecialty' => $rows[0]['SubSpecialty'] ?? null,
'Details' => []
];
foreach ($rows as $row) {
if (!empty($row['ContactDetID'])) {
$contact['Details'][] = [
'ContactDetID' => $row['ContactDetID'],
'ContactCode' => $row['ContactCode'] ?? null,
'ContactEmail' => $row['DetailPhone'] ?? null,
'OccupationID' => $row['OccupationID'] ?? null,
'JobTitle' => $row['JobTitle'] ?? null,
'Department' => $row['Department'] ?? null,
'ContactStartDate' => $row['ContactStartDate'] ?? null,
'ContactEndDate' => $row['ContactEndDate'] ?? null
];
}
}
return $this->respond([
'status' => 'success',
'message'=> "Data fetched successfully",
'data' => $contact,
], 200);
}
public function create() {
try {
$input = $this->request->getJSON(true);
// Prepare data
$dataContact = $this->prepareContactData($input);
$dataContactDetail = $this->prepareContactDetailData($input);
if (!$this->validateData($dataContact, $this->rulesContact)) {
return $this->failValidationErrors($this->validator->getErrors());
}
// Start transaction
$this->db->transStart();
$this->db->table('contact')->insert($dataContact);
$newContactID = $this->db->insertID();
if (!empty($dataContactDetail)) {
$dataContactDetail['ContactID'] = $newContactID;
$this->db->table('contactdetail')->insert($dataContactDetail);
}
if ($this->db->transStatus() === false) {
$dbError = $this->db->error();
return $this->failServerError(
'Failed to create data (transaction rolled back): ' . ( $dbError['message'] ?? 'Unknown database error')
);
}
// Complete transaction
$this->db->transComplete();
return $this->respondCreated([
'status' => 'success',
'message' => 'Contact created successfully',
'data' => $dataContact,
], 201);
} catch (\Throwable $e) {
// Ensure rollback if something goes wrong
if ($this->db->transStatus() !== false) {
$this->db->transRollback();
}
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function update() {
try {
$input = $this->request->getJSON(true);
// Prepare data
$dataContact = $this->prepareContactData($input);
$dataContactDetail = $this->prepareContactDetailData($input);
if (!$this->validateData($dataContact, $this->rulesContact)) {
return $this->failValidationErrors( $this->validator->getErrors());
}
// Start transaction
$this->db->transStart();
$this->db->table('contact')->where('ContactID', $dataContact["ContactID"])->update($dataContact);
// Insert address if available
if (!empty($dataContactDetail)) {
$dataContactDetail['ContactID'] = $input["ContactID"];
$this->db->table('contactdetail')->upsert($dataContactDetail);
}
// Complete transaction
$this->db->transComplete();
if ($this->db->transStatus() === false) {
$dbError = $this->db->error();
return $this->failServerError(
'Failed to update contact data (transaction rolled back): ' . ($dbError['message'] ?? 'Unknown database error')
);
}
return $this->respondCreated([
'status' => 'success',
'message' => 'Contact updated successfully',
'data' => $dataContact,
], 201);
} catch (\Throwable $e) {
// Ensure rollback if something goes wrong
if ($this->db->transStatus() !== false) {
$this->db->transRollback();
}
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function delete() {
try {
$input = $this->request->getJSON(true);
$ContactID = $input["ContactID"];
if (!$ContactID) {
return $this->failValidationError('ContactID is required.');
}
$contact = $this->db->table('contact')->where('ContactID', $ContactID)->get()->getRow();
if (!$contact) {
return $this->failNotFound("data with {$ContactID} not found.");
}
$this->db->table('contact')->where('ContactID', $ContactID)->update(['EndDate' => NOW()]);
return $this->respondDeleted([
'status' => 'success',
'message' => "Contact with {$ContactID} deleted successfully."
]);
} catch (\Throwable $e) {
// Ensure rollback if something goes wrong
if ($this->db->transStatus() !== false) {
$this->db->transRollback();
}
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
private function prepareContactData(array $input): array {
$data = [
"NameFirst" => $input['NameFirst'] ?? null,
"NameLast" => $input['NameLast'] ?? null,
"Title" => $input['Title'] ?? null,
"Initial" => $input['Initial'] ?? null,
"Birthdate" => $input['Birthdate'] ?? null,
"EmailAddress1" => $input['EmailAddress1'] ?? null,
"EmailAddress2" => $input['EmailAddress2'] ?? null,
"Phone" => $input["Phone"] ?? null,
"MobilePhone1" => $input["MobilePhone1"] ?? null,
"MobilePhone2" => $input["MobilePhone2"] ?? null,
"Specialty" => $input["Specialty"] ?? null,
"SubSpecialty" => $input["SubSpecialty"] ?? null,
];
if(!empty($input["ContactID"])) { $data["ContactID"] = $input["ContactID"]; }
return $data;
}
private function prepareContactDetailData(array $input): array {
$data = [
"ContactCode" => $input['ContactCode'] ?? null,
"ContactEmail" => $input['ContactEmail'] ?? null,
"OccupationID" => $input['OccupationID'] ?? null,
"JobTitle" => $input['JobTitle'] ?? null,
"Department" => $input['Department'] ?? null,
"ContactStartDate" => $input['ContactStartDate'] ?? null,
"ContactEndDate" => $input['ContactEndDate'] ?? null,
];
return $data;
}
}