<?php

namespace App\Controllers\Panel\Users;

use App\Controllers\Panel\BC;
use App\Models\Panel\RoleModel;
use App\Models\Panel\User\AdministratorModel;
use CodeIgniter\API\ResponseTrait;

class Administrator extends BC
{
    use ResponseTrait;
    private $adminModel;
    public function __construct()
    {
        parent::__construct();
        $this->adminModel = new AdministratorModel();
    }
    public function index()
    {
        return view('Panel/Users/Administrator/index', ['page_title' => "Administrator"]);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $admin = $this->adminModel->getAll();
        return $this->respond(['data' => $admin]);
    }

    public function detail($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $admin = $this->adminModel->findId($id);
        return $this->respond(['data' => $admin]);
    }

    public function delete($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if ($this->adminModel->countAdmin() <= 1) {
            return $this->respond(['deleted' => false, 'message' => 'Tidak dapat menghapus administrator utama']);
        }
        $state = $this->adminModel->deleteId($id);
        return $this->respond(['deleted' => $state, 'message' => $state ? "Berhasil Menghapus" : "Gagal Menghapus"]);
    }

    public function add()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $rules['username'] = [
            "alias" => "Username",
            'rules' => 'alpha_dash|max_length[128]|is_unique[users.username]',
            'errors' => [
                'alpha_dash' => 'Karakter Tidak Valid',
                'max_length' => 'Maksimal 128 Karakter',
                'is_unique' => '"{value}" Sudah Ada'
            ]
        ];
        $rules['fullname'] = [
            "alias" => "Nama Lengkap",
            'rules' => 'string|max_length[255]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter'
            ]
        ];
        $rules['password'] = [
            "alias" => "Password",
            'rules' => 'string|min_length[4]|max_length[64]',
            'errors' => [
                'string' => 'Karakter Tidak Valid',
                'min_length' => 'Minimal 4 Karakter',
                'max_length' => 'Maksimal 64 Karakter'
            ]
        ];
        $rules['phone'] = [
            "alias" => "Nomor Handphone",
            'rules' => "integer|max_length[20]|permit_empty",
            'errors' => [
                'integer' => '{value} Nomor Tidak Valid,Pastikan Hanya Angka',
                'max_length' => '{value} Maksimal 20 Karakter',
            ]
        ];
        $rules['role'] = [
            "alias" => "Peran",
            'rules' => 'string',
            'errors' => [
                'string' => 'Karakter Tidak Valid',
            ]
        ];
        $rules['status'] = [
            "alias" => "Status",
            'rules' => 'integer|in_list[1,0]',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'in_list' => 'Status Tidak Valid',
            ]
        ];
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            $err = '';
            foreach ($errors as $key => $error) {
                $err = $err . $rules[$key]['alias'] . " : " . $error . '<br>';
            }
            return $this->fail(["csrf" => csrf_hash(), 'message' => $err]);
        }
        $user = new \App\Entities\Panel\User();
        $fullname = $this->request->getVar('fullname');
        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');
        $phone = $this->request->getVar('phone');
        $status = $this->request->getVar('status');
        $role = $this->request->getVar('role');
        $data = [
            'username' => $username,
            'fullname' => $fullname,
            'phone' => $phone,
            'status' => $status,
            'role' => [$role]
        ];
        $user->fill($data);
        $user->setPassword($password);
        $state = $this->adminModel->tambah($user);
        if (!$state) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah User']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah User']);
    }
    public function edit($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $rules['username'] = [
            "alias" => "Username",
            'rules' => "alpha_dash|max_length[128]|is_unique[users.username,id,$id]",
            'errors' => [
                'alpha_dash' => 'Karakter Tidak Valid',
                'max_length' => 'Maksimal 128 Karakter',
                'is_unique' => '"{value}" Sudah Ada'
            ]
        ];
        $rules['fullname'] = [
            "alias" => "Nama Lengkap",
            'rules' => 'string|max_length[255]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter'
            ]
        ];
        if ($this->request->getVar('password')) {
            $rules['password'] = [
                "alias" => "Password",
                'rules' => 'string|min_length[4]|max_length[64]',
                'errors' => [
                    'string' => 'Karakter Tidak Valid',
                    'min_length' => 'Minimal 4 Karakter',
                    'max_length' => 'Maksimal 64 Karakter'
                ]
            ];
        }
        $rules['phone'] = [
            "alias" => "Nomor Handphone",
            'rules' => "integer|max_length[20]|permit_empty",
            'errors' => [
                'integer' => '{value} Nomor Tidak Valid,Pastikan Hanya Angka',
                'max_length' => '{value} Maksimal 20 Karakter',
            ]
        ];
        $rules['role'] = [
            "alias" => "Peran",
            'rules' => 'string',
            'errors' => [
                'string' => 'Karakter Tidak Valid',
            ]
        ];
        $rules['status'] = [
            "alias" => "Status",
            'rules' => 'integer|in_list[1,0]',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'in_list' => 'Status Tidak Valid',
            ]
        ];
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            $err = '';
            foreach ($errors as $key => $error) {
                $err = $err . $rules[$key]['alias'] . " : " . $error . '<br>';
            }
            return $this->fail(["csrf" => csrf_hash(), 'message' => $err]);
        }
        $user = new \App\Entities\Panel\User();
        $fullname = $this->request->getVar('fullname');
        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');
        $phone = $this->request->getVar('phone');
        $status = $this->request->getVar('status');
        $role = $this->request->getVar('role');
        $data = [
            'id' => $id,
            'username' => $username,
            'fullname' => $fullname,
            'phone' => $phone,
            'status' => $status,
            'role' => [$role]
        ];
        $user->fill($data);
        $user->setPassword($password);
        $state = $this->adminModel->ubah($user);
        if (!$state) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah User']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah User']);
    }
    public function roles()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $roles = (new RoleModel())->whereIn('name', ['admin'])->findAll();
        return $this->respond(['data' => $roles, 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash(),]]);
    }
}
