100 lines
3.0 KiB
PHP
100 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Models\BaseModel;
|
|
|
|
class Staff extends BaseModel
|
|
{
|
|
protected $table = 'staff';
|
|
protected $primaryKey = 'id';
|
|
protected $useAutoIncrement = true;
|
|
protected $useSoftDeletes = false; // We're handling 'inactive' via active_role column
|
|
protected $fillable = [
|
|
'firstname',
|
|
'lastname',
|
|
'email',
|
|
'phone',
|
|
'role_name',
|
|
'school_year',
|
|
'active_role',
|
|
'created_at',
|
|
'updated_at',
|
|
'user_id',
|
|
];
|
|
|
|
public $timestamps = true; // Managed manually in controller
|
|
|
|
public function getActiveStaff()
|
|
{
|
|
return $this->where('active_role !=', 'inactive')
|
|
->orderBy('created_at', 'DESC')
|
|
->findAll();
|
|
}
|
|
|
|
public function getInactiveStaff()
|
|
{
|
|
return $this->where('active_role', 'inactive')
|
|
->orderBy('updated_at', 'DESC')
|
|
->findAll();
|
|
}
|
|
|
|
/**
|
|
* Insert or update a staff row keyed by (user_id, school_year).
|
|
* Ensures created_at is only set on insert and updated_at can be provided by caller.
|
|
*/
|
|
public function upsert(array $data): bool
|
|
{
|
|
if (!isset($data['user_id'])) {
|
|
return false;
|
|
}
|
|
|
|
// If school_year not provided, try to keep existing or fall back to current year string
|
|
$schoolYear = $data['school_year'] ?? null;
|
|
|
|
if ($schoolYear === null) {
|
|
// Try to find any existing row by user_id to reuse its school_year
|
|
$existingAny = $this->where('user_id', $data['user_id'])->orderBy('id', 'DESC')->first();
|
|
if ($existingAny && isset($existingAny['school_year'])) {
|
|
$schoolYear = $existingAny['school_year'];
|
|
$data['school_year'] = $schoolYear;
|
|
}
|
|
}
|
|
|
|
$existing = null;
|
|
if ($schoolYear !== null) {
|
|
$existing = $this->where('user_id', $data['user_id'])
|
|
->where('school_year', $schoolYear)
|
|
->first();
|
|
} else {
|
|
// If no school_year, treat (user_id) as key
|
|
$existing = $this->where('user_id', $data['user_id'])->first();
|
|
}
|
|
|
|
$now = utc_now();
|
|
|
|
if ($existing) {
|
|
// Preserve original created_at unless explicitly provided
|
|
if (!isset($data['created_at']) && isset($existing['created_at'])) {
|
|
$data['created_at'] = $existing['created_at'];
|
|
}
|
|
// Ensure updated_at exists
|
|
if (!isset($data['updated_at'])) {
|
|
$data['updated_at'] = $now;
|
|
}
|
|
return $this->update($existing['id'], $data);
|
|
}
|
|
|
|
// New row — set created_at/updated_at if not provided
|
|
if (!isset($data['created_at'])) {
|
|
$data['created_at'] = $now;
|
|
}
|
|
if (!isset($data['updated_at'])) {
|
|
$data['updated_at'] = $now;
|
|
}
|
|
|
|
return $this->insert($data) !== false;
|
|
}
|
|
}
|
|
|