<?php

namespace App\Controllers\Panel\DailyPresence;

use App\Controllers\Panel\BC;
use CodeIgniter\API\ResponseTrait;

class QR extends BC
{
    use ResponseTrait;
    public function present()
    {
        $tbl = user()->hasRole('guru') ? "daily_presence_guru" : "daily_presence_karyawan";
        if (!options('el_mode')) return $this->respond(false);
        $sdt = strtotime(" 00:00:00");
        $edt = strtotime(" 23:59:59");
        $db = db_connect();
        $libur = $db->table('jadwal_libur')->where(['is_nasional' => 1, 'tanggal' => date('Y-m-d')])->get()->getRowArray();
        if ($libur) return $this->respond(false);
        $qr = options('attendance_qr');
        if ($qr != $this->request->getVar('qrCode')) return $this->respond(false);
        $attendance = json_decode(options('attendance_staff'), true);
        $lat = $this->request->getVar('lat');
        $lon = $this->request->getVar('lon');

        $exist = $db->table($tbl)->select("timeIn,timeOut,latIn,lonIn,latOut,lonOut,status");
        $exist->where('user_id', user()->id);
        $exist->where("IFNULL(timeIn,timeOut) BETWEEN $sdt AND $edt");
        // $exist->where('IFNULL(timeIn,UNIX_TIMESTAMP()) >=', strtotime(" 00:00:00"), false);
        // $exist->where("IFNULL(timeOut,UNIX_TIMESTAMP()) <=", strtotime(" 23:59:59"), false);
        $exist = $exist->orderBy('created_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;
        }
        if ($attendance['timeIn'] && $attendance['timeOut']) {
            $timeIn = parseAttendanceTimeToNow($attendance['timeIn']);
            $timeOut = parseAttendanceTimeToNow($attendance['timeOut']);
            if (strtotime("+2 hours") < $timeIn) return $this->respond(false);
            if (!$exist) {
                $pd = [
                    'user_id' => user()->id,
                    'updated_at' => time(),
                    'created_at' => time()
                ];
                if ($timeOut > time()) {
                    $pd['timeIn'] = time();
                    $pd['latIn'] = $lat;
                    $pd['methodIn'] = 'qr';
                    $pd['lonIn'] = $lon;
                } else {
                    $pd['latOut'] = $lat;
                    $pd['lonOut'] = $lon;
                    $pd['methodOut'] = 'qr';
                    $pd['timeOut'] = time();
                }
                $db->table($tbl)->insert($pd);
            } else {
                if ($exist['status'] != 1) return $this->respond(false);
                if ($timeOut <= time() && !$exist['timeOut']) {
                    $presence = [
                        'timeOut' => time(),
                        'methodOut' => 'qr',
                        'updated_at' => time()
                    ];
                    if ($lat && !$exist['latOut']) $presence['latOut'] = $lat;
                    if ($lon && !$exist['lonOut']) $presence['lonOut'] = $lon;
                    $update = $db->table($tbl)->where(['user_id' => user()->id]);
                    $update->where("IFNULL(timeIn,timeOut) BETWEEN $sdt AND $edt");
                    $update->update($presence);
                } else if (!$exist['timeIn']) {
                    $presence = [
                        'timeIn' => time(),
                        'methodOut' => 'qr',
                    ];
                    if ($lat && !$exist['latIn']) $presence['latIn'] = $lat;
                    if ($lon && !$exist['lonIn']) $presence['lonIn'] = $lon;
                    $update = $db->table($tbl)->where(['user_id' => user()->id]);
                    $update->where("IFNULL(timeIn,timeOut) BETWEEN $sdt AND $edt");
                    $update->update($presence);
                }
            }
        } else {
            if (!$exist) {
                $db->table($tbl)->insert([
                    'user_id' => user()->id,
                    'methodIn' => 'qr',
                    'latIn' => $lat,
                    'lonIn' => $lon,
                    'timeIn' => time(),
                    'updated_at' => time(),
                    'created_at' => time()
                ]);
            } else {
                if ($exist['status'] != 1) return $this->respond(false);
                $pd = [
                    'updated_at' => time()
                ];
                if (!$exist['timeIn']) {
                    $pd['timeIn'] = time();
                    $pd['methodIn'] = 'qr';
                    $pd['latIn'] = $lat;
                    $pd['lonIn'] = $lon;
                } else {
                    $pd['methodOut'] = 'qr';
                    $pd['timeOut'] = time();
                    $pd['latOut'] = $lat;
                    $pd['lonOut'] = $lon;
                }
                $update = $db->table($tbl)->where(['user_id' => user()->id]);
                $update->where("IFNULL(timeIn,timeOut) BETWEEN $sdt AND $edt");
                $update->update($pd);
            }
        }
        if ($db->affectedRows() > 0) return $this->respond(true);
        return $this->respond(false);
    }
}
