clqms-be/app/Models/Contact/ContactDetailModel.php

64 lines
1.7 KiB
PHP
Raw Normal View History

2025-09-24 16:15:55 +07:00
<?php
2025-10-14 18:53:06 +07:00
namespace App\Models\Contact;
2025-09-24 16:15:55 +07:00
2025-10-14 18:53:06 +07:00
use App\Models\BaseModel;
2025-09-24 16:15:55 +07:00
2025-10-14 18:53:06 +07:00
class ContactDetailModel extends BaseModel {
2025-09-24 16:15:55 +07:00
protected $table = 'contactdetail';
protected $primaryKey = 'ContactDetID';
protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate'];
2025-10-13 11:08:26 +07:00
protected $useTimestamps = true;
protected $createdField = 'ContactStartDate';
2025-10-13 12:28:09 +07:00
protected $updatedField = '';
2025-09-25 09:42:17 +07:00
2025-09-25 13:30:15 +07:00
public function syncDetails(int $ContactID, array $contactDetails) {
try {
2025-09-25 13:42:37 +07:00
$keptSiteIDs = [];
2025-09-25 09:42:17 +07:00
2025-09-25 13:42:37 +07:00
foreach ($contactDetails as $detail) {
if (empty($detail['SiteID'])) {
continue;
}
2025-09-25 13:30:15 +07:00
2025-09-25 13:42:37 +07:00
$detail['ContactID'] = $ContactID;
2025-09-25 13:30:15 +07:00
2025-09-25 13:42:37 +07:00
$existing = $this->where('ContactID', $ContactID)
->where('SiteID', $detail['SiteID'])
->first();
2025-09-25 13:30:15 +07:00
2025-09-25 13:42:37 +07:00
if ($existing) {
$this->update($existing[$this->primaryKey], $detail);
2025-09-25 09:42:17 +07:00
} else {
2025-09-25 13:42:37 +07:00
$this->insert($detail);
2025-09-25 09:42:17 +07:00
}
2025-09-25 13:42:37 +07:00
$keptSiteIDs[] = $detail['SiteID'];
}
// Delete missing rows
if (!empty($keptSiteIDs)) {
$this->where('ContactID', $ContactID)
->whereNotIn('SiteID', $keptSiteIDs)
->delete();
} else {
$this->where('ContactID', $ContactID)->delete();
}
return [
'status' => 'success',
'inserted' => count($contactDetails) - count($keptSiteIDs),
'kept' => count($keptSiteIDs),
];
2025-09-25 13:30:15 +07:00
} catch (\Throwable $e) {
log_message('error', 'syncDetails error: ' . $e->getMessage());
return [
2025-09-25 13:42:37 +07:00
'status' => 'error',
'message' => $e->getMessage(),
2025-09-25 13:30:15 +07:00
];
}
}
2025-09-24 16:15:55 +07:00
}