<?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 Apidevice 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(){
        
    }

    private function generateToken(int $length = 5, string $alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'): string {
        // batasi panjang: minimal 1, maksimal 5
        $length = max(1, min(5, $length));

        $token = '';
        $maxIndex = strlen($alphabet) - 1;
        for ($i = 0; $i < $length; $i++) {
            $token .= $alphabet[random_int(0, $maxIndex)];
        }
        return $token;
    }

    private function trimDeviceRows(string $idDevice, int $keep = 50): int
    {
        $db = \Config\Database::connect();

        // 1) Hitung total baris untuk device ini
        $row = $db->query(
            'SELECT COUNT(*) AS c FROM data_device WHERE id_device = ?',
            [$idDevice]
        )->getRow();

        $toDelete = max(0, ((int)$row->c) - $keep);
        if ($toDelete === 0) return 0;

        // 2) Hapus yang tertua (ASC) sebanyak yang perlu dihapus
        //    Catatan: LIMIT tidak pakai binding; cast ke int untuk aman.
        $sql = 'DELETE FROM data_device
                WHERE id_device = ?
                ORDER BY created_at ASC, id_data ASC
                LIMIT ' . (int)$toDelete;

        $db->transStart();
        $db->query($sql, [$idDevice]);
        $db->transComplete();

        if (! $db->transStatus()) {
            throw new \RuntimeException('Gagal menghapus data lama.');
        }
        return $db->affectedRows(); // jumlah baris yang terhapus
    }

    public function regis(){
        // $request = [
        //     'serial_id' => $this->request->getPost('serial_id',FILTER_SANITIZE_ADD_SLASHES),
        //     'model' => $this->request->getPost('model',FILTER_SANITIZE_ADD_SLASHES)
        // ];

        $request = $this->request->getJSON(true);
        $validation = \Config\Services::validation();
        $validation->setRule('serial_id', 'Serial ID', 'required');
        $validation->setRule('model', 'Model', 'required');

        if (!$validation->run($request)) {
            $respon = [
                "s" => 0,
                "m" => "Invalid Data."
            ];
            return $this->response->setStatusCode(400)->setJSON($respon);
        }else{
            $devicemodel = new Devicemodel();
            $builder = $devicemodel->builder("device");
            $builder->where("serial_id",$request["serial_id"]);
            $builder->where("model",$request["model"]);
            $builder->where("mode","API");
            $device = $builder->get()->getRow();
            if($device == null){
                $respon = [
                    "s" => 0,
                    "m" => "Unauthorized Device."
                ];
                return $this->response->setStatusCode(400)->setJSON($respon);
            }else{
                $update = [
                    "registered" => date("Y-m-d H:i:s"),
                    "token" => $this->generateToken()
                ];

                if($devicemodel->update($device->id_device,$update)){
                    $respon = [
                        "s" => 1,
                        "t" => $update['token']
                    ];
                    return $this->response->setStatusCode(200)->setJSON($respon);
                }

            }
        }
    }

    public function logging(){
        // $request = [
        //     'serial_id' => $this->request->getPost('serial_id',FILTER_SANITIZE_ADD_SLASHES),
        //     'token' => $this->request->getPost('token',FILTER_SANITIZE_ADD_SLASHES),
        //     'temp' => $this->request->getPost('temp',FILTER_SANITIZE_ADD_SLASHES),
        //     'humid' => $this->request->getPost('humid',FILTER_SANITIZE_ADD_SLASHES),
        //     'adc' => $this->request->getPost('adc',FILTER_SANITIZE_ADD_SLASHES),
        //     'ppm' => $this->request->getPost('ppm',FILTER_SANITIZE_ADD_SLASHES)
        // ];

        $request = $this->request->getJSON(true);
        $validation = \Config\Services::validation();
        $validation->setRule('serial_id', 'Serial ID', 'required');
        $validation->setRule('token', 'Token', 'required');

        if (!$validation->run($request)) {
            $respon = [
                "s" => 0,
                "m" => "Invalid Data."
            ];
            return $this->response->setStatusCode(400)->setJSON($respon);
        }else{
            $devicemodel = new Devicemodel();
            $builder = $devicemodel->builder("device");
            $builder->where("serial_id",$request["serial_id"]);
            $builder->where("token",$request["token"]);
            $builder->where("mode","API");
            $device = $builder->get()->getRow();
            if($device == null){
                $respon = [
                    "s" => 0,
                    "m" => "Unauthorized Device."
                ];
                return $this->response->setStatusCode(400)->setJSON($respon);
            }else{
                $db = db_connect();
                
                $request['id_device'] = $device->id_device;
                $datadevicemodel = new Datadevicemodel();
                if($datadevicemodel->insert($request)){
                    $this->trimDeviceRows($device->id_device,10);

                    $update = [
                        "last_data" => date("Y-m-d H:i:s")
                    ];
                    $devicemodel->update($device->id_device,$update);
                    
                    $respon = [
                        "s" => 1
                    ];
                    return $this->response->setStatusCode(200)->setJSON($respon);
                }
            }
        }
    }
}
?>