<?php

namespace App\Controllers\Referensi;

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

class Pdksatker extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->PdksatkerModel = model('App\Models\Referensi\PdksatkerModel');
        $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
    private function ruleData($id = null)
    {
        return [
            'id' => 'trim',
            'satker' => $id 
                ? "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[200]|is_unique[pdk_satker.satker,id,{$id}]"
                : "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[200]|is_unique[pdk_satker.satker]",
            'alamat' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
            'lati' => 'permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
            'longi' => 'permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
            'prov' => 'required',
            'kako' => 'required',
            'kodepos' => 'permit_empty|numeric',
            'tel1' => 'permit_empty|numeric',
            'mail1' => 'permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
            'tipe' => 'required|regex_match[/^[a-zA-Z0-9\s.,@\/\-]+$/]',
            'id_kanwil' => 'permit_empty|numeric',
            'id_area' => 'permit_empty|numeric',
        ];
    }

    public function index()
    {
        //function($modul, $menu) --------
        $links = genlinks('referensi', 'pdksatker');

        $link_show = base_url('referensi/pdksatker/show/');

        $rekam = $links['rekam']['status'];
        $link_rekam = base_url('referensi/pdksatker/new');

        $ubah = $links['ubah']['status'];
        $link_ubah = base_url('referensi/pdksatker/edit/');

        $hapus = $links['hapus']['status'];
        $link_hapus = base_url('referensi/pdksatker/delete');

        return view('referensi/pdksatker/pdksatker_list', [
            'rekam' => $rekam,
            'link_show' => $link_show,
            'link_rekam' => $link_rekam,
            'ubah' => $ubah,
            'link_ubah' => $link_ubah,
            'hapus' => $hapus,
            'link_hapus' => $link_hapus,
        ]);
    }

    public function datagrid()
    {
        $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->PdksatkerModel->get_rows2($rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }

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

        return $this->response->setJSON($res);
    }

    public function show($id)
    {
        $row = $this->PdksatkerModel->find(decrypt_url($id));

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

        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        return view('referensi/pdksatker/pdksatker_show', [
            'back' => base_url('referensi/pdksatker'),
			'id' => encrypt_url($row->id),
			'satker' => $row->satker,
			'alamat' => $row->alamat,
            'lati' => $row->lati,
            'longi' => $row->longi,
			'prov' => $row->prov,
            'kako' => $row->kako,
			'kodepos' => $row->kodepos,
			'tel1' => $row->tel1,
            'mail1' => $row->mail1,
			'tipe' => $row->tipe,
            'id_kanwil' => $row->id_kanwil,
            'id_area' => $row->id_area,
            'dt_prov' => $this->PdksatkerModel->dt_prov(),
            'dd_kako' => $this->PdksatkerModel->dt_kako($row->prov),
            'map_api' => $map_api,
        ]);
    }

    public function new()
    {
        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        return view('referensi/pdksatker/pdksatker_form', [
            'action' => base_url('referensi/pdksatker/create'),
            'back' => base_url('referensi/pdksatker'),
            'button' => 'SIMPAN DATA',
			'id' => '',
			'satker' => '',
			'alamat' => '',
            'lati' => '',
            'longi' => '',
			'prov' => '',
            'kako' => '',
			'kodepos' => '',
			'tel1' => '',
			'mail1' => '',
            'tipe' => '',
			'id_kanwil' => '',
			'id_area' => '',
            'dt_prov' => $this->PdksatkerModel->dt_prov(),
            'dd_kako' => $this->PdkkakoModel->dd_kako1(0),
            'map_api' => $map_api,
        ]);
    }

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

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

        //Collect form data
        $id_kanwil = $this->request->getPost('id_kanwil', FILTER_SANITIZE_NUMBER_INT);
        $id_area = $this->request->getPost('id_area', FILTER_SANITIZE_NUMBER_INT);

        $data = [
			'satker' => $this->request->getPost('satker', FILTER_SANITIZE_SPECIAL_CHARS),
			'alamat' => $this->request->getPost('alamat', FILTER_SANITIZE_SPECIAL_CHARS),
            'lati' => $this->request->getPost('lati', FILTER_SANITIZE_SPECIAL_CHARS),
            'longi' => $this->request->getPost('longi', FILTER_SANITIZE_SPECIAL_CHARS),
            'prov' => $this->request->getPost('prov', FILTER_SANITIZE_NUMBER_INT),
			'kako' => $this->request->getPost('kako', FILTER_SANITIZE_NUMBER_INT),
			'kodepos' => $this->request->getPost('kodepos', FILTER_SANITIZE_NUMBER_INT),
			'tel1' => $this->request->getPost('tel1', FILTER_SANITIZE_NUMBER_INT),
            'mail1' => $this->request->getPost('mail1', FILTER_SANITIZE_SPECIAL_CHARS),
			'tipe' => $this->request->getPost('tipe', FILTER_SANITIZE_SPECIAL_CHARS),
			'id_kanwil' => !empty($id_kanwil) ? $id_kanwil : 0,
			'id_area' => !empty($id_area) ? $id_area : 0,
        ];

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

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

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

    public function edit($id)
    {
        $row = $this->PdksatkerModel->find(decrypt_url($id));

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

        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        return view('referensi/pdksatker/pdksatker_edit', [
            'action' => base_url('referensi/pdksatker/update'),
            'back' => base_url('referensi/pdksatker'),
            'button' => 'UBAH DATA', 
			'id' => encrypt_url($row->id),
			'satker' => $row->satker,
			'alamat' => $row->alamat,
            'lati' => $row->lati,
            'longi' => $row->longi,
			'prov' => $row->prov,
            'kako' => $row->kako,
			'kodepos' => $row->kodepos,
			'tel1' => $row->tel1,
            'mail1' => $row->mail1,
			'tipe' => $row->tipe,
            'id_kanwil' => $row->id_kanwil,
            'id_area' => $row->id_area,
            'dt_prov' => $this->PdksatkerModel->dt_prov(),
            'dd_kako' => $this->PdksatkerModel->dt_kako($row->prov),
            'map_api' => $map_api,
        ]);
    }

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

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

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));
        $id_kanwil = $this->request->getPost('id_kanwil', FILTER_SANITIZE_NUMBER_INT);
        $id_area = $this->request->getPost('id_area', FILTER_SANITIZE_NUMBER_INT);

        $data = [
            'id'  => $id,
			'satker' => $this->request->getPost('satker', FILTER_SANITIZE_SPECIAL_CHARS),
            'alamat' => $this->request->getPost('alamat', FILTER_SANITIZE_SPECIAL_CHARS),
            'lati' => $this->request->getPost('lati', FILTER_SANITIZE_SPECIAL_CHARS),
            'longi' => $this->request->getPost('longi', FILTER_SANITIZE_SPECIAL_CHARS),
            'prov' => $this->request->getPost('prov', FILTER_SANITIZE_NUMBER_INT),
            'kako' => $this->request->getPost('kako', FILTER_SANITIZE_NUMBER_INT),
            'kodepos' => $this->request->getPost('kodepos', FILTER_SANITIZE_NUMBER_INT),
            'tel1' => $this->request->getPost('tel1', FILTER_SANITIZE_NUMBER_INT),
            'mail1' => $this->request->getPost('mail1', FILTER_SANITIZE_SPECIAL_CHARS),
            'tipe' => $this->request->getPost('tipe', FILTER_SANITIZE_SPECIAL_CHARS),
            'id_kanwil' => !empty($id_kanwil) ? $id_kanwil : 0,
            'id_area' => !empty($id_area) ? $id_area : 0,
        ];

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

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

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

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

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

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

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

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

    //AMBIL DATA KAKO BY PROV
    public function get_prov()
    {
        $this->setJsonHeader();

        $field      = $this->request->getPost('id_prov');
        $datas      = $this->PdksatkerModel->dt_kako($field);
        $datax = array("id" => "", "nama_kako" => "Pilih Kabupaten/Kota...");
        array_unshift($datas , $datax);

        return json_encode($datas);
    }

    //AMBIL DATA WILAYAH
    public function get_wilayah()
    {
        $this->setJsonHeader();

        $datas = $this->PdksatkerModel->dt_wilayah();
        return json_encode($datas);
    }

    //AMBIL DATA AREA BY WILAYAH
    public function get_area()
    {
        $this->setJsonHeader();

        $id_wilayah = $this->request->getPost('id_kanwil');
        $datas = $this->PdksatkerModel->dt_area($id_wilayah);
        return json_encode($datas);
    }
}