<?php
namespace App\Controllers;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use CodeIgniter\API\ResponseTrait;
use App\Models\Devicemodel;
use App\Models\Datadevicemodel;

class Realtime extends BaseController
{
    use ResponseTrait;

    private $user;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) 
    {
        parent::initController($request, $response, $logger);
        $this->user = service("user_data");
    }

    public function index(){
        $data['user'] = $this->user->data;
        return view('realtime/index',$data);
    }

    public function log(){
        $devicemodel = new Devicemodel();
        $builder1 = $devicemodel->builder("device");
        $devices = $builder1->get()->getResultObject();

        $respon = array();
        $i=0;
        foreach($devices as $device){
            $datadevicemodel = new Datadevicemodel();
            $builder2 = $datadevicemodel->builder("vdatadevice");
            $builder2->where("id_device",$device->id_device);
            $builder2->orderBy("created_at","DESC");
            $builder2->limit(1);

            $datadevice = $builder2->get()->getRow();
            if($datadevice){
                $respon[$i] = [
                    "name" => $device->name,
                    "serial_id" => $device->serial_id,
                    "model" => $device->model,
                    "temperature" => $datadevice->temp,
                    "humidity" => $datadevice->humid,
                    "adc" => $datadevice->adc,
                    "ppm_co2" => $datadevice->ppm,
                    "last_data_time" => $datadevice->created_at
                ];
                $i++;
            }
        }
        return $this->response->setJSON($respon);
    }
}
?>