<?php

namespace App\Controllers\Referensi;

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

class Pdklayanan extends BaseController
{
	use ResponseTrait;

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

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

    //Validation Rule untuk Layanan Master
    private function ruleMlay($id = null)
    {
        return [
            'uraian' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[200]',
            'sla' => 'required|numeric|max_length[10]',
            'satuan' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[100]',
            'menit' => 'permit_empty|numeric|max_length[10]',
            'bobot' => 'permit_empty|numeric|max_length[10]',
            'status' => 'permit_empty|in_list[0,1]',
        ];
    }

    //Validation Rule untuk Layanan Detail
    public function index()
    {
        if (priv_menu('pdklayanan', 'rekam')) {
            $rekam = 1;
            $link_rekam_mlay = base_url('referensi/pdklayanan/new_mlay');
            $link_rekam_clay = base_url('referensi/pdklayanan/new_clay');
        } else {
            $rekam = 0;
            $link_rekam_mlay = '';
            $link_rekam_clay = '';
        }

        if (priv_menu('pdklayanan', 'ubah')) {
            $ubah = 1;
            $link_ubah_mlay = base_url('referensi/pdklayanan/edit_mlay/');
            $link_ubah_clay = base_url('referensi/pdklayanan/edit_clay/');
        } else {
            $ubah = 0;
            $link_ubah_mlay = '';
            $link_ubah_clay = '';
        }

        if (priv_menu('pdklayanan', 'hapus')) {
            $hapus = 1;
            $link_hapus_mlay = base_url('referensi/pdklayanan/delete_mlay');
            $link_hapus_clay = base_url('referensi/pdklayanan/delete_clay');
        } else {
            $hapus = 0;
            $link_hapus_mlay = '';
            $link_hapus_clay = '';
        }

        return view('referensi/pdklayanan/layanan_list', [
            'rekam' => $rekam,
            'link_rekam_mlay' => $link_rekam_mlay,
            'link_rekam_clay' => $link_rekam_clay,
            'ubah' => $ubah,
            'link_ubah_mlay' => $link_ubah_mlay,
            'link_ubah_clay' => $link_ubah_clay,
            'hapus' => $hapus,
            'link_hapus_mlay' => $link_hapus_mlay,
            'link_hapus_clay' => $link_hapus_clay,
        ]);
    }

    //DATAGRID STAKE
    public function datagrid_mlay()
    {
        $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->PdkmlayModel->get_rows($rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }

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

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

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

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

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


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

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

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

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

        return view('referensi/pdklayanan/mlay_show', [
            'uraian' => $row->uraian,
            'sla' => $row->sla,
            'satuan' => $row->satuan,
            'menit' => $row->menit,
            'bobot' => $row->bobot,
            'status' => $row->status,
        ]);
    }

    public function show_clay($id)
    {
        $row = $this->PdkclayModel->find_by_id(decrypt_url($id));

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

        // Buat URL untuk view PDF
        $pdfUrl = $row->berkas != '0' ? base_url('referensi/pdklayanan/view_pdf/' . encrypt_url($row->berkas)) : '0';

        return view('referensi/pdklayanan/clay_show', [
            'nama_layanan' => $row->nama_layanan,
            'slayanan' => $row->uraian,
            'berkas' => $row->berkas,
            'pdfUrl' => $pdfUrl,
        ]);
    } 
    //END FUNGSI SHOW --------------------

    //FUNGSI SHOW BERKAS PDF
    public function view_pdf($key)
    {
        // Decode key jika dienkripsi
        $fileKey = decrypt_url($key);
        
        // Ambil file dari server
        $res = download_ceisa($fileKey);
        
        if ($res && $res->getStatusCode() == '200') {
            $body = json_decode($res->getBody());
            
            if (!empty($body->data->base64)) {
                // Set header untuk PDF
                return $this->response
                    ->setHeader('Content-Type', 'application/pdf')
                    ->setBody(base64_decode($body->data->base64));
            }
        }
        
        // Jika file tidak ditemukan, tampilkan pesan error
        return $this->response->setBody('PDF tidak ditemukan');
    }
    //-------------------------

    //FUNGSI REKAM---------------------
    //Tampilkan Form untuk Rekam Layanan Master
    public function new_mlay()
    {
        if (priv_menu('pdklayanan', 'rekam')) {
            return view('referensi/pdklayanan/mlay_form', [
                'action' => base_url('referensi/pdklayanan/create_mlay'),
                'button' => 'SIMPAN DATA',
                'id' => '',
                'uraian' => '',
                'sla' => '',
                'satuan' => '',
                'menit' => '',
                'bobot' => '',
                'status' => '',
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }
    //End Tampilkan Form untuk Rekam

    //proses simpan layanan 
    public function create_mlay()
    {
        $this->setJsonHeader();

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

        //Collect form data
        $status = !empty($this->request->getPost('status')) ? 1:0;
        $data = [
            'uraian' => $this->request->getPost('uraian', FILTER_SANITIZE_SPECIAL_CHARS),
            'sla' => $this->request->getPost('sla', FILTER_SANITIZE_NUMBER_INT),
            'satuan' => $this->request->getPost('satuan', FILTER_SANITIZE_SPECIAL_CHARS),
            'menit' => $this->request->getPost('menit', FILTER_SANITIZE_NUMBER_INT),
            'bobot' => $this->request->getPost('bobot', FILTER_SANITIZE_NUMBER_INT),
            'status' => $status,
            'id_user' => auth()->id(),
            'wkt_rekam' => timestamp(),
        ];

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

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

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

    //Tampilkan Form untuk Rekam Syarat Layanan
    public function new_clay()
    {
        if (priv_menu('pdklayanan', 'rekam')) {
            return view('referensi/pdklayanan/clay_form', [
                'action' => base_url('referensi/pdklayanan/create_clay'),
                'button' => 'SIMPAN DATA',
                'id' => '',
                'id_jalay' => '',
                'uraian' => '',
                'berkas' => '',
                'dd_mlay' => $this->PdkmlayModel->dd_mlay(),
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }
    //End Tampilkan Form untuk Rekam

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

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

        //validationrule
        $validationRule = [
        	'uraian' => [
		        'label' => 'Nama Dokumen',
		        'rules' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]', // Validasi required untuk input teks
		    ],
		    'berkas' => [
		        'label' => 'Berkas',
		        'rules' => [
		            'uploaded[berkas]',
		            'mime_in[berkas,application/pdf,application/x-pdf,application/acrobat]',
		            'max_size[berkas,10240]',
		        ],
		    ],
		];

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

        //collect data form
        $file = $this->request->getFile('berkas');

        //proses upload 
        $res = upload_ceisa($file);

        if ($res && $res->getStatusCode() == '200') {
            $body = json_decode($res->getBody());

            $data = [
                'id_jalay' => $this->request->getPost('id_jalay', FILTER_SANITIZE_NUMBER_INT),
                'uraian' => $this->request->getPost('uraian', FILTER_SANITIZE_SPECIAL_CHARS),
                'berkas'  => $body->data->keyFile,
            ];

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

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

    //FUNGSI UBAH---------------------
    public function edit_mlay($id)
    {
        if (priv_menu('pdklayanan', 'ubah')) {
            $row = $this->PdkmlayModel->find(decrypt_url($id));

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

            return view('referensi/pdklayanan/mlay_form', [
                'action' => base_url('referensi/pdklayanan/update_mlay'),
                'button' => 'UBAH DATA',
                'id' => encrypt_url($row->id),
                'uraian' => $row->uraian,
                'sla' => $row->sla,
                'satuan' => $row->satuan,
                'menit' => $row->menit,
                'bobot' => $row->bobot,
                'status' => $row->status,
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }

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

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

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));
        $status = !empty($this->request->getPost('status')) ? 1:0;
        $data = [
            'id'  => $id,
            'uraian' => $this->request->getPost('uraian', FILTER_SANITIZE_SPECIAL_CHARS),
            'sla' => $this->request->getPost('sla', FILTER_SANITIZE_NUMBER_INT),
            'satuan' => $this->request->getPost('satuan', FILTER_SANITIZE_SPECIAL_CHARS),
            'menit' => $this->request->getPost('menit', FILTER_SANITIZE_NUMBER_INT),
            'bobot' => $this->request->getPost('bobot', FILTER_SANITIZE_NUMBER_INT),
            'status' => $status,
            'id_user' => auth()->id(),
            'wkt_rekam' => timestamp(),
        ];

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

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

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

    //Tampilkan Form Edit Syarat Layanan
    public function edit_clay($id)
    {
        if (priv_menu('pdklayanan', 'ubah')) {
            $row = $this->PdkclayModel->find_by_id(decrypt_url($id));

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

            return view('referensi/pdklayanan/clay_form', [
                'action' => base_url('referensi/pdklayanan/update_clay'),
                'button' => 'UBAH DATA', 
                'id' => encrypt_url($row->id),
                'id_jalay' => $row->id_jalay,
                'uraian' => $row->uraian,
                'berkas' => $row->berkas,
                'dd_mlay' => $this->PdkmlayModel->dd_mlay(),
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }//End Tampilkan Form Edit Syarat Layanan

    //Proses Update Syarat Layanan
    public function update_clay()
    {
        $this->setJsonHeader();

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

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

        // Cek apakah ada file berkas yang diupload
        $file = $this->request->getFile('berkas');

        // Jika ada file yang diupload dan valid
        if ($file && $file->isValid()) {
            // Validasi file
            $fileValidationRules = [
                'berkas' => [
                    'label' => 'Berkas',
                    'rules' => [
                        'uploaded[berkas]',
                        'mime_in[berkas,application/pdf,application/x-pdf,application/acrobat]',
                        'max_size[berkas,10240]',
                    ],
                ],
            ];
            
            // Validasi file
            if (!$this->validate($fileValidationRules)) {
                return $this->fail($this->validator->getErrors(), 400);
            }

            // Proses upload file
            $res = upload_ceisa($file);
            
            if ($res && $res->getStatusCode() == '200') {
                $body = json_decode($res->getBody());
                // Tambahkan berkas ke data yang akan diupdate
                $data['berkas'] = $body->data->keyFile;
            } else {
                return $this->fail(['message' => G_UPLOAD], 400);
            }
        }

        // Validasi data lainnya (selain file)
        $dataValidationRules = [
            'uraian' => [
                'label' => 'Nama Dokumen',
                'rules' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
            ],
        ];
        
        //jika validasi gagal
        if (!$this->validate($dataValidationRules)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

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

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

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

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

    //Proses Delete Syarat Layanan
    public function delete_clay()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk hapus data
        if (!priv_menu('pdklayanan', '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->PdkclayModel->delete($del)) {
            return $this->fail($this->PdkclayModel->errors(), 500);
        }

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