<?php
namespace App\Controllers\Admin;

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

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use App\Models\Devicemodel;

class Device 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");
    }

    public function index(){
        $data['user'] = $this->user->data;
        return view('admin/device/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 Devicemodel();
        return $DataModel->GetDT($data_post,"");
    }

    public function add() {
        $data['user'] = $this->user->data;

        return view('admin/device/add',$data);
    }

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

        $request = [
            'name' => $this->request->getPost('name',FILTER_SANITIZE_ADD_SLASHES),
            'serial_id' => $this->request->getPost('serial_id',FILTER_SANITIZE_ADD_SLASHES),
            'model' => $this->request->getPost('model',FILTER_SANITIZE_ADD_SLASHES),
            'mode' => $this->request->getPost('mode',FILTER_SANITIZE_ADD_SLASHES)
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('name', 'Name', 'required');
        $validation->setRule('serial_id', 'Serial ID', 'required|is_unique[device.serial_id]');
        $validation->setRule('model', 'Model', 'required');
        $validation->setRule('mode', 'Mode', 'required');

        if (!$validation->run($request)) {
            return $this->fail(["error" => $validation->getErrors()] ,400,null,'input');
        }else{
            try{
                $tmodel = new Devicemodel();
                $tmodel->db->transBegin();
                $id = $tmodel->insert($request);
                if($tmodel->db->transStatus() === false){
                    $tmodel->db->transRollback();
                    return $this->fail($tmodel->errors(),400,null,'db');
                }else{
                    $tmodel->db->transCommit();
                    return $this->respond($data,200);
                }
            }catch (\Exception $e) {
                return $this->fail(["error" => $e->getMessage()],400,null,'system');
            }
        }
    }

    public function view($id) {
        $data['user'] = $this->user->data;
        $tmodel = new Devicemodel();
        
        $builder = $tmodel->builder("device");
        $data['data'] = $builder->where("id_device",$id)->get()->getRow();

        return view('admin/device/view',$data);
    }

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

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $request = [
            'name' => $this->request->getPost('name',FILTER_SANITIZE_ADD_SLASHES),
            'serial_id' => $this->request->getPost('serial_id',FILTER_SANITIZE_ADD_SLASHES),
            'model' => $this->request->getPost('model',FILTER_SANITIZE_ADD_SLASHES),
            'mode' => $this->request->getPost('mode',FILTER_SANITIZE_ADD_SLASHES)
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('name', 'Name', 'required');
        $validation->setRule('serial_id', 'Serial ID', "required|is_unique[device.serial_id,device.id_device,$id]");
        $validation->setRule('model', 'Model', 'required');
        $validation->setRule('mode', 'Mode', 'required');

        if (!$validation->run($request)) {
            return $this->fail(["error"=>$validation->getErrors()],400,null,'input');
        }else{
            try{
                $tmodel = new Devicemodel();

                if ($tmodel->update($id,$request))
                {
                    return $this->respond($data,200);
                }else{
                    return $this->fail(["error" => "Database Error!"],400,null,'db');
                }
            }catch(\Exception $e){
                return $this->fail(["error" => $e->getMessage()],400,null,'system');
            }
        }
    }

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

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        try{
            $tmodel = new Devicemodel();
            if ($tmodel->delete($id))
            {
                return $this->respond($data,200);
            }else{
                return $this->fail(["error" => "Database Error!"],400,null,'db');
            }
        }catch(\Exception $e){
            return $this->fail(["error" => $e->getMessage()],400,null,'db');
        }
    }
}
?>