<?php

namespace App\Models;

use CodeIgniter\Model;

class HistorySensorModel extends Model
{
    protected $table            = 'tbl_history_sensor';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useSoftDeletes   = false;
    protected $protectFields    = false;
    protected $allowedFields    = [];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];


    public function getLastedHistoryRpm()
    {

        $this->select('created_at, to_value');
        $this->where('sensor_id',1);
        $this->orderBy('id',"DESC");
        $this->limit(10);
        $results = $this->findAll();

        $values = [];
        $labels = [];
        if(!empty($results)){                
            foreach($results AS $row){
                $values[] = $row->to_value;
                $labels[] = date("H:i:s", strtotime($row->created_at));
            }
        }

        return [
            'value' => !empty($results[0]) ? $results[0]->to_value : 0,
            'history'   => [
                'labels'    => array_reverse($labels),
                'values'    => array_reverse($values),
            ]
        ];
    }


    public function getLastedHistoryTemperature()
    {

        $this->select('created_at, to_value');
        $this->where('sensor_id',2);
        $this->orderBy('id',"DESC");
        $this->limit(10);
        $results = $this->findAll();

        $values = [];
        $labels = [];
        if(!empty($results)){                
            foreach($results AS $row){
                $values[] = $row->to_value;
                $labels[] = date("H:i:s", strtotime($row->created_at));
            }
        }

        return [
            'value' => !empty($results[0]) ? $results[0]->to_value : 0,
            'history'   => [
                'labels'    => array_reverse($labels),
                'values'    => array_reverse($values),
            ]
        ];
    }




}
