<?php

namespace App\Controllers\Panel\App\Settings;

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

class Attendance extends BC
{
    use ResponseTrait;
    public function index()
    {
        $data['page_title'] = "Pengaturan - Presensi";
        return view('Panel/App/Settings/Attendance/index', $data);
    }
    public function config_qr()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        return $this->respond(['data' => options("attendance_qr")]);
    }
    public function generate_qr()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $qr = generateRandomString(10);
        save_options($qr, 'attendance_qr');
        setLog("Membuat QR Presensi");
        return $this->respond(['message' => "Berhasil Dibuat", 'qr' => $qr]);
    }
    public function config_map()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        return $this->respond(['data' => options("attendance_map_data")]);
    }
    public function timePresence($type)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $secret = options("PANELJWTKEY") . options("PANELCN");
        $secret = md5(base64_encode(md5($secret)));
        if ($type == 'staff') {
            $attendance_staff = json_decode(options("attendance_staff"), true);
            $data = [
                'timeIn' => $attendance_staff['timeIn'],
                'timeOut' => $attendance_staff['timeOut'],
                'endpointin' => base_url("api/presence-reminder/$secret/staff/masuk"),
                'endpointout' => base_url("api/presence-reminder/$secret/staff/keluar"),
            ];
        } else {
            $attendance_siswa = json_decode(options("attendance_siswa"), true);
            $data = [
                'timeIn' => $attendance_siswa['timeIn'],
                'timeOut' => $attendance_siswa['timeOut'],
                'endpointin' => base_url("api/presence-reminder/$secret/siswa/masuk"),
                'endpointout' => base_url("api/presence-reminder/$secret/siswa/keluar"),
            ];
        }
        return $this->respond($data);
    }
    public function saveTimePresence($type)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $rules['time'] = [
            'rules' => "integer" . ($type == 'staff' ? '|permit_empty' : ''),
            'errors' => [
                'integer' => 'Waktu Tidak Valid',
            ]
        ];
        $time = $this->request->getVar('time');
        $state = $this->request->getVar('state');
        if (!$this->validate($rules)) return $this->fail(['message' => "Waktu Tidak Valid"]);
        if ($type == 'staff') {
            $attendance = options('attendance_staff');
            $attendance = json_decode($attendance, true);
            if ($state == 'in') $attendance['timeIn'] = $time;
            else $attendance['timeOut'] = $time;
        } else {
            $attendance = options('attendance_siswa');
            $attendance = json_decode($attendance, true);
            if ($state == 'in') $attendance['timeIn'] = $time;
            else $attendance['timeOut'] = $time;
        }
        if ($attendance['timeIn'] && $attendance['timeOut']) {
            if ($state == 'in') {
                $parsed_timeout = parseAttendanceTimeToNow($attendance['timeIn']);
                if ($parsed_timeout < $time) return $this->fail(['message' => "Waktu Masuk Tidak Boleh Lebih Besar Dari Waktu Keluar"]);
                elseif (date("Y-m-d", $parsed_timeout) != date("Y-m-d", $time)) return $this->fail(['message' => "Tidak Bisa Berbeda Hari"]);
            } else {
                $parsed_timein = parseAttendanceTimeToNow($attendance['timeOut']);
                if ($parsed_timein > $time) return $this->fail(['message' => "Waktu Keluar Tidak Boleh Lebih Kecil Dari Waktu Masuk"]);
                elseif (date("Y-m-d", $parsed_timein) != date("Y-m-d", $time)) return $this->fail(['message' => "Tidak Bisa Berbeda Hari"]);
            }
        }

        if ($type == 'staff') {
            if (!save_options(json_encode($attendance), 'attendance_staff')) return $this->fail(['message' => "Gagal Menyimpan"]);
        } else {
            if (!save_options(json_encode($attendance), 'attendance_siswa')) return $this->fail(['message' => "Gagal Menyimpan"]);
        }
        setLog("Mengubah waktu presensi");

        return $this->respond(['message' => "Berhasil Menyimpan"]);
    }
    public function save_map()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = [
            'lat' => $this->request->getVar('lat'),
            'lon' => $this->request->getVar('lon'),
            'student_radius' => $this->request->getVar('student_radius'),
            'staff_radius' => $this->request->getVar('staff_radius'),
        ];
        save_options(json_encode($data), 'attendance_map_data');
        setLog("Mengubah lokasi presensi");
        return $this->respond(['message' => "Berhasil Simpan"]);
    }
}
