<?php

namespace App\Models;

use CodeIgniter\Model;

class EdgeResModel extends Model {
    protected $table = 'edgeres';
    protected $primaryKey = 'EdgeResID';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'SiteID',
        'InstrumentID',
        'SampleID',
        'PatientID',
        'Payload',
        'Status',
        'AutoProcess',
        'ProcessedAt',
        'ErrorMessage',
        'CreateDate',
        'EndDate',
        'ArchiveDate',
        'DelDate'
    ];

    protected $useTimestamps = false;
    protected $createdField = 'CreateDate';
    protected $updatedField = 'EndDate';

    /**
     * Get pending results for processing
     */
    public function getPending($limit = 100) {
        return $this->where('Status', 'pending')
                    ->whereNull('DelDate')
                    ->orderBy('CreateDate', 'ASC')
                    ->findAll($limit);
    }

    /**
     * Mark as processed
     */
    public function markProcessed($id) {
        return $this->update($id, [
            'Status' => 'processed',
            'ProcessedAt' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * Mark as error
     */
    public function markError($id, $errorMessage) {
        return $this->update($id, [
            'Status' => 'error',
            'ErrorMessage' => $errorMessage,
            'ProcessedAt' => date('Y-m-d H:i:s')
        ]);
    }
}
