<?php

namespace App\Controllers\Mobile\Approvals;

use App\Controllers\Mobile\BC;
use App\Models\Mobile\Approvals\Presence as ApprovalPresence;
use CodeIgniter\API\ResponseTrait;

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

    public function all()
    {
        $opt = [];
        if ($this->request->getGet('status')) {
            $opt['status'] = $this->request->getGet('status');
        }
        $opt['siswa_id'] = user()->id;
        $data =    $this->PresenceModel->getAll($opt);
        return $this->respond(['data' => $data, "csrf" => ['name' => csrf_token(), 'value' => csrf_hash()]]);
    }

    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")]);
    }


    public function add()
    {

        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $rules['tanggal'] = [
            "alias" => "Tanggal",
            'rules' => "valid_date[Y-m-d]",
            'errors' => [
                'valid_date' => "{value} Tidak Valid"
            ]
        ];
        $rules['presence_status'] = [
            "alias" => "Kehadiran",
            'rules' => "in_list[1,2,3,4]",
            'errors' => [
                'in_list' => '{value} Pilihan Tidak Valid'
            ]
        ];
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            $err = '';
            foreach ($errors as $key => $error) {
                $err = $err . $rules[$key]['alias'] . " : " . $error . '<br>';
            }
            return $this->fail(["csrf" => csrf_hash(), 'message' => $err]);
        }

        $data = [
            "tanggal" => $this->request->getVar('tanggal'),
            "approval_description" => $this->request->getVar('approval_description'),
            "presence_status" => $this->request->getVar('presence_status'),
            "siswa_id" => user()->id,
            "status" => "1",
        ];
        $db = db_connect();
        $pending = $db->table('approvals_presence_siswa')->getWhere(['tanggal' => $this->request->getVar('tanggal'), 'siswa_id' => user()->id, 'status' => '1'])->getRowArray();
        if ($pending) return $this->fail(['message' => 'Gagal, Ada persetujuan yang sedang menungggu']);
        $id = $this->PresenceModel->insert($data);
        if (!$id) return $this->fail(['csrf' => csrf_hash(), 'message' => "Gagal Membuat Persetujuan"]);
        $notif['url'] = base_url('panel/approvals/presence/siswa?approval=' . base64_encode($id));
        $audience = $db->table('users u')->select("GROUP_CONCAT(MD5(CONCAT('s',u.id))) uid")->join('users_roles ur', 'ur.user_id=u.id')->whereIn('ur.role_id', [1, 4])->get()->getRowArray();
        if ($audience) {
            $text = "Persetujuan Baru Telah Ditambahkan";
            $heading = user()->nama . " " . user()->nomor_induk;
            if (user()->nama_kelas) {
                $heading .= " kelas " . user()->nama_kelas;
            }
            if (user()->nama_jurusan) {
                $heading .= " jurusan " . user()->nama_jurusan;
            }
            $heading .= " mengajukan sebuah persetujuan kehadiran, segera 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'] = explode(',', $audience['uid']);
            sendOneSignal($notif);
        }
        return $this->respond(['csrf' => csrf_hash(), 'message' => "Berhasil Membuat Persetujuan"]);
    }
    public function cancel($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['siswa_id'] != user()->id) return $this->fail(['csrf' => csrf_hash(), 'message' => "Data Tidak Ditemukan"]);
        if ($data['status'] != '1') return $this->fail(['csrf' => csrf_hash(), 'message' => "Persetujuan Sudah Diproses"]);
        if (!$this->PresenceModel->delete($id)) return $this->fail(['csrf' => csrf_hash(), 'message' => "Persetujuan Gagal Dibatalkan"]);
        return $this->respond(['csrf' => csrf_hash(), 'message' => "Berhasil Membatalkan Persetujuan"]);
    }
    public function detail($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->PresenceModel->findId($id, ['siswa_id' => user()->id]);
        if (!$data) return $this->fail(['csrf' => csrf_hash(), 'message' => "Data Tidak Ditemukan"]);
        return $this->respond(['csrf' => csrf_hash(), 'data' => $data]);
    }
}
