<?php

namespace App\Controllers\API\V2;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use DateInterval;
use DatePeriod;
use DateTime;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class WhatsappHook extends BaseController
{
    use ResponseTrait;
    private $device_id;
    private $from;
    private $to;
    private $message;
    private $reply;
    private $button = '';
    private $db;
    private $bln = [
        1 => "Januari",
        2 => "Februari",
        3 => "Maret",
        4 => "April",
        5 => "Mei",
        6 => "Juni",
        7 => "Juli",
        8 => "Agustus",
        9 => "September",
        10 => "Oktober",
        11 => "November",
        12 => "Desember",
    ];
    private $ps = [1 => "Hadir", 2 => "Alpa", 3 => "Sakit", 4 => "Izin"];
    public function index()
    {
        helper("AttendanceSolution");
        $this->from = $this->request->getVar('from');
        $this->to = $this->request->getVar('to');
        $this->message = $this->request->getVar('message');
        $this->db = db_connect();
        $key = $this->request->getGet('key');
        // if ($key != hash('sha256', options('sck'))) return $this->failForbidden();
        // if (!$this->db->table('users u')->join('users_roles ur', 'ur.user_id=u.id')->whereIn('ur.role_id', [1, 2])->where('u.phone', $this->from)->get()->getRowArray()) return $this->failForbidden();
        $wadevice = $this->db->table('whatsapp_device')->getWhere(['nomor' => $this->to])->getRowArray();
        if (!$wadevice) return $this->failNotFound();
        $this->device_id  = $wadevice['device_id'];
        switch (strtolower($this->message)) {
            case "info":
                // $this->button = '/presensi,/data siswa';
                $this->reply = "Berikut adalah pilihan perintah yang tersedia";
                $this->sendMessage();
                $this->reply = "/presensi";
                $this->sendMessage();
                $this->reply = "/data siswa";
                return $this->sendMessage();
                // return $this->sendButton();
            case "/mesin absen":
                $this->reply = "Berikut adalah mesin yang tersedia\n\n";
                $data = $this->db->table('attendance_solution_device')->get()->getResultArray();
                foreach ($data as $k => $v) {
                    $this->reply .= ($k + 1) . ". $v[id] - $v[nama] - " . ($v['is_active'] == '1' ? "Aktif" : "Tidak Aktif") . " - " . ($v['is_connected'] == '1' ? 'Terhubung' : "Tidak Terhubung") . "\n";
                }
                if (count($data) == 0) $this->reply .= "Tidak ada mesin";
                $this->sendMessage();
                $this->reply = "/mesin absen aktif 1 ID";
                $this->sendMessage();
                $this->reply = "/mesin absen konek ID";
                $this->sendMessage();
                $this->reply = "/mesin absen sinkron ID";
                return $this->sendMessage();
                // return $this->sendButton();
            case "/presensi":
                $this->reply = "Berikut adalah pilihan perintah rekap yang tersedia";
                $this->sendMessage();
                $this->reply = '/rekap presensi guru';
                $this->sendMessage();
                $this->reply = "/rekap presensi karyawan";
                $this->sendMessage();
                $this->reply = "/rekap presensi siswa";
                return $this->sendMessage();
                // return $this->sendButton();
            case "/data siswa":
                $dataSiswa = $this->getDataSiswa();
                $siswa = count($dataSiswa['siswa']);
                $this->reply = "= = = = = = DATA SISWA = = = = = =\n";
                $this->reply .= "Total Siswa : $siswa\n\n";
                $this->reply .= "*DATA PERTINGKAT*\n";
                foreach ($dataSiswa['tingkat'] as $k) {
                    $this->reply .= "$k[kode] : $k[jumlah]\n";
                }
                $this->reply .= "\n";
                $this->reply .= "*DATA PERJURUSAN*\n";
                foreach ($dataSiswa['jurusan'] as $k) {
                    $this->reply .= "$k[kode] : $k[jumlah]\n";
                }
                $this->reply .= "\n";
                $this->reply .= "*DATA JURUSAN PER TINGKAT*\n";
                foreach ($dataSiswa['jurusan-tingkat'] as $k) {
                    $this->reply .= "$k[kode_tingkat] - $k[kode_jurusan] : $k[jumlah]\n";
                }
                $this->reply .= "\n";
                $this->reply .= "*DATA PERKELAS*\n";
                foreach ($dataSiswa['kelas'] as $k) {
                    $this->reply .= "$k[nama] : $k[jumlah]\n";
                }
                return $this->sendMessage();
            case "/rekap presensi guru":
                $data = $this->getRekapAbsensiGuru();
                $this->reply = "Presensi Guru Pada " . date("Y-m-d") . "\n\n";
                if (count($data) > 0) {
                    $sudahPulang = [];
                    $belumPulang = [];
                    foreach ($data as $i => $d) {
                        if ($d['timeOut']) $sudahPulang[] = $d;
                        if (!$d['timeOut']) $belumPulang[] = $d;
                        $state = $this->ps[$d['status']];
                        if ($d['status'] == '1' && $d['timeIn']) $state .= " - " . date("H:i", $d['timeIn']);
                        $this->reply .= ($i + 1) . ".$d[fullname] - $state\n";
                    }
                    $this->reply .= "\n\nGuru Sudah Pulang\n\n";
                    if (count($sudahPulang) > 0) {
                        foreach ($sudahPulang as $i => $d) {
                            $timeOut = date("H:i", $d['timeOut']);
                            $this->reply .= ($i + 1) . ".$d[fullname] - $timeOut\n";
                        }
                    } else $this->reply .= "= = = = = = Belum Ada Data = = = = = =";
                    $this->reply .= "\n\nGuru Belum Pulang\n\n";
                    if (count($belumPulang) > 0) {
                        foreach ($belumPulang as $i => $d) {
                            $this->reply .= ($i + 1) . ".$d[fullname]\n";
                        }
                    } else $this->reply .= "= = = = = = Belum Ada Data = = = = = =";
                } else $this->reply .= "= = = = = = Belum Ada Data = = = = = =";
                return $this->sendMessage();
            case "/rekap presensi karyawan":
                $data = $this->getRekapAbsensiKaryawan();
                $this->reply = "Presensi Karyawan Pada " . date("Y-m-d") . "\n\n";
                foreach ($data as $i => $d) {
                    $state = $this->ps[$d['status']];
                    if ($d['status'] == '1' && $d['timeIn']) $state .= " - " . date("H:i", $d['timeIn']);
                    $this->reply .= ($i + 1) . ".$d[fullname] - $state\n";
                }
                if (count($data) == 0) $this->reply .= "= = = = = = Belum Ada Data = = = = = =";
                return $this->sendMessage();
            case "/rekap presensi siswa":
                $data = $this->getRekapAbsensiSiswa();
                $this->reply = "Presensi Siswa Pada " . date("Y-m-d") . "\n\n";
                $this->button = '/rekap presensi guru,/rekap presensi karyawan,/rekap presensi siswa';
                foreach ($data as $i => $d) {
                    $state = $this->ps[$d['status']];
                    if ($d['status'] == '1' && $d['timeIn']) $state .= " - " . date("H:i", $d['timeIn']);
                    $this->reply .= ($i + 1) . ".$d[fullname] - $state\n";
                }
                if (count($data) == 0) $this->reply .= "= = = = = = Belum Ada Data = = = = = =";
                return $this->sendMessage();
        }
        if (preg_match('/\/mesin absen aktif (0|1) (\d+)/m', $this->message, $matches)) {
            $mesin = $this->db->table('attendance_solution_device')->getWhere(['id' => $matches[2]])->getRowArray();
            // $this->button = '/mesin absen';
            if (!$mesin) {
                $this->reply = "Tidak ada mesin dengan ID \"$matches[2]\"\n\n";
                return $this->sendMessage();
            }
            $dm = [
                'is_active' => $matches[1],
                'updated_at' => time(),
            ];
            $this->db->table('attendance_solution_device')->set($dm)->where('id', $matches[2])->update();
            $text = $matches[1] == 1 ? "Aktif" : "Tidak Aktif";
            $this->reply = "Berhasil mengubah mesin absen \"$mesin[nama]\" menjadi $text";
            return $this->sendMessage();
        }
        if (preg_match('/\/mesin absen konek (\d+)/m', $this->message, $matches)) {
            $mesin = $this->db->table('attendance_solution_device')->getWhere(['id' => $matches[1]])->getRowArray();
            $this->button = '/mesin absen';
            if (!$mesin) {
                $this->reply = "Tidak ada mesin dengan ID \"$matches[1]\"\n\n";
                return $this->sendMessage();
            }
            $result = getDataAttendance($mesin['ip'], $mesin['port']);
            if ($result['status'] != 1) {
                $this->reply = "Tidak bisa terhubung dengan mesin \"$mesin[nama]\".\n\n Keterangan\n\n";
                $this->reply .= "\"$result[message]\"";
            }
            $dm = [
                'is_connected' => 1,
                'sync_at' => time(),
                'updated_at' => time(),
            ];
            $this->db->table('attendance_solution_device')->set($dm)->where('id', $mesin['id'])->update();
            $this->reply = "Berhasil terhubung dengan mesin absen \"$mesin[nama]\"";
            return $this->sendMessage();
        }
        if (preg_match('/\/mesin absen sinkron (\d+)/m', $this->message, $matches)) {
            $mesin = $this->db->table('attendance_solution_device')->getWhere(['id' => $matches[1]])->getRowArray();
            $this->button = '/mesin absen';
            if (!$mesin) {
                $this->reply = "Tidak ada mesin dengan ID \"$matches[1]\"\n\n";
                return $this->sendMessage();
            }
            $result = getDataAttendance($mesin['ip'], $mesin['port']);
            if ($result['status'] != 1) {
                $this->reply = "Tidak bisa terhubung dengan mesin \"$mesin[nama]\".\n\n Keterangan\n\n";
                $this->reply .= "\"$result[message]\"";
            }
            $this->syncAttendanceSolution($result);
            $dm = [
                'is_connected' => 1,
                'sync_at' => time(),
                'updated_at' => time(),
            ];
            $this->db->table('attendance_solution_device')->set($dm)->where('id', $mesin['id'])->update();
            $this->reply = "Berhasil sinkron dengan mesin absen \"$mesin[nama]\"";
            return $this->sendMessage();
        }
        if (preg_match('/\/mesin absen (\d+)/m', $this->message, $matches)) {
            $mesin = $this->db->table('attendance_solution_device')->getWhere(['id' => $matches[1]])->getRowArray();
            $this->button = '/mesin absen';
            if (!$mesin) {
                $this->reply = "Tidak ada mesin dengan ID \"$matches[1]\"\n\n";
                return $this->sendMessage();
            }
            $this->reply = "Detail Mesin Absensi\n\n";
            $this->reply .= "ID : $mesin[id]\n";
            $this->reply .= "Nama : $mesin[nama]\n";
            $this->reply .= "IP : $mesin[ip]\n";
            $this->reply .= "Port : $mesin[port]\n";
            $this->reply .= "CommKey : $mesin[commKey]\n";
            $this->reply .= "Terhubung : " . ($mesin['is_connected'] == '1' ? 'Ya' : "Tidak") . "\n";
            $this->reply .= "Aktif : " . ($mesin['is_active'] == '1' ? 'Ya' : "Tidak") . "\n";
            $this->reply .= "Terputus : " . ($mesin['disconnected_at'] ? date("Y-m-d H:i", $mesin['disconnected_at']) : "-") . "\n";
            $this->reply .= "Sinkron : " . ($mesin['sync_at'] ? date("Y-m-d H:i", $mesin['sync_at']) : "-") . "\n";
            return $this->sendMessage();
        }
        if (preg_match('/\/cari siswa (.*)/m', $this->message, $matches)) {
            $siswa  = null;
            $builder = $this->db->table('m_siswa ms');
            $builder->select("ms.nomor_induk,ms.phone,ms.nama,ms.alamat,ms.tempat_lahir,ms.tanggal_lahir,ms.alamat,mk.nama nama_kelas");
            $builder->join('m_kelas mk', 'mk.id=ms.kelas_id', 'left');
            if (is_numeric($matches[1])) {
                $builder->where(['ms.nomor_induk' => $matches[1]]);
                $builder = $builder->get()->getRowArray();
                if (!$builder) {
                    $this->reply = "Tidak Ada Siswa Dengan Nomor Induk '$matches[1]'";
                    return $this->sendMessage();
                }
                $siswa = $builder;
            } else if (is_string($matches[1])) {
                $builder->like('ms.nama', $matches[1]);
                $builder = $builder->get()->getResultArray();
                if (count($builder) == 0) {
                    $this->reply = "Tidak Ada Siswa Dengan Nama '$matches[1]'";
                    return $this->sendMessage();
                } else if (count($builder) == 1) {
                    $siswa = $builder[0];
                } else {
                    $this->reply = "Hasil Pencarian Siswa\n\n";
                    foreach ($builder as $i => $v) {
                        $this->reply .= ($i + 1) . ". $v[nomor_induk] - $v[nama] - $v[nama_kelas]\n";
                    }
                    return $this->sendMessage();
                }
            }
            if ($siswa) {
                $this->reply = "Nama : $siswa[nama]\n";
                $this->reply .= "Kelas : " . ($siswa['nama_kelas'] ?? 'Tidak Ada') . "\n";
                $tempat_lahir = ($siswa['tempat_lahir'] ?? 'Tidak Ada');
                $tanggal_lahir = ($siswa['tanggal_lahir'] ? date("d") . " " . $this->bln[date("n")] . " " . date('Y') : 'Tidak Ada');
                $this->reply .= "TTL : $tempat_lahir, $tanggal_lahir\n";
                $this->reply .= "Alamat : " . ($siswa['alamat'] ?? 'Tidak Ada') . "\n";
                $this->reply .= "No HP : " . ($siswa['phone'] ?? 'Tidak Ada') . "\n";
                return $this->sendMessage();
            }
        }
        return $this->failValidationErrors("Invalid Command");
    }
    private function sendButton()
    {

        $client = new Client();
        $options = [
            'multipart' => [
                [
                    'name' => 'device_id',
                    'contents' => $this->device_id
                ],
                [
                    'name' => 'number',
                    'contents' => $this->from
                ],
                [
                    'name' => 'message',
                    'contents' => $this->reply
                ],
                [
                    'name' => 'button',
                    'contents' => $this->button
                ]
            ]
        ];

        $request = new Request('POST', 'https://wa.cbtcandy.com/api/sendButton');
        $this->button = "";
        $this->reply = "";
        $res = $client->sendAsync($request, $options)->wait();
        return $this->respond(['message' => $res->getBody()->getContents()]);
    }
    private function sendMessage()
    {

        $client = new Client();
        $options = [
            'multipart' => [
                [
                    'name' => 'device_id',
                    'contents' => $this->device_id
                ],
                [
                    'name' => 'number',
                    'contents' => $this->from
                ],
                [
                    'name' => 'message',
                    'contents' => $this->reply
                ],
            ]
        ];

        $request = new Request('POST', 'https://wa.cbtcandy.com/api/send');
        $res = $client->sendAsync($request, $options)->wait();
        $this->reply = "";
        return $this->respond(['message' => "Success"]);
    }
    private function getRekapAbsensiGuru()
    {
        $sdt = strtotime(" 00:00:00");
        $edt = strtotime(" 23:59:59");
        $builder = $this->db->table("daily_presence_guru dpg");
        $builder->join('users u', 'u.id=dpg.user_id');
        $builder->where("IFNULL(dpg.timeIn,dpg.timeOut) BETWEEN $sdt AND $edt");
        $builder->having('timeIO !=', null);
        $builder->select("u.fullname,dpg.status,dpg.timeIn,dpg.timeOut,IFNULL(dpg.suhuOut,dpg.suhuIn) suhuIO,IFNULL(dpg.timeIn,dpg.timeOut) created_at,IFNULL(dpg.timeOut,dpg.timeIn) timeIO");
        $builder->orderBy('IFNULL(dpg.timeIn,dpg.timeOut)', 'DESC', false);
        return $builder->get()->getResultArray();
    }
    private function getRekapAbsensiKaryawan()
    {
        $sdt = strtotime(" 00:00:00");
        $edt = strtotime(" 23:59:59");
        $builder = $this->db->table("daily_presence_karyawan dpk");
        $builder->join('users u', 'u.id=dpk.user_id');
        $builder->where("IFNULL(dpk.timeIn,dpk.timeOut) BETWEEN $sdt AND $edt");
        $builder->having('timeIO !=', null);
        $builder->select("u.fullname,dpk.status,dpk.timeIn,dpk.timeOut,IFNULL(dpk.suhuOut,dpk.suhuIn) suhuIO,IFNULL(dpk.timeIn,dpk.timeOut) created_at,IFNULL(dpk.timeOut,dpk.timeIn) timeIO");
        $builder->orderBy('IFNULL(dpk.timeIn,dpk.timeOut)', 'DESC', false);
        return $builder->get()->getResultArray();
    }
    private function getRekapAbsensiSiswa()
    {
        $sdt = strtotime(" 00:00:00");
        $edt = strtotime(" 23:59:59");
        $builder = $this->db->table("daily_presence_siswa dps");
        $builder->join('m_siswa ms', 'ms.id=dps.siswa_id');
        $builder->where("IFNULL(dps.timeIn,dps.timeOut) BETWEEN $sdt AND $edt");
        $builder->having('timeIO !=', null);
        $builder->select("ms.nama fullname,dps.status,dps.timeIn,dps.timeOut,IFNULL(dps.suhuOut,dps.suhuIn) suhuIO,IFNULL(dps.timeIn,dps.timeOut) created_at,IFNULL(dps.timeOut,dps.timeIn) timeIO");
        $builder->orderBy('IFNULL(dps.timeIn,dps.timeOut)', 'DESC', false);
        return $builder->get()->getResultArray();
    }
    private function getDataSiswa()
    {
        $data['siswa'] = $this->db->table('m_siswa')->get()->getResultArray();
        $data['kelas'] = $this->db->table('m_kelas mk')->select('mk.*,COUNT(*) jumlah')->join('m_siswa ms', 'ms.kelas_id=mk.id')->groupBy('mk.id')->get()->getResultArray();
        $data['tingkat'] = $this->db->table('m_tingkat mt')->select('mt.kode,COUNT(*) jumlah')->join('kelas_data kd', 'kd.tingkat_id=mt.id')->join('m_siswa ms', 'ms.kelas_id=kd.kelas_id')->groupBy('mt.id')->get()->getResultArray();
        $data['jurusan'] = $this->db->table('m_jurusan mj')->select('mj.kode,COUNT(*) jumlah')->join('kelas_data kd', 'kd.jurusan_id=mj.id')->join('m_siswa ms', 'ms.kelas_id=kd.kelas_id')->groupBy('mj.id')->get()->getResultArray();
        $data['jurusan-tingkat'] = $this->db->table('m_jurusan mj')->select('mj.kode kode_jurusan,mt.kode kode_tingkat,COUNT(*) jumlah')->join('kelas_data kd', 'kd.jurusan_id=mj.id')->join('m_tingkat mt', 'mt.id=kd.tingkat_id')->join('m_siswa ms', 'ms.kelas_id=kd.kelas_id')->groupBy("CONCAT(mj.id,'-',mt.id)", false)->get()->getResultArray();
        return $data;
    }
    private function syncAttendanceSolution($result)
    {

        $device_config['sync_at'] = time();
        $device_config['updated_at'] = time();
        $device_config['is_connected'] = '1';
        $device_config['disconnected_at'] = null;
        $timeData = [];
        $begin = new DateTime(date("Y-m-d", strtotime('-40 days')));
        $end = new DateTime(date("Y-m-d 00:01"));
        if ($result['data']) {
            $interval = DateInterval::createFromDateString('next day');
            $period = new DatePeriod($begin, $interval, $end);
            foreach ($period as $k => $dt) {
                $sdt = strtotime($dt->format("Y-m-d") . " 00:00:00");
                $edt = strtotime($dt->format("Y-m-d") . " 23:59:59");
                foreach ($result['data'] as $d) {
                    if (!(strtotime($d['DateTime']) > $sdt && strtotime($d['DateTime']) < $edt)) continue;
                    $presensi = [
                        'updated_at' => time(),
                    ];
                    $uuid = $dt->format("Y-m-d-") . $d["PIN"];
                    if (!isset($timeData[$uuid])) $timeData[$uuid] = strtotime($d['DateTime']);
                    if ($timeData[$uuid] > strtotime($d['DateTime'])) $d['DateTime'] = $timeData[$uuid];
                    $siswa = $this->db->table('m_siswa ms');
                    $siswa->select('ms.id,dps.status,dps.timeIn,dps.timeOut,dps.created_at');
                    $siswa->join('daily_presence_siswa dps', "dps.siswa_id=ms.id AND IFNULL(dps.timeIn,dps.timeOut) BETWEEN $sdt AND $edt", 'left');
                    $siswa->where('ms.attendance_solution_id', $d['PIN']);
                    $siswa->groupBy('ms.id');
                    $siswa = $siswa->get()->getRowArray();
                    if ($siswa) {
                        $presensi['status'] = is_int($siswa['status']) ? $siswa['status'] : '1';
                        if (!$siswa['timeIn'] && $d['Status'] == '0') {
                            $presensi['timeIn'] = strtotime($d['DateTime']);
                            $presensi['methodIn'] = 'rf';
                        } elseif ($d['Status'] == '1') {
                            $presensi['methodOut'] = 'rf';
                            $presensi['timeOut'] = strtotime($d['DateTime']);
                        }
                        if ($siswa['created_at']) $this->db->table('daily_presence_siswa')->where('siswa_id', $siswa['id'])->where("created_at BETWEEN $sdt AND $edt")->set($presensi)->update();
                        elseif (!$siswa['timeIn'] && $d['Status'] == '0') {
                            $presensi['siswa_id'] = $siswa['id'];
                            $presensi['created_at'] = time();
                            $this->db->table('daily_presence_siswa')->insert($presensi);
                        } elseif (!$siswa['timeOut'] && $d['Status'] == '1') {
                            $presensi['siswa_id'] = $siswa['id'];
                            $presensi['created_at'] = time();
                            $this->db->table('daily_presence_siswa')->insert($presensi);
                        }
                        continue;
                    }

                    $guru = $this->db->table('users u');
                    $guru->select('u.id,u.fullname,dpg.status,dpg.timeIn,dpg.timeOut,dpg.created_at');
                    $guru->join('users_roles ur', 'ur.user_id=u.id AND ur.role_id=2');
                    $guru->join('daily_presence_guru dpg', "dpg.user_id=u.id AND IFNULL(dpg.timeIn,dpg.timeOut) BETWEEN $sdt AND $edt", 'left');
                    $guru->where('u.attendance_solution_id', $d['PIN']);
                    $guru->groupBy('u.id');
                    $guru = $guru->get()->getRowArray();
                    if ($guru) {

                        $presensi['status'] = is_int($guru['status']) ? $guru['status'] : '1';
                        if (!$guru['timeIn'] && $d['Status'] == '0') {
                            $presensi['timeIn'] = strtotime($d['DateTime']);
                            $presensi['methodIn'] = 'rf';
                        } elseif ($d['Status'] == '1') {
                            $presensi['methodOut'] = 'rf';
                            $presensi['timeOut'] = strtotime($d['DateTime']);
                        }
                        if ($guru['created_at']) $this->db->table('daily_presence_guru')->where('user_id', $guru['id'])->where("created_at BETWEEN $sdt AND $edt")->set($presensi)->update();
                        elseif (!$guru['timeIn'] && $d['Status'] == '0') {
                            $presensi['user_id'] = $guru['id'];
                            $presensi['created_at'] = time();
                            $this->db->table('daily_presence_guru')->insert($presensi);
                        } elseif (!$guru['timeOut'] && $d['Status'] == '1') {
                            $presensi['user_id'] = $guru['id'];
                            $presensi['created_at'] = time();
                            $this->db->table('daily_presence_guru')->insert($presensi);
                        }
                        continue;
                    }

                    $karyawan = $this->db->table('users u');
                    $karyawan->select('u.id,dpk.status,dpk.timeIn,dpk.timeOut,dpk.created_at');
                    $karyawan->join('users_roles ur', 'ur.user_id=u.id AND ur.role_id=6');
                    $karyawan->join('daily_presence_karyawan dpk', "dpk.user_id=u.id AND IFNULL(dpk.timeIn,dpk.timeOut) BETWEEN $sdt AND $edt", 'left');
                    $karyawan->where('u.attendance_solution_id', $d['PIN']);
                    $karyawan->groupBy('u.id');
                    $karyawan = $karyawan->get()->getRowArray();
                    if ($karyawan) {
                        $presensi['status'] = is_int($karyawan['status']) ? $karyawan['status'] : '1';
                        if (!$karyawan['timeIn'] && $d['Status'] == '0') {
                            $presensi['timeIn'] = strtotime($d['DateTime']);
                            $presensi['methodIn'] = 'rf';
                        } elseif ($d['Status'] == '1') {
                            $presensi['methodOut'] = 'rf';
                            $presensi['timeOut'] = strtotime($d['DateTime']);
                        }
                        if ($karyawan['created_at']) $this->db->table('daily_presence_karyawan')->where('user_id', $karyawan['id'])->where("created_at BETWEEN $sdt AND $edt")->set($presensi)->update();
                        elseif (!$karyawan['timeIn'] && $d['Status'] == '0') {
                            $presensi['user_id'] = $karyawan['id'];
                            $presensi['created_at'] = time();
                            $this->db->table('daily_presence_karyawan')->insert($presensi);
                        } elseif (!$karyawan['timeOut'] && $d['Status'] == '1') {
                            $presensi['user_id'] = $karyawan['id'];
                            $presensi['created_at'] = time();
                            $this->db->table('daily_presence_karyawan')->insert($presensi);
                        }
                        continue;
                    }
                }
            }
        }
        $this->db->transComplete();
    }
}
