<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\AreaModel;
use App\Models\CustomerModel;

class Subdistrict extends BaseController
{


    private $AreaModel;
    private $CustomerModel;

    public function __construct()
    {

        $this->AreaModel      = new AreaModel();   
        $this->CustomerModel      = new CustomerModel();   
    }

    public function index()
    {   


        haveAccess(2,"is_read", session()->get('role_id'));

        $data   = [
            'title' => "Kecamatan",
        ];

        return  view('app/subdistrict/main/subdistrict-main-css', $data) .
        view('app/subdistrict/main/subdistrict-main', $data) .
        view('app/subdistrict/main/subdistrict-main-js', $data);

    }

    public function add()
    {


        haveAccess(2,"is_update", session()->get('role_id'));

        $data = [
            'title' => "Tambah Kecamatan"
        ];

        return  view('app/subdistrict/add/subdistrict-add-css', $data) .
        view('app/subdistrict/add/subdistrict-add', $data) .
        view('app/subdistrict/add/subdistrict-add-js', $data);
    }


    public function detail($id = null)
    {


        haveAccess(2,"is_read", session()->get('role_id'));

        $this->GoodModel->select('tbl_good.*, tbl_area.name AS area_name');
        $this->GoodModel->join('tbl_area','tbl_area.id=tbl_good.area_id');
        $row = $this->GoodModel->find($id);


        $data = [
            'title' => "Detail Barang",
            'code'  => $row->unique_id
        ];

        return  view('app/good/detail-qrcode/detail-qrcode-css', $data) .
        view('app/good/detail-qrcode/detail-qrcode', $data) .
        view('app/good/detail-qrcode/detail-qrcode-js', $data);
    }

    public function save()
    {


        haveAccess(2,"is_create", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
        ];


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

            

        $data = [
            'type'          => "SUBDISTRICT",
            'name'          => $request->name,
            'created_by'    => session()->get('id'),
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        if(!$this->AreaModel->insert($data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Subdistrict","Create","User $nameUser berhasil membuat data kecamatan $request->name ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);





    }


    public function getAllData()
    {
        
        $this->AreaModel->draw     = $this->request->getPOST('draw');
        $this->AreaModel->start    = $this->request->getPOST('start');
        $this->AreaModel->limit    = $this->request->getPOST('length');
        $this->AreaModel->search   = $this->request->getPOST('search')['value'];
        $this->AreaModel->columns  = $this->request->getPOST('columns');
        $this->AreaModel->order    = $this->request->getPOST('order');

        echo $this->AreaModel->getAllDataSubdistrict();
    }

    public function delete()
    {


        haveAccess(2,"is_delete", session()->get('role_id'));

        $request;
        if ($this->request->hasHeader('Content-Type') && strpos($this->request->getHeaderLine('Content-Type'), 'application/json') !== false) {
            $request    = $this->request->getJSON();
        }else{
            $request    = $this->request->getPOST();
        }

        $request = json_decode(json_encode($request));


                    $this->AreaModel->where('parent_id',$request->id);
        $isExits = $this->AreaModel->first();
        if(!empty((array)$isExits)){
            
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data kecamatan tidak bisa dihapus dikarenakan sudah digunakan di beberapa desa"
            ]);            
        }


                    $this->CustomerModel->where('subdistrict_id',$request->id);
        $isExitsSub = $this->CustomerModel->first();
        if(!empty((array)$isExitsSub)){
            
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data kecamatan tidak bisa dihapus dikarenakan sudah digunakan di beberapa pelanggan"
            ]);            
        }


        $this->AreaModel->where('id', $request->id);
        if(!$this->AreaModel->delete()){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal dihapus. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Subdistrict","Delete","User $nameUser berhasil menghapus data kecamatan ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil dihapus"
        ]);

    }


    public function edit($id = null)
    {


        haveAccess(2,"is_update", session()->get('role_id'));

        $row = $this->AreaModel->find($id);

        $data = [
            'title' => "Edit Kecamatan",
            'row'   => $row
        ];

        return  view('app/subdistrict/edit/subdistrict-edit-css', $data) .
        view('app/subdistrict/edit/subdistrict-edit', $data) .
        view('app/subdistrict/edit/subdistrict-edit-js', $data);
        
    }



    public function update()
    {


        haveAccess(2,"is_update", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ]
        ];


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

        
        $data = [
            'name'          => $request->name,
            'updated_by'         => session()->get('id'),
            'updated_at'         => date('Y-m-d H:i:s'),
        ];

        if(!$this->AreaModel->update($request->id, $data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Subdistrict","Update","User $nameUser berhasil mengubah data desa $request->name ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);


    }



    public function getAllSubdistirctName()
    {
        $page  = $this->request->getPOST('page') ? $this->request->getPOST('page') - 1 : 0;
        $limit = $this->request->getPOST('limit') ? $this->request->getPOST('limit') : 30;

        $this->AreaModel->name          = $this->request->getPOST('name');
        $this->AreaModel->limit         = $limit;
        $this->AreaModel->start         = ($page * $limit);

        echo $this->AreaModel->getAllSubdistirctName();
    }



}

