<?php

namespace App\Models;

use CodeIgniter\Model;

class PromotionQueueModel extends Model
{
    protected $table      = 'promotion_queue';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'student_id',
        'from_class_section_id',
        'to_class_id',
        'to_class_section_id',
        'school_year_from',
        'school_year_to',
        'status',
        'created_at',
        'updated_at',
        'updated_by',
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    public function upsert(array $data): bool
    {
        if (empty($data['student_id']) || empty($data['school_year_to'])) {
            return false;
        }

        $existing = $this->where('student_id', (int)$data['student_id'])
            ->where('school_year_to', (string)$data['school_year_to'])
            ->first();

        if ($existing) {
            return (bool) $this->update((int)$existing[$this->primaryKey], array_merge($existing, $data));
        }

        return (bool) $this->insert($data);
    }
}

