<?php

namespace App\Controllers;

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

class Village 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' => "Desa",
        ];

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

    }

    public function add()
    {


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

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

        return  view('app/village/add/village-add-css', $data) .
        view('app/village/add/village-add', $data) .
        view('app/village/add/village-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',
                ]
            ],
            'subdistrict' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Kecamatan tidak boleh kosong',
                ]
            ],
        ];


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

            

        $data = [
            'parent_id'     => $request->subdistrict,
            'type'          => "VILLAGE",
            '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("Village","Create","User $nameUser berhasil membuat data desa $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->getAllDataVillage();
    }

    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->CustomerModel->where('village_id',$request->id);
        $isExitsVil = $this->CustomerModel->first();
        if(!empty((array)$isExitsVil)){
            
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data desa 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("Village","Delete","User $nameUser berhasil menghapus data desa ",$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);
        $row->parent_name = $this->AreaModel->find($row->parent_id)->name;


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

        return  view('app/village/edit/village-edit-css', $data) .
        view('app/village/edit/village-edit', $data) .
        view('app/village/edit/village-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',
                ]
            ],
            'subdistrict_edit' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Kecamatan tidak boleh kosong',
                ]
            ],
        ];


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

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

        if(!$this->AreaModel->update($request->hide_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("Village","Update","User $nameUser berhasil mengubah data desa $request->name ",$userId);

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


    }



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

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

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



}

