<?php

namespace App\Controllers;

use App\Models\ModelUser;
use App\Models\ModelJabatan;
use App\Models\ModelUnitKerja;


class Users extends BaseController
{


    protected $modelUser; // Properti untuk model
    protected $modelJabatan; // Properti untuk model
    protected $modelUnitKerja; // Properti untuk model

    public function __construct()
    {

        // Cek apakah pengguna sudah login
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login'); // Arahkan ke halaman login jika belum login
        }
        $this->modelUser = new ModelUser();
        $this->modelJabatan = new ModelJabatan();
        $this->modelUnitKerja = new ModelUnitKerja();
    }


    public function index()
    {

        $session = session();
        $userRole = $session->get('role'); // Ambil role user dari session
        $userEmail = $session->get('email'); // Ambil email user dari session

        $dataUser = $this->modelUser->getAllData($userRole, $userEmail);
        $dataJabatan = $this->modelJabatan->getAllData();
        $dataUnitKerja = $this->modelUnitKerja->getAllData();
        $dataBreadcumb = 'User';

        $data = [
            'Breadcumb' => $dataBreadcumb,
            'jabatan' => $dataJabatan,
            'unitkerja' => $dataUnitKerja,
            'User' => $dataUser,
            'session_id_user' => session()->get('id_user') // Pastikan dikirim ke view
        ];

        return view('user/index', $data);
    }

    public function atasanUnit($id_unit)
    {
        if ($this->request->isAJAX()) {
            $listAtasan = $this->modelUser
                ->whereIn('role', ['supervisor', 'manager'])
                ->where('id_unit', $id_unit)
                ->where('status', 'aktif')
                ->orderBy('nama', 'ASC')
                ->findAll();

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

    public function simpanTTD()
    {
        if ($this->request->isAJAX()) {
            $id_user = $this->request->getPost('id_user');
            $ttd_base64 = $this->request->getPost('ttd_user');

            if (!$id_user || !$ttd_base64) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'ID user atau tanda tangan kosong.'
                ]);
            }

            // Konversi base64 ke file
            $namaFile = uniqid('ttd_') . '.png';
            $path = FCPATH . 'uploads/ttd/' . $namaFile;

            $ttd_base64 = str_replace('data:image/png;base64,', '', $ttd_base64);
            $ttd_base64 = str_replace(' ', '+', $ttd_base64);
            $decoded = base64_decode($ttd_base64);

            if (!mb_check_encoding($ttd_base64, 'UTF-8')) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Karakter tidak valid dalam base64.'
                ]);
            }

            file_put_contents($path, $decoded);

            // Pastikan array $data tidak kosong
            $data = ['ttd_user' => $namaFile];

            // Update user
            if ($this->modelUser->update($id_user, $data)) {
                return $this->response->setHeader('Content-Type', 'application/json')
                    ->setStatusCode(200)
                    ->setBody(json_encode([
                        'status' => 'success',
                        'message' => 'Tanda tangan berhasil disimpan.'
                    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Gagal menyimpan ke database.'
                ]);
            }
        }

        return redirect()->back();
    }

    public function getTTD($id)
    {
        $user = $this->modelUser->find($id);

        if ($user) {
            return $this->response->setJSON([
                'ttd_user' => $user['ttd_user'] ?? null
            ]);
        }

        return $this->response->setJSON([
            'ttd_user' => null
        ]);
    }



    public function tambahData()
    {
        if ($this->request->isAJAX()) {
            $nama               = $this->request->getVar('nama');
            $nip                = $this->request->getVar('nip');
            $id_jabatan         = $this->request->getVar('id_jabatan');
            $id_unit            = $this->request->getVar('id_unit');
            $id_atasan            = $this->request->getVar('id_atasan');
            $status_kepegawaian = $this->request->getVar('status_kepegawaian');
            $role               = $this->request->getVar('role');
            $nohape             = $this->request->getVar('nohape');
            $email              = $this->request->getVar('email');
            $status             = $this->request->getVar('status');

            $errors = [];

            if (empty($nama)) $errors[] = 'Nama';
            if (empty($nip)) $errors[] = 'NIP';
            if (empty($id_jabatan)) $errors[] = 'Jabatan';
            // if (empty($id_atasan)) $errors[] = 'Atasan';
            if (empty($id_unit)) $errors[] = 'Unit Kerja';
            if (empty($status_kepegawaian)) $errors[] = 'Status Kepegawaian';
            if (empty($role)) $errors[] = 'Role';
            if (empty($nohape)) $errors[] = 'Nomor HP';
            if (empty($email)) $errors[] = 'Email';
            if (empty($status)) $errors[] = 'Status';

            if (!empty($errors)) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Field berikut harus diisi: ' . implode(', ', $errors)
                ]);
                return;
            }

            // Cek apakah email sudah digunakan
            $cekEmail = $this->modelUser->where('email', $email)->first();
            if ($cekEmail) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Email sudah digunakan oleh pengguna lain.'
                ]);
                return;
            }

            // Data siap disimpan
            $data = [
                'nama'               => $nama,
                'nip'                => $nip,
                'id_jabatan'         => $id_jabatan,
                'id_unit'            => $id_unit,
                'id_atasan'            => $id_atasan,
                'status_kepegawaian' => $status_kepegawaian,
                'role'               => $role,
                'nohape'             => $nohape,
                'email'              => $email,
                'status'             => $status,
                'password'          => password_hash('123456', PASSWORD_DEFAULT),
                'created_at'         => date('Y-m-d H:i:s')
            ];

            if ($this->modelUser->insert($data)) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Data pengguna berhasil ditambahkan'
                ]);
            } else {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Terjadi kesalahan saat menambahkan data'
                ]);
            }
        }
    }

    public function getData($id_user)
    {
        if ($this->request->isAJAX()) {
            $data = $this->modelUser->find($id_user); // Ambil data berdasarkan ID

            if ($data) {
                echo json_encode($data); // Kirim data ke frontend
            } else {
                echo json_encode(null);
            }
        }
    }

    public function updateData()
    {
        if ($this->request->isAJAX()) {

            $id_user               = $this->request->getVar('id_user');
            $nama               = $this->request->getVar('nama');
            $nip                = $this->request->getVar('nip');
            $id_jabatan         = $this->request->getVar('id_jabatan');
            $id_unit            = $this->request->getVar('id_unit');
            $id_atasan            = $this->request->getVar('id_atasan');
            $status_kepegawaian = $this->request->getVar('status_kepegawaian');
            $role               = $this->request->getVar('role');
            $nohape             = $this->request->getVar('nohape');
            $email              = $this->request->getVar('email');
            $status             = $this->request->getVar('status');

            $errors = [];

            if (empty($nama)) $errors[] = 'Nama';
            if (empty($nip)) $errors[] = 'NIP';
            if (empty($id_jabatan)) $errors[] = 'Jabatan';
            // if (empty($id_atasan)) $errors[] = 'Atasan';
            if (empty($id_unit)) $errors[] = 'Unit Kerja';
            if (empty($status_kepegawaian)) $errors[] = 'Status Kepegawaian';
            if (empty($role)) $errors[] = 'Role';
            if (empty($nohape)) $errors[] = 'Nomor HP';
            if (empty($email)) $errors[] = 'Email';
            if (empty($status)) $errors[] = 'Status';

            if (!empty($errors)) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Field berikut harus diisi: ' . implode(', ', $errors)
                ]);
                return;
            }

            // Cek apakah email sudah digunakan
            // $cekEmail = $this->modelUser->where('email', $email)->first();
            // if ($cekEmail) {
            //     echo json_encode([
            //         'status' => 'error',
            //         'message' => 'Email sudah digunakan oleh pengguna lain, dengan nama user ' . $cekEmail['nama']
            //     ]);
            //     return;
            // }

            // Data siap disimpan
            $data = [
                'nama'               => $nama,
                'nip'                => $nip,
                'id_jabatan'         => $id_jabatan,
                'id_unit'            => $id_unit,
                'id_atasan'            => $id_atasan,
                'status_kepegawaian' => $status_kepegawaian,
                'role'               => $role,
                'nohape'             => $nohape,
                'email'              => $email,
                'status'             => $status,
                'password'          => password_hash('123456', PASSWORD_DEFAULT),
                'created_at'         => date('Y-m-d H:i:s')
            ];

            if ($this->modelUser->updateData($id_user, $data)) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Data pengguna berhasil ditambahkan'
                ]);
            } else {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Terjadi kesalahan saat menambahkan data'
                ]);
            }
        }
    }




    public function changeStatus()
    {
        $id_user = $this->request->getPost('id_user');
        $status = $this->request->getPost('status');

        $ModelUser = new \App\Models\ModelUser();

        if ($ModelUser->update($id_user, ['status' => $status])) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Status User berhasil diubah.'
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal mengubah status Produk.'
            ]);
        }
    }

    public function deleteData()
    {
        if ($this->request->isAJAX()) {
            // Ambil data dari request
            $id_user = $this->request->getVar('id_user');

            // Valid_userasi apakah id_user ada
            if (!$id_user) {
                return $this->response->setJSON(['error' => 'Terjadi kesalahan saat Hapus data']);
            }



            // Cari data berdasarkan id_user
            $UserData = $this->modelUser->find($id_user);
            if (!$UserData) {
                return $this->response->setJSON(
                    [
                        'error' => "Data User dengan id_user $id_user id_user ditemukan"
                    ]
                );
            }

            // Ambil nama untuk pesan sukses
            $nama = $UserData['nama'] ?? 'nama Diketahui';

            // Proses penghapusan data
            if ($this->modelUser->delete($id_user)) {
                return $this->response->setJSON(['status' => 'success', 'message' => "Data User $nama berhasil dihapus"]);
            } else {
                return $this->response->setJSON([
                    'error' => "Terjadi kesalahan saat menghapus data User"
                ]);
            }
        }

        // Jika bukan permintaan AJAX, tampilkan error
        return $this->response->setJSON([
            'error' => "Akses tid_userak valid"
        ]);
    }
}
