<?php

namespace App\Controllers\Potensiwilayah;

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

class Datapromosi extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->DatapromosiModel = model('App\Models\Potensiwilayah\DatapromosiModel');
    }

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

    //Validation Rule
    private function ruleData($id = null)
    {
        return [
            'id' => 'trim',
            'id_jenis' => 'required|numeric',
            'id_katelok' => 'required|numeric',
            'id_lokasi' => 'required|numeric',
            'nama_giat' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[200]',
            'piclok_nama' => 'permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[100]',
            'piclok_kontak' => 'permit_empty|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[50]',
            'tgl_1' => 'required|valid_date',
            'tgl_2' => 'required|valid_date',
            'status' => 'permit_empty|in_list[0,1]',
        ];
    }

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

        $link_show = base_url('potensiwilayah/datapromosi/show/');

        $rekam = $links['rekam']['status'];
        $link_rekam = base_url('potensiwilayah/datapromosi/new');

        $ubah = $links['ubah']['status'];
        $link_ubah = base_url('potensiwilayah/datapromosi/edit/');

        $hapus = $links['hapus']['status'];
        $link_hapus = base_url('potensiwilayah/datapromosi/delete');

        return view('potwil/promosi/promosi_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();
        
        $user_id = auth()->id();
        $id_kantor = $this->DatapromosiModel->kantor_user($user_id);

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

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

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

    public function show($id)
    {
        $row = $this->DatapromosiModel->find_by_id(decrypt_url($id));

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

        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        return view('potwil/promosi/promosi_show', [
            'back' => base_url('potensiwilayah/datapromosi'),
            'id' => encrypt_url($row->id),
            'id_jenis' => $row->id_jenis,
            'nama_kegiatan' => $row->nama_kegiatan,
            'id_katelok' => $row->id_katelok,
            'nama_kat' => $row->nama_kat,
            'id_lokasi' => $row->id_lokasi,
            'nama_lokasi' => $row->nama_lokasi,
            'lati' => $row->lati,
            'longi' => $row->longi,
            'nama_giat' => $row->nama_giat,
            'piclok_nama' => $row->piclok_nama,
            'piclok_kontak' => $row->piclok_kontak,
            'tgl_1' => $row->tgl_1,
            'tgl_2' => $row->tgl_2,
            'status' => $row->status,
            'map_api' => $map_api,
        ]);
    }

    public function new()
    {
        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        $id_kantor = $this->DatapromosiModel->get_user_kantor(auth()->id());
        
        return view('potwil/promosi/promosi_form', [
            'action' => base_url('potensiwilayah/datapromosi/create'),
            'back' => base_url('potensiwilayah/datapromosi'),
            'button' => 'SIMPAN DATA',
            'id' => '',
            'id_jenis' => '',
            'id_katelok' => '',
            'id_lokasi' => '',
            'nama_giat' => '',
            'piclok_nama' => '',
            'piclok_kontak' => '',
            'tgl_1' => '',
            'tgl_2' => '',
            'status' => 0,
            'dd_jenis' => $this->DatapromosiModel->dd_jenis(),
            'dd_katelok' => $this->DatapromosiModel->dd_katelok(),
            'dd_lokasi' => [],
            'id_kantor' => $id_kantor,
            'map_api' => $map_api,
        ]);
    }

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

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

        //Collect form data
        $id_kantor = $this->DatapromosiModel->get_user_kantor(auth()->id());
        $data = [
            'id_jenis' => $this->request->getPost('id_jenis', FILTER_SANITIZE_NUMBER_INT),
            'id_katelok' => $this->request->getPost('id_katelok', FILTER_SANITIZE_NUMBER_INT),
            'id_lokasi' => $this->request->getPost('id_lokasi', FILTER_SANITIZE_NUMBER_INT),
            'nama_giat' => $this->request->getPost('nama_giat', FILTER_SANITIZE_SPECIAL_CHARS),
            'piclok_nama' => $this->request->getPost('piclok_nama', FILTER_SANITIZE_SPECIAL_CHARS),
            'piclok_kontak' => $this->request->getPost('piclok_kontak', FILTER_SANITIZE_SPECIAL_CHARS),
            'tgl_1' => $this->request->getPost('tgl_1', FILTER_SANITIZE_SPECIAL_CHARS),
            'tgl_2' => $this->request->getPost('tgl_2', FILTER_SANITIZE_SPECIAL_CHARS),
            'status' => $this->request->getPost('status', FILTER_SANITIZE_NUMBER_INT) ?: 0,
            'id_kantor' => $id_kantor,
            'id_rek' => auth()->id(),
            'wkt_rek' => date('Y-m-d H:i:s'),
        ];

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

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

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

    public function edit($id)
    {
        $row = $this->DatapromosiModel->find_by_id(decrypt_url($id));

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

        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        $id_kantor = $this->DatapromosiModel->get_user_kantor(auth()->id());
        
        return view('potwil/promosi/promosi_form', [
            'action' => base_url('potensiwilayah/datapromosi/update'),
            'back' => base_url('potensiwilayah/datapromosi'),
            'button' => 'UBAH DATA', 
            'id' => encrypt_url($row->id),
            'id_jenis' => $row->id_jenis,
            'id_katelok' => $row->id_katelok,
            'id_lokasi' => $row->id_lokasi,
            'nama_giat' => $row->nama_giat,
            'piclok_nama' => $row->piclok_nama,
            'piclok_kontak' => $row->piclok_kontak,
            'tgl_1' => $row->tgl_1,
            'tgl_2' => $row->tgl_2,
            'status' => $row->status,
            'dd_jenis' => $this->DatapromosiModel->dd_jenis(),
            'dd_katelok' => $this->DatapromosiModel->dd_katelok(),
            'dd_lokasi' => $this->DatapromosiModel->dd_lokasi($row->id_katelok, $id_kantor),
            'id_kantor' => $id_kantor,
            'map_api' => $map_api,
        ]);
    }

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

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

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

        $data = [
            'id'  => $id,
            'id_jenis' => $this->request->getPost('id_jenis', FILTER_SANITIZE_NUMBER_INT),
            'id_katelok' => $this->request->getPost('id_katelok', FILTER_SANITIZE_NUMBER_INT),
            'id_lokasi' => $this->request->getPost('id_lokasi', FILTER_SANITIZE_NUMBER_INT),
            'nama_giat' => $this->request->getPost('nama_giat', FILTER_SANITIZE_SPECIAL_CHARS),
            'piclok_nama' => $this->request->getPost('piclok_nama', FILTER_SANITIZE_SPECIAL_CHARS),
            'piclok_kontak' => $this->request->getPost('piclok_kontak', FILTER_SANITIZE_SPECIAL_CHARS),
            'tgl_1' => $this->request->getPost('tgl_1', FILTER_SANITIZE_SPECIAL_CHARS),
            'tgl_2' => $this->request->getPost('tgl_2', FILTER_SANITIZE_SPECIAL_CHARS),
            'status' => $this->request->getPost('status', FILTER_SANITIZE_NUMBER_INT) ?: 0,
        ];

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

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

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

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

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('datapromosi', '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->DatapromosiModel->delete($del)) {
            return $this->fail($this->DatapromosiModel->errors(), 500);
        } else {
            return $this->respond(['message' => count($del).lang('App.delete_success')]);
        }
    }

    //AMBIL DATA LOKASI BY KATEGORI
    public function get_lokasi()
    {
        $this->setJsonHeader();

        $id_katelok = $this->request->getPost('id_katelok');
        $id_kantor = $this->DatapromosiModel->get_user_kantor(auth()->id());
        $datas = $this->DatapromosiModel->dd_lokasi($id_katelok, $id_kantor);
        $datax = array("id" => "", "nama_lokasi" => "Pilih Lokasi...");
        array_unshift($datas , $datax);

        return json_encode($datas);
    }

    //AMBIL DETAIL LOKASI BY ID
    public function get_lokasi_detail()
    {
        $this->setJsonHeader();

        $id_lokasi = $this->request->getPost('id_lokasi');
        $data = $this->DatapromosiModel->get_lokasi_detail($id_lokasi);

        return json_encode($data);
    }
}
