<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\PegawaiModel;
use App\Models\UserModel;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Models\UserIdentityModel;


class EmployeeController extends BaseController
{

    protected $userModel;
    protected $pegawaiModel;
    protected $authModel;

    public function __construct()
    {
        $this->userModel = new userModel();
        $this->pegawaiModel = new PegawaiModel();
        $this->authModel = new UserIdentityModel();
    }

    // READ: Menampilkan daftar data
    public function index()
    {
        $data['title'] = 'Pegawai';
        $data['data'] = $this->pegawaiModel->orderBy('created_at', 'desc')->findAll();
        return view('employee/index', $data);
    }

    // CREATE: Menampilkan form tambah data dan memprosesnya
    public function create()
    {
        helper(['form']);
        $request = $this->request;

        if ($this->request->getMethod() == 'POST') {
            // Aturan validasi
            $rules = [
                'nama'         => 'required|min_length[3]|max_length[255]',
                'username'          => 'required|min_length[3]|max_length[30]|is_unique[users.username]',
                'password'          => 'required|min_length[8]|max_length[255]',
                'password_confirm'  => 'required|matches[password]',
                'role'              => 'required|in_list[admin,kasir,pemilik_toko]',
            ];

            $user = $this->pegawaiModel->orderBy('created_at', 'desc')->findAll();
            if (!$this->validate($rules)) {
                return view('customer/index', [
                    'title'      => 'Customer',
                    'data'       => $user,
                    'validation' =>  $this->validator
                ]);
            }


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

            $PegawaiModel->insert([
                'nama' => $this->request->getPost('nama'),
                'username' => $this->request->getPost('username'),
                'password'    => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                'role'   => $this->request->getPost('role')
            ]);
            $NewPegawaiId = $PegawaiModel->getInsertID();

            $image = null;
            if ($this->request->getPost('role') == 'admin') {
                $image = 'assets/img/avatar3.png';
            } elseif ($this->request->getPost('role') == 'kasir') {
                $image = 'assets/img/avatar5.png';
            } else {
                $image = 'assets/img/avatar.png';
            }

            $usersModel = new \App\Models\UserModel();

            $usersModel->insert([
                'name' => $this->request->getPost('nama'),
                'username' => $this->request->getPost('username'),
                'role'     => $this->request->getPost('role'),
                'user_id'    => $NewPegawaiId,
                'image'     =>  $image,
            ]);
            $newUserId = $usersModel->getInsertID();

            $identityModel = new UserIdentityModel();

            $identityModel->insert([
                'user_id' => $newUserId,
                'type' => 'email_password',
                'secret' => $this->request->getPost('username'),
                'secret2' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            if ($identityModel->affectedRows() > 0) {
                session()->setFlashdata('success', 'Data Pegawai Berhasil Ditambahkan');
                return redirect()->to('/employee');
            }

            session()->setFlashdata('error', 'Terjadi kesalahan, coba lagi.');
            return redirect()->to('/employee');
        }

        return view('employee/create', ['title' => 'Tambah Pegawai']);
    }

    // UPDATE: Menampilkan form edit dan memprosesnya
    public function edit($id)
    {

        helper(['form']);
        $request = $this->request;

        if ($this->request->getMethod() == 'POST') {
            // Aturan validasi
            $rules = [
                'nama'      => 'required|min_length[3]|max_length[255]',
                'username'  => 'required|min_length[3]|max_length[30]|is_unique[tabel_pegawai.username, id_pegawai, ' . $id . ']',
                'role'      => 'required|in_list[admin,kasir,pemilik_toko]',
            ];

            $user = $this->pegawaiModel->find($id);
            if (!$this->validate($rules)) {
                return view('employee/edit', [
                    'title'      => 'Edit Customer',
                    'data'       => $user,
                    'validation' =>  $this->validator
                ]);
            }

            $dataUpdate = [
                'nama' => $this->request->getPost('nama'),
                'username'    => $this->request->getPost('username'),
                'role'     => $this->request->getPost('role'),
            ];

            $dataUpdateUsername = [
                'name' => $this->request->getPost('nama'),
                'username'    => $this->request->getPost('username'),
                'role'     => $this->request->getPost('role'),
            ];

            $this->pegawaiModel->update($id, $dataUpdate);
            $this->userModel->where('user_id', $id)->where('role <>', 'customer')->update(null, $dataUpdateUsername);

            return redirect()->to('employee/edit/' . $id)->with('success', 'Edit Pegawai Berhasil');
        }

        $data['title'] = 'Edit Pegawai';
        $data['data'] = $this->pegawaiModel->find($id);
        return view('employee/edit', $data);
    }

    // DELETE: Menghapus data
    public function delete($id)
    {
        $this->userModel->where('user_id', $id)->delete();
        $this->pegawaiModel->delete($id);
        return redirect()->to('/employee')->with('success', 'Data Pegawai berhasil dihapus.');
    }

    public function username_check($str, $id)
    {
        $pegawai = $this->pegawaiModel->where('username', $str)->first();

        if ($pegawai && $pegawai['id_pegawai'] != $id) {
            $this->validator->setError('username', 'Username sudah digunakan.');
            return false;
        }
        return true;
    }
}
