<?php

namespace App\Controllers\Referensi;

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

class Pdkprov extends BaseController
{
	use ResponseTrait;

    public function __construct()
    {
        $this->PdkprovModel = model('App\Models\Referensi\PdkprovModel');
        $this->PdkkakoModel = model('App\Models\Referensi\PdkkakoModel');
    }

    private function setJsonHeader()
    {
        return $this->response->setHeader('Content-Type', 'application/json');
    }

    //Validation Rule untuk Provinsi
    private function ruleProv($id = null)
    {
        return [
            'nama_prov' => $id 
                ? "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[pdk_prov.nama_prov,id,{$id}]"
                : "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[pdk_prov.nama_prov]",
            'nama_alt'  => $id 
                ? "permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[pdk_prov.nama_alt,id,{$id}]"
                : "permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[pdk_prov.nama_alt]",
            'kode' => 'permit_empty|numeric',
        ];
    }

    //Validation Rule untuk Kota/Kab.
    private $vrKako = [
        'id_prov'   => 'required|numeric',
        'nama_kako'  => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
        'nama_alt'  => 'permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
        'kode' => 'permit_empty|numeric',
    ];

    public function index()
    {
        if (priv_menu('pdkprov', 'rekam')) {
            $rekam = 1;
            $link_rekam_prov = base_url('referensi/pdkprov/new_prov');
            $link_rekam_kako = base_url('referensi/pdkprov/new_kako');
        } else {
            $rekam = 0;
            $link_rekam_prov = '';
            $link_rekam_kako = '';
        }

        if (priv_menu('pdkprov', 'ubah')) {
            $ubah = 1;
            $link_ubah_prov = base_url('referensi/pdkprov/edit_prov/');
            $link_ubah_kako = base_url('referensi/pdkprov/edit_kako/');
        } else {
            $ubah = 0;
            $link_ubah_prov = '';
            $link_ubah_kako = '';
        }

        if (priv_menu('pdkprov', 'hapus')) {
            $hapus = 1;
            $link_hapus_prov = base_url('referensi/pdkprov/delete_prov');
            $link_hapus_kako = base_url('referensi/pdkprov/delete_kako');
        } else {
            $hapus = 0;
            $link_hapus_prov = '';
            $link_hapus_kako = '';
        }

        return view('referensi/pdkprov/prov_list', [
            'rekam' => $rekam,
            'link_rekam_prov' => $link_rekam_prov,
            'link_rekam_kako' => $link_rekam_kako,
            'ubah' => $ubah,
            'link_ubah_prov' => $link_ubah_prov,
            'link_ubah_kako' => $link_ubah_kako,
            'hapus' => $hapus,
            'link_hapus_prov' => $link_hapus_prov,
            'link_hapus_kako' => $link_hapus_kako,
        ]);
    }

    //DATAGRID PROV
    public function datagrid_prov()
    {
        $this->setJsonHeader();

        $page           = trim($this->request->getPost('page')) ? trim($this->request->getPost('page')) : 1;
        $rows           = trim($this->request->getPost('rows')) ? trim($this->request->getPost('rows')) : 10;
        $sort           = trim($this->request->getPost('sort'));
        $order          = trim($this->request->getPost('order'));
        $filterRules    = trim($this->request->getPost('filterRules'));
        $start          = ($page - 1) * $rows;

        if ($sort && $order) {
            $sortOrder = multi_sort($sort, $order);
        } else {
            $sortOrder = multi_sort('id', 'ASC');
        }

        $datas = $this->PdkprovModel->get_rows($rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }


        $res['total']  = $this->PdkprovModel->get_total($filterRules);
        $res['rows']   = $datas;

        return $this->response->setJSON($res);
    }//END DATAGRID PROV

    //DATAGRID MENU
    public function datagrid_kako()
    {
        $this->setJsonHeader();

        $id_prov = (!empty($this->request->getPost('id_prov')) ? decrypt_url($this->request->getPost('id_prov')) : $this->session->get('id_prov_mm'));
        $this->session->set('id_prov_mm',$id_prov);

        $page           = trim($this->request->getPost('page')) ? trim($this->request->getPost('page')) : 1;
        $rows           = trim($this->request->getPost('rows')) ? trim($this->request->getPost('rows')) : 10;
        $sort           = trim($this->request->getPost('sort'));
        $order          = trim($this->request->getPost('order'));
        $filterRules    = trim($this->request->getPost('filterRules'));
        $start          = ($page - 1) * $rows;

        if ($sort && $order) {
            $sortOrder = multi_sort($sort, $order);
        } else {
            $sortOrder = multi_sort('id', 'ASC');
        }

        $datas = $this->PdkkakoModel->get_rows2($id_prov, $rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }


        $res['total']  = $this->PdkkakoModel->get_total2($id_prov, $filterRules);
        $res['rows']   = $datas;

        return $this->response->setJSON($res);
    }//END DATAGRID MENU

    //FUNGSI SHOW --------------------------
    public function show_prov($id)
    {
        $row = $this->PdkprovModel->find(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        return view('referensi/pdkprov/prov_show', [
			'nama_prov' => $row->nama_prov,
			'nama_alt' => $row->nama_alt,
			'kode' => $row->kode,
        ]);
    }

    public function show_kako($id)
    {
        $row = $this->PdkkakoModel->find_by_id(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        return view('referensi/pdkprov/kako_show', [
            'nama_prov' => $row->nama_prov,
            'nama_kako' => $row->nama_kako,
            'nama_alt' => $row->nama_alt,
            'kode' => $row->kode,
        ]);
    } //END FUNGSI SHOW --------------------

    //FUNGSI REKAM---------------------
    //Tampilkan Form untuk Rekam Prov
    public function new_prov()
    {
        if (priv_menu('pdkprov', 'rekam')) {
            return view('referensi/pdkprov/prov_form', [
                'action' => base_url('referensi/pdkprov/create_prov'),
                'button' => 'SIMPAN DATA',
    			'id' => '',
    			'nama_prov' => '',
    			'nama_alt' => '',
    			'kode' => '',
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }//End Tampilkan Form untuk Rekam

    //proses simpan prov
    public function create_prov()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('pdkprov', 'rekam')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //Collect form data
        $data = [
			'nama_prov' => $this->request->getPost('nama_prov', FILTER_SANITIZE_SPECIAL_CHARS),
			'nama_alt' => $this->request->getPost('nama_alt', FILTER_SANITIZE_SPECIAL_CHARS),
			'kode' => $this->request->getPost('kode', FILTER_SANITIZE_NUMBER_INT),
        ];

        $vrData = $this->ruleProv();
        //jika validasi gagal
        if (!$this->validate($vrData)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        if (!$this->PdkprovModel->insert($data)) {
            return $this->fail($this->PdkprovModel->errors(), 500);
        }

        return $this->respond(['message' => B_SIMPAN], 201);
    }//end create form

    //Tampilkan Form untuk Rekam Kako
    public function new_kako()
    {
        if (priv_menu('pdkprov', 'rekam')) {
            return view('referensi/pdkprov/kako_form', [
                'action' => base_url('referensi/pdkprov/create_kako'),
                'button' => 'SIMPAN DATA',
    			'id' => '',
    			'id_prov' => '',
    			'nama_kako' => '',
    			'nama_alt' => '',
    			'kode' => '',
    			'dd_prov' => $this->PdkprovModel->dd_prov(),
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }//End Tampilkan Form untuk Rekam

    public function create_kako()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('pdkprov', 'rekam')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect data form
        $data = [
            'id_prov' => $this->request->getPost('id_prov', FILTER_SANITIZE_NUMBER_INT),
            'nama_kako' => $this->request->getPost('nama_kako', FILTER_SANITIZE_SPECIAL_CHARS),
            'nama_alt' => $this->request->getPost('nama_alt', FILTER_SANITIZE_SPECIAL_CHARS),
            'kode' => $this->request->getPost('kode', FILTER_SANITIZE_NUMBER_INT),
        ];

        //jika validasi gagal
        if (!$this->validate($this->vrKako)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        //jika insert gagal
        if (!$this->PdkkakoModel->insert($data)) {
            return $this->fail($this->PdkkakoModel->errors(), 500);
        }

        return $this->respond(['message' => B_SIMPAN], 201);
    }
    //END FUNGSI REKAM---------------------

    //FUNGSI UBAH---------------------
    public function edit_prov($id)
    {
    	if (priv_menu('pdkprov', 'ubah')) {
	        $row = $this->PdkprovModel->find(decrypt_url($id));

	        if (!$row) {
	            exit('Data tidak ditemukan');
	        }

	        return view('referensi/pdkprov/prov_form', [
	            'action' => base_url('referensi/pdkprov/update_prov'),
	            'button' => 'UBAH DATA',
				'id' => encrypt_url($row->id),
				'nama_prov' => $row->nama_prov,
				'nama_alt' => $row->nama_alt,
				'kode' => $row->kode,
	        ]);
	    } else {
	    	return $this->fail(['message' => NO_AKSES], 403);
	    }
	}

	public function update_prov()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('pdkprov', 'ubah')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));
        $data = [
            'id'  => $id,
			'nama_prov' => $this->request->getPost('nama_prov', FILTER_SANITIZE_SPECIAL_CHARS),
            'nama_alt' => $this->request->getPost('nama_alt', FILTER_SANITIZE_SPECIAL_CHARS),
            'kode' => $this->request->getPost('kode', FILTER_SANITIZE_NUMBER_INT),
        ];

        $vrData = $this->ruleProv($id);
        //jika validasi gagal
        if (!$this->validate($vrData)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        if (!$this->PdkprovModel->update($id, $data)) {
            return $this->fail($this->PdkprovModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }

    //Tampilkan Form Edit Kako
    public function edit_kako($id)
    {
        $row = $this->PdkkakoModel->find_by_id(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        return view('referensi/pdkprov/kako_form', [
            'action' => base_url('referensi/pdkprov/update_kako'),
            'button' => 'UBAH DATA', 
            'id' => encrypt_url($row->id),
            'id_prov' => $row->id_prov,
            'nama_kako' => $row->nama_kako,
            'nama_alt' => $row->nama_alt,
            'kode' => $row->kode,
            'dd_prov' => $this->PdkprovModel->dd_prov(),
        ]);
    }//End Tampilkan Form Edit Kako

    //Proses Update Menu
    public function update_kako()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('pdkprov', 'ubah')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));
        $data = [
            'id_prov' => $this->request->getPost('id_prov', FILTER_SANITIZE_NUMBER_INT),
            'nama_kako' => $this->request->getPost('nama_kako', FILTER_SANITIZE_SPECIAL_CHARS),
            'nama_alt' => $this->request->getPost('nama_alt', FILTER_SANITIZE_SPECIAL_CHARS),
            'kode' => $this->request->getPost('kode', FILTER_SANITIZE_NUMBER_INT),
        ];

        //jika validasi gagal
        if (!$this->validate($this->vrKako)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        //jika proses update gagal
        if (!$this->PdkkakoModel->update($id, $data)) {
            return $this->fail($this->PdkkakoModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }//End Proses Update Menu
    //END FUNGSI UBAH---------------------

    //FUNGSI HAPUS---------------------
    public function delete_prov()
    {
        $this->setJsonHeader();

        $ids  = $this->request->getPost('ids');

        $del = array();
        foreach ($ids as $id) {
            $del[] = decrypt_url($id);
        }

        if (!$this->PdkprovModel->delete($del)) {
            return $this->fail($this->PdkprovModel->errors(), 500);
        } else {
            return $this->respond(['message' => count($del).lang('App.delete_success')]);
        }
    }

    //Proses Delete Menu
    public function delete_kako()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk hapus data
        if (!priv_menu('pdkprov', 'hapus')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect form data
        $ids  = $this->request->getPost('ids');
        $del = array();
        foreach ($ids as $id) {
            $del[] = decrypt_url($id);
        }

        if (!$this->PdkkakoModel->delete($del)) {
            return $this->fail($this->PdkkakoModel->errors(), 500);
        }

        return $this->respond(['message' => count($del).' '.B_HAPUS], 200);
    }
    //END FUNGSI HAPUS
}