<?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'),
                    'nisn' => $this->request->getPost('nisn'),
                    'tempat' => $this->request->getPost('tempat'),
                    'tgl_lahir' => $this->request->getPost('tgl_lahir'),
                    'jurusan' => $this->request->getPost('jurusan'),
                    'nama_wali' => $this->request->getPost('nama_wali'),
                    'nohp' => $this->request->getPost('nohp'),
                    'keterangan' => $this->request->getPost('keterangan'),
                    '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'),
            'nisn' => $this->request->getPost('nisn'),
            'tempat' => $this->request->getPost('tempat'),
            'tgl_lahir' => $this->request->getPost('tgl_lahir'),
            'jurusan' => $this->request->getPost('jurusan'),
            'nama_wali' => $this->request->getPost('nama_wali'),
            'nohp' => $this->request->getPost('nohp'),
            'keterangan' => $this->request->getPost('keterangan'),
            '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());
                // Read only the "Siswa" sheet
                $sheet = $spreadsheet->getSheetByName('Siswa');

                if (!$sheet) {
                    $response['message'] = 'Sheet "Siswa" tidak ditemukan dalam file XLSX.';
                    return $this->response->setJSON($response);
                }

                $data = [];
                foreach ($sheet->getRowIterator(2) as $row) {
                    $rowData = [];
                    foreach ($row->getCellIterator() as $cell) {
                        $rowData[] = $cell->getValue();
                    }
                    $data[] = $rowData;
                }

                $insertData = [];
                $updateData = [];
                foreach ($data as $row) {
                    // Sesuaikan ini dengan model dan struktur tabel Anda
                    $nis = $row[1];
                    $existingData = $this->Siswa_model->where('nis', $nis)->first();

                    if ($existingData) {
                        // Jika NIS sudah ada, tambahkan ke array untuk update
                        $updateData[] = [
                            'id' => $existingData['id'],
                            '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],
                            'jurusan' => $row[10],
                            'keterangan' => $row[11],
                            'nohp' => $row[12],
                            'tahun_lulus' => $row[13],
                            'nama_wali' => $row[14],
                        ];
                    } else {
                        // Jika NIS belum ada, tambahkan ke array untuk insert
                        $insertData[] = [
                            'nis' => $nis,
                            '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],
                            'jurusan' => $row[10],
                            'keterangan' => $row[11],
                            'nohp' => $row[12],
                            'tahun_lulus' => $row[13],
                            'nama_wali' => $row[14],
                        ];
                    }
                }

                // Lakukan update data
                if (!empty($updateData)) {
                    $this->Siswa_model->updateBatch($updateData, 'id');
                }

                // Lakukan insert data baru
                if (!empty($insertData)) {
                    $insertedRows = $this->Siswa_model->insertBatch($insertData);
                    $response['berhasil'] = $insertedRows;
                    $response['gagal'] = count($data) - $insertedRows;
                    $response['message'] = 'Data berhasil diimpor.';
                } else {
                    $response['message'] = 'Semua data sudah ada di database.';
                }
            } 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']);
    }
}
