<?php

namespace App\Controllers\Panel\MasterData;

use App\Controllers\Panel\BC;
use App\Models\Panel\MasterData\Kelas;
use App\Models\Panel\MasterData\RuangUjian;
use App\Models\Panel\MasterData\Siswa as SiswaModel;
use CodeIgniter\API\ResponseTrait;
use ZipArchive;

class Alumni extends BC
{
    use ResponseTrait;
    private $siswaModel;
    public function __construct()
    {
        parent::__construct();
        $this->siswaModel = new SiswaModel();
    }
    public function index()
    {
        return view('Panel/MasterData/Alumni/index', ['page_title' => "Alumni"]);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $opt = [];
        $kelas = $this->request->getGet('kelas');
        if (is_numeric($kelas)) {
            $opt['kelas'] = $kelas;
        }
        $opt['is_alumni'] = '1';
        $opt['stealth'] = true;
        $opt['edit'] = true;

        $data = $this->siswaModel->getAll($opt);
        $users = [];
        foreach ($data as $k => $v) {
            $user = $v->toArray();
            $user['password_hash'] = $v->getPassword();
            $users[] = $user;
        }
        return $this->respond(['data' => $users]);
    }
    public function detail($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->siswaModel->findId($id);
        return $this->respond(['data' => $data]);
    }

    public function delete($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $state = $this->siswaModel->delete($id);
        if ($state) db_connect()->table('jadwal_diskusi')->where(['user_id' => $id, 'user_type' => 'mobile'])->delete();
        return $this->respond(['deleted' => $state, 'message' => $state ? "Berhasil Menghapus" : "Gagal Menghapus"]);
    }

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

        $rules['nomor_induk'] = [
            "alias" => "Nomor Induk",
            'rules' => "alpha_dash|max_length[128]|is_unique[m_siswa.nomor_induk]",
            'errors' => [
                'alpha_dash' => 'Karakter Tidak Valid',
                'max_length' => 'Maksimal 128 Karakter',
                'is_unique' => '"{value}" Sudah Ada'
            ]
        ];
        $rules['nama'] = [
            "alias" => "Nama",
            'rules' => 'string|max_length[255]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter'
            ]
        ];
        $rules['email'] = [
            "alias" => "Email",
            'rules' => "valid_email|max_length[255]|permit_empty|is_unique[m_siswa.email]",
            'errors' => [
                'valid_email' => '{value} Email Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter',
            ]
        ];
        $rules['phone'] = [
            "alias" => "Nomor Handphone",
            'rules' => "integer|max_length[20]|permit_empty",
            'errors' => [
                'integer' => '{value} Nomor Tidak Valid,Pastikan Hanya Angka',
                'max_length' => '{value} Maksimal 20 Karakter',
            ]
        ];
        // $rules['tanggal_lahir'] = [
        //     "alias" => "Tanggal Lahir",
        //     'rules' => "valid_date[Y-m-d]|permit_empty",
        //     'errors' => [
        //         'valid_date' => 'Tanggal Lahir tidak valid',
        //     ]
        // ];
        $rules['jenis_kelamin'] = [
            "alias" => "Jenis Kelamin",
            'rules' => 'string|in_list[L,P]',
            'errors' => [
                'string' => 'Karakter Tidak Valid',
                'in_list' => 'Jenis Kelamin Tidak Valid',
            ]
        ];
        $rules['status'] = [
            "alias" => "Status",
            'rules' => 'integer|in_list[1,0]',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'in_list' => 'Status 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]);
        }
        $rfid = $this->request->getVar('rfid');
        if ($rfid) {
            $sql = "SELECT IFNULL(ms.nama,u.fullname) fullname ,IFNULL(ms.nomor_induk,u.nomor_induk) nomor_induk";
            $sql .= ",IFNULL(ms.id,u.id) id,(CASE WHEN ms.id IS NULL THEN 1 ELSE 2 END) utype FROM (SELECT '$rfid' as rfid) as rftb";
            $sql .= " LEFT JOIN m_siswa ms ON rftb.rfid=ms.rfid LEFT JOIN users u ON rftb.rfid=u.rfid HAVING nomor_induk IS NOT NULL";
            $registered = db_connect()->query($sql)->getRowArray();
            if ($registered) {
                $msg = ["csrf" => csrf_hash(), 'message' => "RFID sudah terdaftar"];
                if ($registered['utype'] == 1) {
                    $msg['message'] .= " pada staff dengan nomor induk $registered[nomor_induk]";
                } else {
                    $msg['message'] .= " pada siswa dengan nomor induk $registered[nomor_induk]";
                }
                return $this->fail($msg);
            }
        }
        $attendance_solution_id = $this->request->getVar('attendance_solution_id');
        if ($attendance_solution_id) {
            $sql = "SELECT IFNULL(ms.nama,u.fullname) fullname ,IFNULL(ms.nomor_induk,u.nomor_induk) nomor_induk";
            $sql .= ",IFNULL(ms.id,u.id) id,(CASE WHEN ms.id IS NULL THEN 1 ELSE 2 END) utype FROM (SELECT '$attendance_solution_id' as attendance_solution_id) as rftb";
            $sql .= " LEFT JOIN m_siswa ms ON rftb.attendance_solution_id=ms.attendance_solution_id LEFT JOIN users u ON rftb.attendance_solution_id=u.attendance_solution_id HAVING nomor_induk IS NOT NULL";
            $registered = db_connect()->query($sql)->getRowArray();
            if ($registered) {
                $msg = ["csrf" => csrf_hash(), 'message' => "Solution ID sudah terdaftar"];
                if ($registered['utype'] == 1) {
                    $msg['message'] .= " pada staff dengan nomor induk $registered[nomor_induk]";
                } else {
                    $msg['message'] .= " pada siswa dengan nomor induk $registered[nomor_induk]";
                }
                return $this->fail($msg);
            }
        }
        $kelas_id = $this->request->getVar('kelas_id');
        $password = $this->request->getVar('password');
        $ruang_id = $this->request->getVar('ruang_id');
        $data = [
            'nomor_induk' => $this->request->getVar('nomor_induk'),
            'nama' => $this->request->getVar('nama'),
            'email' => $this->request->getVar('email'),
            'phone' => $this->request->getVar('phone'),
            'jenis_kelamin' => $this->request->getVar('jenis_kelamin'),
            'tempat_lahir' => $this->request->getVar('tempat_lahir'),
            'tanggal_lahir' => $this->request->getVar('tanggal_lahir'),
            'alamat' => $this->request->getVar('alamat'),
            'rfid' => $rfid,
            'attendance_solution_id' => $attendance_solution_id,
            'status' => $this->request->getVar('status'),
            'updated_at' => time(),
            'created_at' => time(),
        ];
        if ($ruang_id) $data['ruang_id'] = $ruang_id;
        if ($kelas_id) $data['kelas_id'] = $kelas_id;
        $user = new \App\Entities\Mobile\User();
        $user->fill($data);
        if ($password) $user->setPassword($password);
        $id = $this->siswaModel->tambah($user);
        if (!$id) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah Siswa']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah Siswa']);
    }
    public function edit($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $rules['nomor_induk'] = [
            "alias" => "Nomor Induk",
            'rules' => "alpha_dash|max_length[128]|is_unique[m_siswa.nomor_induk,id,$id]",
            'errors' => [
                'alpha_dash' => 'Karakter Tidak Valid',
                'max_length' => 'Maksimal 128 Karakter',
                'is_unique' => '"{value}" Sudah Ada'
            ]
        ];
        $rules['nama'] = [
            "alias" => "Nama",
            'rules' => 'string|max_length[255]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter'
            ]
        ];
        $rules['email'] = [
            "alias" => "Email",
            'rules' => "valid_email|max_length[255]|permit_empty|is_unique[m_siswa.email,id,$id]",
            'errors' => [
                'valid_email' => '{value} Email Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter',
                'is_unique' => '"{value}" Sudah Ada'
            ]
        ];

        $rules['phone'] = [
            "alias" => "Nomor Handphone",
            'rules' => "integer|max_length[20]|permit_empty",
            'errors' => [
                'integer' => '{value} Nomor Tidak Valid,Pastikan Hanya Angka',
                'max_length' => '{value} Maksimal 20 Karakter',
                'is_unique' => '"{value}" Sudah Ada'
            ]
        ];
        $rules['status'] = [
            "alias" => "Status",
            'rules' => 'integer|in_list[1,0]',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'in_list' => 'Status Tidak Valid',
            ]
        ];
        $rules['jenis_kelamin'] = [
            "alias" => "Jenis Kelamin",
            'rules' => 'string|in_list[L,P]',
            'errors' => [
                'string' => 'Karakter Tidak Valid',
                'in_list' => 'Jenis Kelamin 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]);
        }
        $rfid = $this->request->getVar('rfid');
        if ($rfid) {
            $sql = "SELECT IFNULL(ms.nama,u.fullname) fullname ,IFNULL(ms.nomor_induk,u.nomor_induk) nomor_induk";
            $sql .= ",IFNULL(ms.id,u.id) id,(CASE WHEN ms.id IS NULL THEN 1 ELSE 2 END) utype FROM (SELECT '$rfid' as rfid) as rftb";
            $sql .= " LEFT JOIN m_siswa ms ON rftb.rfid=ms.rfid LEFT JOIN users u ON rftb.rfid=u.rfid HAVING nomor_induk IS NOT NULL";
            $registered = db_connect()->query($sql)->getRowArray();
            if ($registered) {
                if ($registered['id'] != $id) {
                    $msg = ["csrf" => csrf_hash(), 'message' => "RFID sudah terdaftar"];
                    if ($registered['utype'] == 1) {
                        $msg['message'] .= " pada staff dengan nomor induk $registered[nomor_induk]";
                    } else {
                        $msg['message'] .= " pada siswa dengan nomor induk $registered[nomor_induk]";
                    }
                    return $this->fail($msg);
                }
            }
        }
        $attendance_solution_id = $this->request->getVar('attendance_solution_id');
        if ($attendance_solution_id) {
            $sql = "SELECT IFNULL(ms.nama,u.fullname) fullname ,IFNULL(ms.nomor_induk,u.nomor_induk) nomor_induk";
            $sql .= ",IFNULL(ms.id,u.id) id,(CASE WHEN ms.id IS NULL THEN 1 ELSE 2 END) utype FROM (SELECT '$attendance_solution_id' as attendance_solution_id) as rftb";
            $sql .= " LEFT JOIN m_siswa ms ON rftb.attendance_solution_id=ms.attendance_solution_id LEFT JOIN users u ON rftb.attendance_solution_id=u.attendance_solution_id HAVING nomor_induk IS NOT NULL";
            $registered = db_connect()->query($sql)->getRowArray();
            if ($registered) {
                if ($registered['id'] != $id) {
                    $msg = ["csrf" => csrf_hash(), 'message' => "Solution ID sudah terdaftar"];
                    if ($registered['utype'] == 1) {
                        $msg['message'] .= " pada staff dengan nomor induk $registered[nomor_induk]";
                    } else {
                        $msg['message'] .= " pada siswa dengan nomor induk $registered[nomor_induk]";
                    }
                    return $this->fail($msg);
                }
            }
        }
        $kelas_id = $this->request->getVar('kelas_id');
        $ruang_id = $this->request->getVar('ruang_id');
        $password = $this->request->getVar('password');
        $data = [
            "id" => $id,
            'nomor_induk' => $this->request->getVar('nomor_induk'),
            'nama' => $this->request->getVar('nama'),
            'email' => $this->request->getVar('email'),
            'phone' => $this->request->getVar('phone'),
            'rfid' => $rfid,
            'jenis_kelamin' => $this->request->getVar('jenis_kelamin'),
            'tempat_lahir' => $this->request->getVar('tempat_lahir'),
            'tanggal_lahir' => $this->request->getVar('tanggal_lahir'),
            'alamat' => $this->request->getVar('alamat'),
            'attendance_solution_id' => $attendance_solution_id,
            'status' => $this->request->getVar('status'),
            'updated_at' => time(),
        ];
        if ($kelas_id) $data['kelas_id'] = $kelas_id;
        if ($ruang_id) $data['ruang_id'] = $ruang_id;
        $user = new \App\Entities\Mobile\User();
        $user->fill($data);
        if ($password) $user->setPassword($password);
        $state = $this->siswaModel->ubah($data);
        if (!$state) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah Siswa']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah Siswa']);
    }

    public function kelas()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $kelas = (new Kelas())->getAll();
        return $this->respond(['data' => $kelas, 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash(),]]);
    }
    public function detail_kelas($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $kelas = (new Kelas())->findId($id);
        return $this->respond(['data' => $kelas, 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash(),]]);
    }
    public function siswa_kelas($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if ($id == 0) {
            $id = null;
            $kelas = [
                "id" => 0,
                "nama" => "Siswa Belum Mempunyai Kelas",
                "kode" => null,
                "tingkat_id" => null,
                "kode_tingkat" => null,
                "jurusan_id" => null,
                "kode_jurusan" => null,
                "kode_ruang" => null,
                "nama_jurusan" => null
            ];
        } else {
            $kelas =  (new Kelas())->findId($id);
        }
        $siswa = $this->siswaModel->getSiswaByKelas($id);
        $data['kelas'] = $kelas;
        $data['siswa'] =  $siswa;
        return $this->respond(['data' => $data, 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash(),]]);
    }
    public function siswa_ruang($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if ($id == 0) {
            $id = null;
            $ruang = [
                "id" => 0,
                "nama" => "Siswa Belum Mempunyai Ruang",
                "kode" => null,
            ];
        } else {
            $ruang =  (new RuangUjian())->find($id);
        }
        $siswa = $this->siswaModel->getSiswaByRuang($id);
        $data['ruang'] = $ruang;
        $data['siswa'] =  $siswa;
        return $this->respond(['data' => $data, 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash(),]]);
    }
    public function ruang_pindah()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = (array) $this->request->getVar('siswa');
        $siswa = [];
        foreach ($data as $s) {
            $user = new \App\Entities\Mobile\User();
            $user->id = $s->id;
            $user->ruang_id = $s->ruang_id;
            $siswa[] = $user;
        }
        $state = $this->siswaModel->ruang_pindah($siswa);
        if (!$state) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah Ruang']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah Ruang']);
    }
    public function kelas_pindah()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = (array) $this->request->getVar('siswa');
        $siswa = [];
        foreach ($data as $s) {
            $user = new \App\Entities\Mobile\User();
            $user->id = $s->id;
            $user->kelas_id = $s->kelas_id;
            $siswa[] = $user;
        }
        $state = $this->siswaModel->kelas_pindah($siswa);
        if (!$state) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah Kelas']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah Kelas']);
    }
    public function rfid()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $rfid = options('rfid_latest');
        save_options('', 'rfid_latest');
        return $this->respond(["csrf" => csrf_hash(), 'rfid' => $rfid]);
    }
    public function examplePhoto()
    {
        return $this->response->download($this->fileLocation['photo-siswa.zip'], null);
    }
    public function uploadPhoto()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        helper('Panel/utils');
        $allowedFile = [
            'zip', 'application/octet-stream', 'application/zip', 'application/x-zip', 'application/x-zip-compressed'
        ];
        $file = $this->request->getFile('file');
        if (!$file) return $this->fail("Berkas tidak valid");
        if (!$file->isValid()) return $this->fail("Berkas tidak valid");
        if ($file->hasMoved()) return $this->fail("File tidak ditemukan");
        if (!in_array($file->getMimeType(), $allowedFile)) return $this->fail("Format tidak diizinkan");
        $filePath = $file->getRealPath();
        $folderPath = WRITEPATH . "uploads/dump/photo/" . time();
        if (!file_exists($folderPath)) mkdir($folderPath, 0777, true);
        $za = new ZipArchive();
        $za->open($filePath);
        $za->extractTo($folderPath);
        $za->close();
        $photos = [];
        foreach (scandir($folderPath) as $k => $v) {
            if (in_array($v, ['.', '..'])) continue;
            $name = explode('-', $v);
            $photos[] = [
                'nomor_induk' => trim($name[0]),
                'photo' => $v,
                'updated_at' => time(),
            ];
        }
        if (count($photos) == 0) return $this->fail("Tidak Ada Photo");
        recurse_copy($folderPath, FCPATH . "assets/img/users");
        db_connect()->table('m_siswa')->updateBatch($photos, 'nomor_induk');
        return $this->respond(['message' => "Berhasil mengganti photo"]);
    }
    public function changeData()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $allowedFile = [
            'application/vnd.ms-excel',
            'application/csv',
            'text/plain',
            'text/csv',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ];
        $file = $this->request->getFile('file');
        if (!$file) return $this->fail("Berkas tidak valid");
        if (!$file->isValid()) return $this->fail("Berkas tidak valid");
        if ($file->hasMoved()) return $this->fail("File tidak ditemukan");
        if (!in_array($file->getMimeType(), $allowedFile)) return $this->fail("Format tidak diizinkan");
        $filePath = $file->getRealPath();
        $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($filePath);
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
        $spreadsheet = $reader->load($filePath);
        $query = "";
        $binding = [];
        $data = $spreadsheet->getActiveSheet()->toArray();
        if (count($data) < 2) return $this->fail("Data tidak boleh kosong");
        helper('Mobile/auth');
        $siswa = [];
        foreach ($data as $k => $v) {
            if ($k == 0) continue;
            $input  = false;
            $nis = $v[1];
            $jenis_kelamin = $v[4];
            $tempat_lahir = $v[5];
            $tanggal_lahir = $v[6];
            $alamat = $v[7];
            $set = [];
            $s = [
                'nomor_induk' => $nis,
            ];
            if ($v[8]) {
                $input = true;
                $s['password_hash'] = setMPassword($v[8]);
                // $set[] = "`password_hash` = BINARY ?";
                // $binding[] = hex2bin(bin2hex(setMPassword($v[8])));
            }
            if (in_array($jenis_kelamin, ["L", "P"])) {
                $s['jenis_kelamin'] = $jenis_kelamin;
                $input = true;
                // $set[] = "`jenis_kelamin` = ?";
                // $binding[] = $jenis_kelamin;
            }
            if ($tempat_lahir) {
                $s['tempat_lahir'] = $tempat_lahir;
                $input = true;
                // $set[] = "`tempat_lahir` = ?";
                // $binding[] = $tempat_lahir;
            }
            if ($tanggal_lahir) {
                $s['tanggal_lahir'] = date("Y-m-d", strtotime($tanggal_lahir));
                $input = true;
                // $set[] = "`tanggal_lahir` = ?";
                // $binding[] = date("Y-m-d", strtotime($tanggal_lahir));
            }
            if ($alamat) {
                $s['alamat'] = $alamat;
                $input = true;
                // $set[] = "`alamat` = ?";
                // $binding[] = $alamat;
            }
            if (!$input) continue;
            $siswa[] = $s;
            // $query .= "UPDATE `m_siswa` SET ";
            // $query .=  implode(",", $set) . " WHERE `m_siswa`.`nomor_induk` = ?;";
            // $binding[] = $nis;
        }
        if (count($siswa) == 0) return $this->fail("Tidak ada data yang diubah");
        // db_connect()->query($query, $binding);
        db_connect()->table('m_siswa')->updateBatch($siswa, 'nomor_induk');
        return $this->respond(['message' => "Berhasil mengubah data"]);
    }
}
