<?php

namespace App\Controllers\API\V1;

use CodeIgniter\RESTful\ResourceController;

class PresenceRF extends ResourceController
{
    /**
     * Return an array of resource objects, themselves in array format
     *
     * @return mixed
     */
    public function index()
    {
        helper('app');
        $suhu = $this->request->getVar('suhu');
        $ba = $this->request->getHeaderLine('authorization');
        $crm = $this->request->getHeaderLine('candy-rf-machine');
        if (!$ba || !$crm) return $this->respond(['message' => "Invalid Secret1"], 403);
        $ba = explode(" ", $ba);
        if (count($ba) != 2) return $this->respond(['message' => "Invalid Secret2"], 403);
        $ba = explode(":", base64_decode($ba[1]));
        if (count($ba) != 2) return $this->respond(['message' => "Invalid Secret3"], 403);
        if ($ba[0] != $crm || $crm != options('sck')) return $this->respond(['message' => "Invalid Secret4"], 403);
        if (!options('el_mode')) return $this->respond(['message' => "E-learning Mode is Off"], 403);
        $rfid = $this->request->getVar('id');
        $db = db_connect();
        if ($db->table('jadwal_libur')->getWhere(['tanggal' => date('Y-m-d')])->getRowArray()) return $this->respond(['message' => "Hari Ini Libur", "ts" => 3], 403);
        $sql = "SELECT IFNULL(ms.nama,u.fullname) fullname ,IFNULL(ms.nomor_induk,u.nomor_induk) nomor_induk";
        $sql .= ",IFNULL(ms.id,u.id) id,(CASE WHEN ms.id IS NULL THEN 1 ELSE 2 END) utype FROM (SELECT '$rfid' as rfid) as rftb";
        $sql .= " LEFT JOIN m_siswa ms ON rftb.rfid=ms.rfid LEFT JOIN users u ON rftb.rfid=u.rfid HAVING nomor_induk IS NOT NULL";
        $registered = $db->query($sql)->getRowArray();
        if (!$registered) return $this->respond(['message' => "ID Tidak Terdaftar di sistem!"], 403);
        $utype = $registered['utype'];
        if ($utype == 1) {
            $attendance = options('attendance_staff');
            $exist = $db->table('daily_presence_guru')->select("timeIn,timeOut,status,created_at");
            $exist->where('IFNULL(timeIn,UNIX_TIMESTAMP()) >=', strtotime(" 00:00:00"), false);
            $exist->where("IFNULL(timeOut,UNIX_TIMESTAMP()) <=", strtotime(" 23:59:59"), false);
            $exist->where(['user_id' => $registered['id']]);
            $exist = $exist->orderBy('craeted_at', 'DESC')->get()->getRowArray();
        } else {
            $attendance = options('attendance_siswa');
            $exist = $db->table('daily_presence_siswa')->select("timeIn,timeOut,status,created_at");
            $exist->where('IFNULL(timeIn,UNIX_TIMESTAMP()) >=', strtotime(" 00:00:00"), false);
            $exist->where("IFNULL(timeOut,UNIX_TIMESTAMP()) <=", strtotime(" 23:59:59"), false);
            $exist->where(['siswa_id' => $registered['id']]);
            $exist = $exist->orderBy('craeted_at', 'DESC')->get()->getRowArray();
        }

        if ($exist) {
            if ($exist['timeIn'] == null && $exist['timeOut'] == null) $exist = null;
            else if (strlen($exist['timeOut'] ?? '') < 10 && $exist['timeOut'] != null) $exist = null;
            else if (strlen($exist['timeIn'] ?? '') < 10 && $exist['timeIn'] != null) $exist = null;
            else if ($exist['timeIn'] && date('Y-m-d', $exist['timeIn']) != date('Y-m-d'))     $exist = null;
            else if ($exist['timeOut'] && date('Y-m-d', $exist['timeOut']) != date('Y-m-d')) $exist = null;
        }
        $statePresence = 'in';
        $new = false;
        if ($attendance['timeIn'] && $attendance['timeOut']) {

            $timeIn = parseAttendanceTimeToNow($attendance['timeIn']);
            $timeOut = parseAttendanceTimeToNow($attendance['timeOut']);
            if (strtotime("+2 hours") < $timeIn) return $this->fail(['message' => "Presensi Belum Dimulai"]);
            if (!$exist) {
                $new = true;
                $pd = [
                    'updated_at' => time(),
                    'created_at' => time()
                ];
                if ($timeOut > time()) {
                    $statePresence = 'in';
                    $pd['timeIn'] = time();
                    $pd['methodIn'] = 'rf';
                    if ($suhu) $pd['suhuIn'] = $suhu;
                } else {
                    $statePresence = 'out';
                    $pd['methodOut'] = 'rf';
                    $pd['timeOut'] = time();
                    if ($suhu) $pd['suhuOut'] = $suhu;
                }
                if ($utype == 1) {
                    $pd['user_id'] = $registered['id'];
                    $db->table('daily_presence_guru')->insert($pd);
                } else {
                    $pd['siswa_id'] = $registered['id'];
                    $db->table('daily_presence_siswa')->insert($pd);
                }
            } else {
                if ($exist['status'] != 1 || $exist['timeIn'] && $exist['timeOut']) return $this->respond(['message' => "Tidak Perlu Mengambil Presensi"], 403);
                if ($timeOut <= time() && !$exist['timeOut']) {
                    $new = true;
                    $statePresence = 'out';
                    $presence = [
                        'timeOut' => time(),
                        'updated_at' => time(),
                        'methodOut' => 'rf'
                    ];
                    // if (!$exist['timeIn']) $presence['timeIn'] = time();
                    if ($suhu)  $presence['suhuOut'] = $suhu;
                    if ($utype == 1) {
                        $db->table('daily_presence_guru')->where(['user_id' => $registered['id'], 'created_at >=' => strtotime(" 00:00:00"), "created_at <=" => strtotime(" 23:59:59")])->update($presence);
                    } else {
                        $db->table('daily_presence_siswa')->where(['siswa_id' => $registered['id'], 'created_at >=' => strtotime(" 00:00:00"), "created_at <=" => strtotime(" 23:59:59")])->update($presence);
                    }
                } else if (!$exist['timeIn']) {
                    $statePresence = 'in';
                    $new = true;
                    $presence = [
                        'timeIn' => time(),
                        'methodIn' => 'rf',
                    ];
                    if ($suhu)  $presence['suhuIn'] = $suhu;
                    if ($utype == 1) {
                        $db->table('daily_presence_guru')->where(['user_id' => $registered['id'], 'created_at >=' => strtotime(" 00:00:00"), "created_at <=" => strtotime(" 23:59:59")])->update($presence);
                    } else {
                        $db->table('daily_presence_siswa')->where(['siswa_id' => $registered['id'], 'created_at >=' => strtotime(" 00:00:00"), "created_at <=" => strtotime(" 23:59:59")])->update($presence);
                    }
                }
            }
        }

        if ($db->affectedRows() <= 0) return $this->respond(['message' => "Gagal Memproses Presensi"], 403);
        $msg = ['message' => "Presensi berhasil dilakukan."];
        $notif['url'] = base_url($utype == 1 ? 'panel' : '') . "/daily-presence/map";
        $audience = md5(($utype == 1 ? "s" : "m") . $registered['id']);
        $text = "Presensi berhasil dilakukan";
        if ($statePresence == 'in') {
            $heading = "Presensi berhasil dilakukan pada " . date('Y-m-d H:i') . ($suhu != 0 ? ", Suhu berada pada $suhu °C" : "") . ". Selamat Datang " . $registered['fullname'];
            $msg['message'] .= " Selamat Datang!";
            $msg['time'] = time();
        } else {
            $heading = "Presensi berhasil dilakukan pada " . date('Y-m-d H:i') . ($suhu != 0 ? ", Suhu berada pada $suhu °C" : "") . ". Selamat Jalan " . $registered['fullname'];
            $msg['message'] .= " Selamat Jalan!";
            $msg['time'] = time();
        }
        $notif['contents'] = [
            "en" => $text, "id" => $text,
        ];
        $notif['headings'] = [
            "en" => $heading, "id" => $heading,
        ];
        $notif['channel_for_external_user_ids'] = "push";
        $notif['include_external_user_ids'] = [$audience];
        if ($new) sendOneSignal($notif);
        $msg['delay'] = 100;
        return $this->respond($msg, 200);
    }

    /**
     * Return the properties of a resource object
     *
     * @return mixed
     */
    public function scanner()
    {
        helper('app');
        $ba = $this->request->getHeaderLine('authorization');
        $crm = $this->request->getHeaderLine('candy-rf-machine');
        if (!$ba || !$crm) return $this->respond(['message' => "Invalid Secret"], 403);
        $ba = explode(" ", $ba);
        if (count($ba) != 2) return $this->respond(['message' => "Invalid Secret"], 403);
        $ba = explode(":", base64_decode($ba[1]));
        if (count($ba) != 2) return $this->respond(['message' => "Invalid Secret"], 403);
        if ($ba[0] != $crm || $crm != options('sck')) return $this->respond(['message' => "Invalid Secret"], 403);
        if (!options('el_mode')) return $this->respond(['message' => "E-learning Mode is Off"], 403);
        $rfid = $this->request->getVar('id');
        save_options($rfid, 'rfid_latest');
        return $this->respond(['message' => "RFID Tersimpan", 'ts' => 2], 200);
    }

    /**
     * Return the properties of a resource object
     *
     * @return mixed
     */
    public function show($id = null)
    {
        //
    }

    /**
     * Return a new resource object, with default properties
     *
     * @return mixed
     */
    public function new()
    {
        //
    }

    /**
     * Create a new resource object, from "posted" parameters
     *
     * @return mixed
     */
    public function create()
    {
        //
    }

    /**
     * Return the editable properties of a resource object
     *
     * @return mixed
     */
    public function edit($id = null)
    {
        //
    }

    /**
     * Add or update a model resource, from "posted" properties
     *
     * @return mixed
     */
    public function update($id = null)
    {
        //
    }

    /**
     * Delete the designated resource object from the model
     *
     * @return mixed
     */
    public function delete($id = null)
    {
        //
    }
}
