<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;
use Ramsey\Uuid\Uuid;

class UserController extends BaseController
{
    protected $userModel;
    protected $validation;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->validation = \Config\Services::validation();
    }

    public function index()
    {
        $setting = $this->appSetting(); // opsional
        return view('Panel/User/user_view', [
            'setting' => $setting,
            'title'   => 'Manajemen Pengguna'
        ]);
    }

    public function getAll()
    {
        if ($this->request->isAJAX()) {
            $data = $this->userModel->findAll();
            return $this->response->setJSON(['status' => true, 'data' => $data]);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    public function create()
    {
        if ($this->request->isAJAX()) {
            $rules = [
                'username' => 'required|min_length[4]|max_length[50]|is_unique[users.username]',
                'email'    => 'required|valid_email|is_unique[users.email]',
                'full_name' => 'permit_empty|max_length[100]',
                'password' => 'required|min_length[6]',
                'roles'    => 'permit_empty',
                'is_active' => 'required|in_list[0,1]'
            ];

            if (!$this->validate($rules)) {
                return $this->response->setJSON(['status' => false, 'message' => $this->validation->getErrors()]);
            }

            $this->userModel->insert([
                'id'       => Uuid::uuid4()->toString(),
                'username' => $this->request->getPost('username'),
                'email'    => $this->request->getPost('email'),
                'full_name' => $this->request->getPost('full_name'),
                'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                'roles'    => $this->request->getPost('roles'),
                'is_active' => $this->request->getPost('is_active'),
                'created_at' => date('Y-m-d H:i:s')
            ]);

            return $this->response->setJSON(['status' => true, 'message' => 'Pengguna berhasil ditambahkan.']);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    public function update($id = null)
    {
        if ($this->request->isAJAX()) {
            $rules = [
                'username' => "required|min_length[4]|max_length[50]|is_unique[users.username,id,{$id}]",
                'email'    => "required|valid_email|is_unique[users.email,id,{$id}]",
                'full_name' => 'permit_empty|max_length[100]',
                'password' => 'permit_empty|min_length[6]',
                'roles'    => 'permit_empty',
                'is_active' => 'required|in_list[0,1]'
            ];

            if (!$this->validate($rules)) {
                return $this->response->setJSON(['status' => false, 'message' => $this->validation->getErrors()]);
            }

            $data = [
                'username' => $this->request->getPost('username'),
                'email'    => $this->request->getPost('email'),
                'full_name' => $this->request->getPost('full_name'),
                'roles'    => $this->request->getPost('roles'),
                'is_active' => $this->request->getPost('is_active'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if ($this->request->getPost('password')) {
                $data['password'] = password_hash($this->request->getPost('password'), PASSWORD_DEFAULT);
            }

            $this->userModel->update($id, $data);
            return $this->response->setJSON(['status' => true, 'message' => 'Pengguna berhasil diperbarui.']);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    public function delete($id = null)
    {
        if ($this->request->isAJAX()) {
            $this->userModel->delete($id);
            return $this->response->setJSON(['status' => true, 'message' => 'Pengguna berhasil dihapus.']);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    private function fail($message)
    {
        return $this->response->setJSON(['status' => false, 'message' => $message]);
    }
}
