<?php

namespace App\Controllers\Panel\Approvals\Presence;

use App\Controllers\Panel\BC;
use App\Models\Panel\Approvals\Presence\Guru as PresenceGuru;
use CodeIgniter\API\ResponseTrait;
use DateTime;

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

    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('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");
        $attendance = json_decode(options('attendance_staff'), true);

        $db = db_connect();
        $exist = $db->table('users u')->select("u.id,dpg.methodIn,dpg.methodOut,dpg.created_at,dpg.timeIn,dpg.timeOut");
        $exist->where('IFNULL(dpg.timeIn,UNIX_TIMESTAMP()) >=', strtotime("$data[tanggal] 00:00:00"), false);
        $exist->where("IFNULL(dpg.timeOut,UNIX_TIMESTAMP()) <=", strtotime("$data[tanggal] 23:59:59"), false);
        $exist->join('daily_presence_guru dpg', "dpg.user_id=u.id");
        $exist->where('u.id', $data['user_id']);
        $exist = $exist->orderBy('dpg.created_at', 'DESC')->get()->getRowArray();

        if ($exist) {
            if ($exist['timeIn'] == null && $exist['timeOut'] == null) $exist['created_at'] = null;
            else if (strlen($exist['timeOut'] ?? '') < 10 && $exist['timeOut'] != null) $exist['created_at'] = null;
            else if (strlen($exist['timeIn'] ?? '') < 10 && $exist['timeIn'] != null) $exist['created_at'] = null;
            else if ($exist['timeIn'] && date('Y-m-d', $exist['timeIn']) != $data['tanggal']) $exist['created_at'] = null;
            else if ($exist['timeOut'] && date('Y-m-d', $exist['timeOut']) != $data['tanggal']) $exist['created_at'] = 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_guru')->update($pd, ['user_id' => $data['user_id'], "created_at" => $exist['created_at']]);
        } else {
            $pd  = [
                'user_id' => $data['user_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_guru')->where('user_id', $data['user_id'])->where('created_at >=', strtotime("$data[tanggal] 00:00:00"))->where('created_at <=', strtotime("$data[tanggal] 23:59:59"))->delete();
            $db->table('daily_presence_guru')->insert($pd);
        }
        $db->table('approvals_presence_guru')->update($d, ['id' => $id]);
        $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("s$data[user_id]")];
        sendOneSignal($notif);
        setLog("Menyetujui persetujuan kehadiran guru $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("s$data[user_id]")];
        sendOneSignal($notif);
        setLog("Membatalkan persetujuan kehadiran guru $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")]);
    }
}
