<?php

namespace App\Controllers;

use App\Models\ModelUser;


class Users extends BaseController
{


    protected $modelUser; // 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();
    }


    public function index()
    {

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

        $dataUser = $this->modelUser->getAllData($userLevel, $userEmail);
        $dataBreadcumb = 'User';

        $data = [
            'Breadcumb' => $dataBreadcumb,
            'User' => $dataUser,
            // 'user_id' => session()->get('user_id') // Pastikan dikirim ke view
        ];

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


    public function getData($id)
    {
        if ($this->request->isAJAX()) {
            $model = new \App\Models\ModelUser();
            $data = $model->find($id); // Ambil data berdasarkan ID

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

    public function tambahData()
    {
        if ($this->request->isAJAX()) {
            // Ambil data dari request POST
            $firstname              = $this->request->getVar('firstname');
            $nohape                 = $this->request->getVar('nohape');
            $email                  = $this->request->getVar('email');
            $level                  = $this->request->getVar('level');
            $status                  = $this->request->getVar('status');


            // Validasi data (misalnya, pastikan semua field diisi)
            if (
                empty($firstname)
            ) {
                $msg =  ['status' => 'error', 'message' => 'Field harus diisi semua'];
                echo json_encode($msg);
                return;
            }

            // Memuat model
            $model = new ModelUser();

            // Siapkan data untuk disimpan
            $data = [
                'firstname'    => $firstname,
                'nohape'            => $nohape,
                'email'            => $email,
                'level'            => $level,
                'status'            => $status,
            ];

            // Memanggil method tambahData() dari model untuk insert data
            if ($model->tambahData($data)) {
                $msg = ['status' => 'success', 'message' => 'Data User berhasil ditambahkan'];
                echo json_encode($msg);
            } else {
                $msg = ['status' => 'error', 'message' => 'Terjadi kesalahan saat menambahkan data'];
                echo json_encode($msg);
            }
        }
    }


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

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

        if ($ModelUser->update($user_id, ['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 deleteUser()
    {
        if ($this->request->isAJAX()) {
            // Ambil data dari request
            $user_id = $this->request->getVar('user_id');

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

            // Inisialisasi model
            $model = new \App\Models\ModelUser();

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

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

            // Proses penghapusan data
            if ($model->delete($user_id)) {
                return $this->response->setJSON(['status' => 'success', 'message' => 'Data User 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 tuser_idak valid"
        ]);
    }
}
