<?php

namespace App\Controllers;

use App\Models\Siswa_model;

use PhpOffice\PhpSpreadsheet\IOFactory;

class Siswa extends BaseController
{
    public function __construct()
    {
        $this->Siswa_model = new Siswa_model();
    }
    private $Siswa_model;
    public function index()
    {
        // $ceklogin = cekLogin();
        // if ($ceklogin) return $ceklogin;
        // $user = getUserInfo();
        $setting = $this->appSetting();
        $data = [
            // 'nama_user' => $user->nama,
            'setting' => $setting,
            'title' => 'Daftar Siswa',
        ];
        return view('Admin/Siswa/siswa-list', $data);
    }
    public function getData()
    {

        $siswa = $this->Siswa_model->get_all_siswa($this->appSetting()->tahunpelajaran);
        $data['data'] = $siswa;
        return $this->response->setJSON($data);
    }
    public function getSiswa()
    {

        $siswa = $this->Siswa_model->get_all_siswa($this->appSetting()->tahunpelajaran);
        return $this->response->setJSON($siswa);
    }
    public function getSiswaRombel($idrombel)
    {

        $siswa = $this->Siswa_model->get_all_rombel($this->appSetting()->tahunpelajaran);
        return $this->response->setJSON($siswa);
    }

    public function getRombel()
    {

        $rombel = $this->Siswa_model->get_rombel('reguler');

        return $this->response->setJSON($rombel);
    }
    public function getrombelPeminatan()
    {

        $rombel = $this->Siswa_model->get_rombel('peminatan');
        return $this->response->setJSON($rombel);
    }
    public function add()
    {
        $validationRules = [
            'nis' => 'required',
            'nama' => 'required',
            'username' => 'required',
            'password' => 'required',
            'rombel' => 'required',
        ];

        if ($this->request->isAJAX()) {
            $response = ['success' => false, 'errors' => []];
            if ($this->validate($validationRules)) {
                $response['success'] = true;

                $password = $this->request->getPost('password') ?? "";
                $data = array(
                    'nis' => $this->request->getPost('nis'),
                    'nama' => $this->request->getPost('nama'),
                    'username' => $this->request->getPost('username'),
                    'password' => password_hash($password, PASSWORD_BCRYPT),
                    'rombel' => $this->request->getPost('rombel'),
                    'nohp' => $this->request->getPost('nohp'),
                    'status' => $this->request->getPost('status'),
                );
                $insert = $this->Siswa_model->siswa_add($data);
                if ($insert) {
                    return $this->response->setJSON(['success' => true, 'message' => 'Siswa Add successfully']);
                } else {
                    return $this->response->setStatusCode(404)->setJSON(['success' => false, 'message' => 'Siswa not found']);
                }
            } else {
                $response['errors'] = $this->validator->getErrors();
            }
            return $this->response->setJSON($response);
        }
    }

    public function edit($id)
    {
        $data = $this->Siswa_model->get_by_id($id);
        return $this->response->setJSON($data);
    }


    public function update()
    {
        $data = [
            'username' => $this->request->getPost('username'),
            'nama' => $this->request->getPost('nama'),
            'nis' => $this->request->getPost('nis'),
            'status' => $this->request->getPost('status'),
            'nohp' => $this->request->getPost('nohp'),
            'rombel' => $this->request->getPost('rombel'),
        ];

        $password = $this->request->getPost('password') ?? "";
        if (!empty($password)) {
            $data['password'] = password_hash($password, PASSWORD_BCRYPT);
        }

        $exec = $this->Siswa_model->siswa_update(['id' => $this->request->getPost('id')], $data);

        if ($exec) {
            return $this->response->setJSON(['success' => true, 'message' => 'User update successfully']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Tidak ada data yang mengalami perubahan']);
        }
    }


    public function delete($id)
    {
        $user = $this->Siswa_model->find($id);

        if ($user) {
            $this->Siswa_model->delete($id);
            return $this->response->setJSON(['success' => true, 'message' => 'User deleted successfully']);
        } else {
            return $this->response->setStatusCode(404)->setJSON(['success' => false, 'message' => 'User not found']);
        }
    }

    //================IMPORT EXCEL ==========================
    public function importViaAjax()
    {
        ini_set('max_execution_time', 1000);
        $response = [];

        if ($this->request->isAJAX() && $this->request->getFile('xlsx_file') !== null) {
            $file = $this->request->getFile('xlsx_file');

            if ($file->isValid() && $file->getExtension() === 'xlsx') {
                // Load file XLSX
                $spreadsheet = IOFactory::load($file->getPathName());
                $sheet = $spreadsheet->getActiveSheet();

                $data = [];
                foreach ($sheet->getRowIterator(2) as $row) {
                    $rowData = [];
                    foreach ($row->getCellIterator() as $cell) {
                        $rowData[] = $cell->getValue();
                    }
                    $data[] = $rowData;
                }
                $berhasil = $gagal = 0;
                // Simpan data ke database
                foreach ($data as $row) {
                    // Sesuaikan ini dengan model dan struktur tabel Anda
                    $cek = $this->Siswa_model->cek_by_nis($row[1]);
                    if ($cek == 0) {

                        $datanya = [
                            'nis' => $row[1],
                            'nisn' => $row[2],
                            'nama' => trim($row[3]),
                            'jenkel' => $row[4],
                            'tempat' => $row[5],
                            'tgl_lahir' => $row[6],
                            'username' => $row[7],
                            'password' => password_hash($row[8], PASSWORD_DEFAULT),
                            'rombel' => $row[9],
                            'nohp' => $row[10],
                            'sekolah_asal' => $row[11],
                            'diterima_kelas' => $row[12],
                            'tgl_diterima' => $row[13],
                            'nama_ayah' => $row[14],
                            'nama_ibu' => $row[15],
                            'pekerjaan_ayah' => $row[16],
                            'pekerjaan_ibu' => $row[17],
                            'alamat' => $row[18],
                            'nama_wali' => $row[19],
                            'pekerjaan_wali' => $row[20],


                        ];
                        $insert = $this->Siswa_model->siswa_add($datanya);
                        if ($insert) {
                            $berhasil++;
                        } else {
                            $gagal++;
                        }
                    }
                }
                $response['berhasil'] = $berhasil;
                $response['gagal'] = $gagal;
                $response['message'] = 'Data berhasil diimpor.';
            } else {
                $response['message'] = 'File tidak valid. Mohon unggah file XLSX.';
            }
        } else {
            $response['message'] = 'Permintaan tidak valid.';
        }

        return $this->response->setJSON($response);
    }

    public function indexProfil($id)
    {
        // $ceklogin = cekLogin();
        // if ($ceklogin) return $ceklogin;
        // $user = getUserInfo();
        $setting = $this->appSetting();
        $siswa = $this->Siswa_model->get_by_id($id);
        $data = [
            // 'nama_user' => $user->nama,
            'setting' => $setting,
            'siswa' => $siswa,
            'title' => 'Profil Siswa',
        ];
        return view('Admin/Siswa/siswa-detail', $data);
    }

    public function updateprofil()
    {
        $logo = $this->request->getFile('fotoprofil');
        if ($this->request->isAJAX()) {
            $data = [
                'nama' => $this->request->getPost('nama'),
                'nis' => $this->request->getPost('nis'),
                'nisn' => $this->request->getPost('nisn'),
                'tempat' => $this->request->getPost('tempat'),
                'tgl_lahir' => $this->request->getPost('tgl_lahir'),
                'agama' => $this->request->getPost('agama'),
                'alamat' => $this->request->getPost('alamat'),
                'sekolah_asal' => $this->request->getPost('sekolah_asal'),
                'diterima_kelas' => $this->request->getPost('diterima_kelas'),
                'tgl_diterima' => $this->request->getPost('tgl_diterima'),
                'nama_ayah' => $this->request->getPost('nama_ayah'),
                'pekerjaan_ayah' => $this->request->getPost('pekerjaan_ayah'),
                'nama_ibu' => $this->request->getPost('nama_ibu'),
                'pekerjaan_ibu' => $this->request->getPost('pekerjaan_ibu'),
                'nama_wali' => $this->request->getPost('nama_wali'),
                'pekerjaan_wali' => $this->request->getPost('pekerjaan_wali'),
                'nohp' => $this->request->getPost('nohp')
            ];
            if (!empty($logo->getName())) {
                if ($logo->isValid() && ($logo->getClientMimeType() === 'image/png' || $logo->getClientMimeType() === 'image/jpeg')) {
                    $maxSize = 1 * 1024 * 1024; // Ukuran maksimum 2MB
                    if ($logo->getSize() > $maxSize) {
                        $response = ['message' => 'Ukuran file logo terlalu besar.'];
                        return $this->response->setJSON($response)->setStatusCode(400);
                    }
                    // Baca data gambar
                    $imageData = file_get_contents($logo->getTempName());
                    $tempPath = $logo->getTempName();
                    // Konversi gambar ke base64
                    $base64Image = base64_encode($imageData);

                    // Pindahkan logo ke folder uploads
                    $newFileName = "profil-" . $this->request->getPost('nis') . "." . $logo->getExtension();
                    //$logomentri->move(FCPATH . 'assets/img', $newFileName, true);
                    $path = FCPATH . 'assets/img/fotosiswa/' . $newFileName;
                    $this->compressImage($tempPath, $path, 80);
                    $imageData = file_get_contents($path);
                    $base64Image = base64_encode($imageData);
                    $data['foto'] = $newFileName;
                    $data['foto64'] = $base64Image;
                } else {
                    $response = ['message' => 'Jenis file logo tidak valid. Harap unggah file PNG atau JPEG.'];
                    return $this->response->setJSON($response)->setStatusCode(400);
                }
            }

            $exec = $this->Siswa_model->siswa_update(['id' => $this->request->getPost('id')], $data);

            if ($exec) {
                return $this->response->setJSON(['success' => true, 'message' => 'Berhasil mengubah data pengguna']);
            } else {
                return $this->response->setJSON(['success' => false, 'message' => 'Tidak ada perubahan data']);
            }
        }
    }

    private function compressImage($sourcePath, $targetPath, $quality)
    {
        $image = \Config\Services::image(); // Menginisialisasi objek Image Manipulation
        $image->withFile($sourcePath)

            ->save($targetPath, $quality); // Simpan gambar dengan kualitas kompresi yang ditentukan
    }
    //=============index===================
    public function uploadFoto()
    {
        // Mendapatkan file yang diunggah
        $file = $this->request->getFile('filefoto');

        // Menyimpan file di folder temporary pada server
        $tempPath = WRITEPATH . 'uploads/';
        $file->move($tempPath);

        // Ekstraksi file ZIP
        $zip = new \ZipArchive;
        $zip->open($tempPath . $file->getName());
        $zip->extractTo(WRITEPATH . 'uploads/extracted/');

        // Pindahkan file-file yang diekstrak ke folder assets/img/fotosiswa
        $extractedPath = WRITEPATH . 'uploads/extracted/';
        $destinationPath = FCPATH . 'assets/img/fotosiswa/';
        foreach (glob($extractedPath . '*.*') as $extractedFile) {
            rename($extractedFile, $destinationPath . basename($extractedFile));
        }

        // Menutup file ZIP
        $zip->close();

        // Menghapus file ZIP yang sudah diekstrak
        unlink($tempPath . $file->getName());

        // Mengirim respons ke client
        return $this->response->setJSON(['status' => 'success']);
    }
}
