<?php
namespace App\Controllers\Admin;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use CodeIgniter\Shield\Entities\User;
use App\Controllers\BaseController;
use App\Models\Operatormodel;
use CodeIgniter\API\ResponseTrait;
use App\Models\Usermodeloperator;

class Operator extends BaseController
{
    use ResponseTrait;

    private $user;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) 
    {
        parent::initController($request, $response, $logger);
        $this->user = service("user_data");
    }

    private function check_access(){
        $user = service("user_data");
        if($user->data->group != 'admin'){
            return false;
        }else{
            return true;
        }
    }

    public function index(){
        $data['user'] = $this->user->data;
        return view('admin/operator/index',$data);
    }

    public function ajax_dt(){
        $data_post = [
            'draw' => $this->request->getPost('draw'),
            'columns' => $this->request->getPost('columns'),
            'order' => $this->request->getPost('order'),
            'start' => $this->request->getPost('start'),
            'length' => $this->request->getPost('length'),
            'search' => $this->request->getPost('search'),
            'searchBuilder' => $this->request->getPost('searchBuilder'),
        ];
        $DataModel = new Usermodeloperator();
        return $DataModel->GetDT($data_post,"");
    }

    public function add() {
        $data['user'] = $this->user->data;
        return view('admin/operator/add',$data);
    }

    public function add_save()
    {
        $data = array();
        $data['status'] = 'success';

        $request = [
            'kode' => $this->request->getPost('kode',FILTER_SANITIZE_ADD_SLASHES),
            'nama' => $this->request->getPost('nama',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
            'created_by' => $this->user->data->id_auth,
            'updated_by' => $this->user->data->id_auth
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('kode', 'Kode', 'required|is_unique[operator.kode]');
        $validation->setRule('nama', 'Nama', 'required|is_unique[operator.nama]');
        $validation->setRule('email', 'Email', 'required|is_unique[operator.email]');
        $validation->setRule('password', 'Password', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $user_provider = auth()->getProvider();
            $user = new User([
                'username' => strtolower(str_replace(" ","_",$request['nama'])),
                'email'    => $request['email'],
                'password' => $request['password'],
            ]);
            
            if($user_provider->save($user)){
                $id_user = $user_provider->getInsertID();
                $user = $user_provider->findById($id_user);
                $user->addgroup("operator");

                $request['id_user'] = $id_user;
                $tmodel = new Usermodeloperator();
                $tmodel->insert($request, false);
                return $this->respond($data,200);
            }else{
                return $this->fail(['email' => "Email sudah digunakan!"],400,null,'input');
            }
        }
    }

    public function view($id) {
        $data['user'] = $this->user->data;
        $tmodel = new Usermodeloperator();
        $builder = $tmodel->builder();
        $data['data'] = $builder->where("id_operator",$id)->get()->getRow();
        if($data['data'] == null){
            return redirect()->to("kolektor");
        }
        return view('admin/operator/view',$data);
    }

    public function update()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $request = [
            'kode' => $this->request->getPost('kode',FILTER_SANITIZE_ADD_SLASHES),
            'nama' => $this->request->getPost('nama',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
            'updated_by' => $this->user->data->id_auth
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('kode', 'Kode', 'required|is_unique[operator.nama,operator.id_operator,'.$id.']');
        $validation->setRule('nama', 'Nama', 'required|is_unique[operator.nama,operator.id_operator,'.$id.']');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $operatormodel = new Usermodeloperator();
            $operator = $operatormodel->find($id);
            if($operator == null){
                return $this->fail(["error" => "Database Error!"],400,null,'db');
            }

            $user_provider = auth()->getProvider();
            $user = $user_provider->findById($operator->id_user);
            
            if($request['email'] != $operator->email){
                $user->setEmail($request['email']);
                if(!$user_provider->update($operator->id_user,$user)){
                    return $this->fail(['email' => "Email sudah digunakan!"],400,null,'input');
                }
            }

            if(!empty($request['password'])){
                $user->setPassword($request['password']);
                $user_provider->update($operator->id_user,$user);
            }

            $adminmodel = new Usermodeloperator();
            if ($adminmodel->update($id,$request))
            {
                return $this->respond($data,200);
            }else{
                return $this->fail(["error" => "Database Error!"],400,null,'db');
            }
        }
    }

    public function delete()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);

        $tmodel = new Usermodeloperator();
        $operator = $tmodel->find($id);
        if($operator == null){
            return $this->fail(["error" => "Database Error!"],400,null,'db');
        }

        $user_provider = auth()->getProvider();
        $user_provider->delete($operator->id_user);
        if(!$user_provider->delete($operator->id_user,true)){
            return $this->fail(['error' => "Database Error!"],400,null,'db');
        }

        if ($tmodel->delete($id,true))
        {
            return $this->respond($data,200);
        }else{
            return $this->fail(["error" => "Database Error!"],400,null,'db');
        }
    }
}
?>