<?php

namespace App\Controllers\Panel\Approvals\Presence;

use App\Controllers\Panel\BC;
use App\Models\Panel\Approvals\Presence\Siswa as PresenceSiswa;
use CodeIgniter\API\ResponseTrait;
use DateTime;

class Siswa extends BC
{
    use ResponseTrait;
    private $PresenceModel;
    public function __construct()
    {
        parent::__construct();
        $this->PresenceModel = new PresenceSiswa();
    }
    public function index()
    {
        return view('Panel/Approvals/Presence/Siswa/index', ['page_title' => "Persetujuan Kehadiran Siswa"]);
    }

    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $opt = [];
        if ($this->request->getGet('status')) {
            $opt['status'] = $this->request->getGet('status');
        }
        if ($this->request->getGet('presence_status')) {
            $opt['presence_status'] = $this->request->getGet('presence_status');
        }
        if ($this->request->getGet('kelas_id')) {
            $opt['kelas_id'] = $this->request->getGet('kelas_id');
        }
        if ($this->request->getGet('startDate') && $this->request->getGet('endDate')) {
            $opt['created_at'] = ['startDate' => $this->request->getGet('startDate'), 'endDate' => $this->request->getGet('endDate')];
        } elseif ($this->request->getGet('startDate') && $this->request->getGet('endDate') && $this->request->getGet('startDate') && $this->request->getGet('endDate')) {
            $opt['created_at'] = $this->request->getGet('startDate');
        } elseif ($this->request->getGet('startDate')) {
            $opt['startDate'] = $this->request->getGet('startDate');
        } elseif ($this->request->getGet('endDate')) {
            $opt['endDate'] = $this->request->getGet('endDate');
        }
        $data =  $this->PresenceModel->getAll($opt);
        return $this->respond(['data' => $data, "csrf" => ['name' => csrf_token(), 'value' => csrf_hash()]]);
    }
    public function detail($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->PresenceModel->findId($id);
        if (!$data) return $this->fail(['csrf' => csrf_hash(), 'message' => "Data Tidak Ditemukan"]);
        return $this->respond(['csrf' => csrf_hash(), 'data' => $data]);
    }
    function validateDate($date, $format = 'Y-m-d')
    {
        if (!$date) return false;
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) === $date;
    }
    public function approve($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->PresenceModel->find($id);
        if (!$data) return $this->fail(['csrf' => csrf_hash(), 'message' => "Data Tidak Ditemukan"]);
        if ($data['status'] != '1') return $this->fail(['csrf' => csrf_hash(), 'message' => "Persetujuan Sudah Diproses"]);
        $d['status'] = "2";
        $d['edited_by'] = user()->id;
        $d['approver_description'] = $this->request->getVar("approver_description");
        $db = db_connect();
        $s6 = strtotime("$data[tanggal] 06:00:00");
        $sdtm = strtotime("$data[tanggal] 00:00:00");
        $edtm = strtotime("$data[tanggal] 23:59:59");
        $japel = $db->table('jadwal_pelajaran jp')->where(['startDay' => date('w', strtotime($data['tanggal'])) + 1]);
        $japel->select("jp.id jadwal_id,ms.id siswa_id,$data[presence_status] keterangan,$s6 created_at,$s6 updated_at");
        $japel->join('m_siswa ms', 'ms.kelas_id=jp.kelas_id');
        $japel->where('ms.id', $data['siswa_id']);
        $japel = $japel->get()->getResultArray();
        $attendance = json_decode(options('attendance_siswa'), true);

        $exist = $db->table('m_siswa ms')->select("ms.id,dps.created_at,dps.timeIn,dps.timeOut");
        $exist->where('IFNULL(dps.timeIn,UNIX_TIMESTAMP()) >=', strtotime("$data[tanggal] 00:00:00"), false);
        $exist->where("IFNULL(dps.timeOut,UNIX_TIMESTAMP()) <=", strtotime("$data[tanggal] 23:59:59"), false);
        $exist->join('daily_presence_siswa dps', "dps.siswa_id=ms.id");
        $exist->where('ms.id', $data['siswa_id']);

        $exist = $exist->orderBy('dps.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']) != $data['tanggal']) $exist = null;
            else if ($exist['timeOut'] && date('Y-m-d', $exist['timeOut']) != $data['tanggal']) $exist = null;
        }
        $db->transStart();

        if ($exist['created_at'] ?? false) {
            $pd = [
                "status" => $data['presence_status'],
                'updated_at' => time(),
            ];
            if (!$exist['timeIn']) {
                if ($attendance['timeIn']) {
                    $timeIn = parseAttendanceTimeToNow($attendance['timeIn']);
                    $pd['timeIn'] = strtotime("$data[tanggal] " . date('H:i:s', strtotime($timeIn)));
                } else {
                    $pd['timeIn'] = strtotime("$data[tanggal] " . date("07:00"));
                }
            }
            if (!$exist['timeOut']) {
                if ($attendance['timeOut']) {
                    $timeOut = parseAttendanceTimeToNow($attendance['timeOut']);
                    $pd['timeOut'] = strtotime("$data[tanggal] " . date('H:i:s', strtotime($timeOut)));
                } else {
                    $pd['timeOut'] = strtotime("$data[tanggal] " . date("17:00"));
                }
            }
            $db->table('daily_presence_siswa')->update($pd, ['siswa_id' => $data['siswa_id'], "created_at" => $exist['created_at']]);
        } else {
            $pd  = [
                'siswa_id' => $data['siswa_id'],
                "status" => $data['presence_status'],
                "created_at" => strtotime("$data[tanggal] " . date("H:i:s")),
                "updated_at" => strtotime("$data[tanggal] " . date("H:i:s")),
            ];
            if ($attendance['timeIn']) {
                $timeIn = parseAttendanceTimeToNow($attendance['timeIn']);
                $pd['timeIn'] = strtotime("$data[tanggal] " . date('H:i:s', strtotime($timeIn)));
            } else {
                $pd['timeIn'] = strtotime("$data[tanggal] " . date("07:00"));
            }
            if ($attendance['timeOut']) {
                $timeOut = parseAttendanceTimeToNow($attendance['timeOut']);
                $pd['timeOut'] = strtotime("$data[tanggal] " . date('H:i:s', strtotime($timeOut)));
            } else {
                $pd['timeOut'] = strtotime("$data[tanggal] " . date("17:00"));
            }
            $db->table('daily_presence_siswa')->where('siswa_id', $data['siswa_id'])->where('created_at >=', strtotime("$data[tanggal] 00:00:00"))->where('created_at <=', strtotime("$data[tanggal] 23:59:59"))->delete();
            $db->table('daily_presence_siswa')->insert($pd);
        }
        $db->table('approvals_presence_siswa')->update($d, ['id' => $id]);
        foreach ($japel as $jp) {
            $a = $db->table('jadwal_absensi_siswa')->where(["siswa_id" => $jp['siswa_id'], 'jadwal_id' => $jp['jadwal_id']]);
            $a->where(["created_at >=" => $sdtm, 'created_at <=' => $edtm])->delete();
            $db->table('jadwal_absensi_siswa')->insert($jp);
        }
        $db->transComplete();
        if ($db->transStatus() === FALSE) return $this->fail(['csrf' => csrf_hash(), 'message' => "Gagal Menyetujui Persetujuan"]);
        $notif['url'] = base_url('panel/approval/presence?approval=' . base64_encode($id));
        $text = "Persetujuan Kehadiran Disetujui";
        $heading = "Persetujuan kehadiran dengan id \"$id\" disetujui, lihat disini";
        $notif['contents'] = [
            "en" => $text, "id" => $text,
        ];
        $notif['headings'] = [
            "en" => $heading, "id" => $heading,
        ];
        $notif['channel_for_external_user_ids'] = "push";
        $notif['include_external_user_ids'] = [md5("m$data[siswa_id]")];
        sendOneSignal($notif);
        setLog("Menyetujui persetujuan kehadiran siswa $id");
        return $this->respond(['csrf' => csrf_hash(), 'message' => "Berhasil Menyetujui Persetujuan"]);
    }
    public function decline($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->PresenceModel->find($id);
        if (!$data) return $this->fail(['csrf' => csrf_hash(), 'message' => "Data Tidak Ditemukan"]);
        if ($data['status'] != '1') return $this->fail(['csrf' => csrf_hash(), 'message' => "Persetujuan Sudah Diproses"]);
        $d['edited_by'] = user()->id;
        $d['status'] = "3";
        $d['approver_description'] = $this->request->getVar("approver_description");
        if (!$this->PresenceModel->update($id, $d)) return $this->fail(['csrf' => csrf_hash(), 'message' => "Gagal Menolak Persetujuan"]);
        $notif['url'] = base_url('panel/approval/presence?approval=' . base64_encode($id));
        $text = "Persetujuan Kehadiran Ditolak";
        $heading = "Persetujuan kehadiran dengan id \"$id\" ditolak, lihat disini";
        $notif['contents'] = [
            "en" => $text, "id" => $text,
        ];
        $notif['headings'] = [
            "en" => $heading, "id" => $heading,
        ];
        $notif['channel_for_external_user_ids'] = "push";
        $notif['include_external_user_ids'] = [md5("m$data[siswa_id]")];
        sendOneSignal($notif);
        setLog("Menolak persetujuan kehadiran siswa $id");
        return $this->respond(['csrf' => csrf_hash(), 'message' => "Berhasil Menolak Persetujuan"]);
    }
    public function imageUploader()
    {
        $app = config('app');
        $img = $this->request->getFile('file');
        $allowed_mime = ['image/png', 'image/jpg', 'image/jpeg'];
        if (!$img->isValid()) return $this->failForbidden();
        if (!in_array($img->getClientMimeType(), $allowed_mime)) $this->failForbidden();
        if ($img->hasMoved()) return $this->failNotFound();
        $imgName = $img->getRandomName();
        $precPath = "$app->imgPath/approval/presence";
        compress_image($img->getTempName(), FCPATH . "$precPath/$imgName");
        rmbfe('php', FCPATH . $precPath);
        return $this->respond(['location' => base_url("$precPath/$imgName")]);
    }
}
