<?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',
        'status',
        'school_year',
        '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, 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;
    }
}

