<?php

namespace App\Controllers;

use App\Models\User_model;
use PhpOffice\PhpSpreadsheet\IOFactory;

class User extends BaseController
{
    public function __construct()
    {
        $this->User_model = new user_model();
    }
    private $User_model;
    public function index()
    {
        // $ceklogin = cekLogin();
        // if ($ceklogin) return $ceklogin;
        // $user = getUserInfo();
        $setting = $this->appSetting();
        $data = [
            // 'nama_user' => $user->nama,
            'setting' => $setting,
            'title' => 'Data User'
        ];
        return view('Admin/User/admin-list', $data);
    }
    public function getUsers()
    {
        $this->User_model = new User_model();
        $users = $this->User_model->get_all_users();
        $data['data'] = $users;
        return $this->response->setJSON($data);
    }
    public function add()
    {
        $validationRules = [
            'nama' => 'required',
            'username' => 'required',
            'password' => 'required',
        ];

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

            if ($this->validate($validationRules)) {
                $response['success'] = true;
                $this->User_model = new User_model();
                $password = $this->request->getPost('password') ?? "";
                $data = array(
                    'nama' => $this->request->getPost('nama'),
                    'nip' => $this->request->getPost('nip'),
                    'username' => $this->request->getPost('username'),
                    'password' => password_hash($password, PASSWORD_BCRYPT),
                    'role' => implode(', ', $this->request->getPost('role')),
                    'status' => $this->request->getPost('status'),
                );
                $insert = $this->User_model->user_add($data);
                if ($insert) {
                    return $this->response->setJSON(['success' => true, 'message' => 'User Add successfully']);
                } else {
                    return $this->response->setStatusCode(404)->setJSON(['success' => false, 'message' => 'User not found']);
                }
            } else {
                $response['errors'] = $this->validator->getErrors();
            }
            return $this->response->setJSON($response);
        }
    }

    public function edit($id)
    {
        $datax = $this->User_model->get_by_id($id);
        // $datax->qrcode = $this->generateQrCode($datax->nip); // Misalnya, fungsi untuk menghasilkan QR code
        return $this->response->setJSON($datax);
        //echo json_encode($data);
    }

    public function update()
    {
        $password = $this->request->getPost('password') ?? "";
        $data = [
            'nip' => $this->request->getPost('nip'),
            'username' => $this->request->getPost('username'),
            'nama' => $this->request->getPost('nama'),
            'role' => implode(', ', $this->request->getPost('role')),
            'status' => $this->request->getPost('status'),
        ];

        if ($password !== "") {
            $data['password'] = password_hash($password, PASSWORD_BCRYPT);
        }

        $exec = $this->User_model->user_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->User_model->find($id);

        if ($user) {
            $this->User_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()
    {
        $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->User_model->cek_by_nip($row[1]);
                    if ($cek == 0) {

                        $datanya = [
                            'nip' => $row[1],
                            'id_presensi' => $row[2],
                            'nama' => $row[3],
                            'username' => $row[4],
                            'password' => password_hash($row[5], PASSWORD_DEFAULT),
                            'role' => $row[6],
                            'nohp' => $row[7]
                        ];
                        $insert = $this->User_model->user_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 profilusers()
    {
        // $ceklogin = cekLogin();
        // if ($ceklogin) return $ceklogin;
        // $user = getUserInfo();
        // $setting = $this->appSetting();
        $data = [
            // 'nama_user' => $user->nama,
            // 'setting' => $setting
        ];
        return view('Admin/User/user-profil', $data);
    }
    public function updateprofil()
    {
        $password = $this->request->getPost('password') ?? "";
        if ($this->request->getPost('password') == "") {
            $data = [
                'nip' => $this->request->getPost('nip'),
                'id_presensi' => $this->request->getPost('idpresensi'),
                'username' => $this->request->getPost('username'),
                'nama' => $this->request->getPost('nama'),
                'nohp' => $this->request->getPost('nohp')

            ];
        } else {
            $password = $this->request->getPost('password') ?? "";
            $data = [
                'nip' => $this->request->getPost('nip'),
                'id_presensi' => $this->request->getPost('idpresensi'),
                'username' => $this->request->getPost('username'),
                'nama' => $this->request->getPost('nama'),
                'password' => password_hash($password, PASSWORD_BCRYPT),
                'nohp' => $this->request->getPost('nohp')
            ];
        }
        $exec = $this->User_model->user_update(['id' => $this->request->getPost('id')], $data);

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