<?php

namespace App\Models;

use CodeIgniter\Model;

class StaffModel extends Model
{
    protected $table            = 'staff';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;

    protected $returnType       = 'array';
    protected $useSoftDeletes   = false; // We're handling 'inactive' via active_role column

    protected $allowedFields = [
        'user_id',
        'firstname',
        'lastname',
        'email',
        'phone',
        'role_name',
        'active_role',
        'created_at',
        'updated_at'
    ];

    protected $useTimestamps = false; // 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.
     * 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;
        }

        unset($data['school_year'], $data['status']);

        $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;
    }
}
