<?php

namespace App\Controllers\Potensiwilayah;

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

class Datanasabah extends BaseController
{
    use ResponseTrait;

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

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

    private function ruleData($id = null)
    {
        return [
            'id' => 'trim',
            'nama_calon' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[100]',
            'tgl_lahir' => 'required|valid_date',
            'alamat' => 'required|max_length[200]',
            'no_wa' => 'required|regex_match[/^[0-9]+$/]|max_length[15]',
            'nik' => 'required|regex_match[/^[0-9]+$/]|max_length[16]',
            'emailx' => 'required|valid_email|max_length[100]',
            'maiden' => 'required|max_length[150]',
            'pekerjaan' => 'required|max_length[150]',
            'ket' => 'permit_empty|max_length[200]',
        ];
    }

    public function index()
    {
        $links = genlinks('potensiwilayah', 'datanasabah');

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

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

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

        return view('potwil/nasabah/nasabah_list', [
            'link_show' => $link_show,
            'ubah' => $ubah,
            'link_ubah' => $link_ubah,
            'hapus' => $hapus,
            'link_hapus' => $link_hapus,
        ]);
    }

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

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

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

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

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

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

        return view('potwil/nasabah/nasabah_show', [
            'back' => base_url('potensiwilayah/datanasabah'),
            'id' => encrypt_url($row->id),
            'id_kegiatan' => $row->id_kegiatan,
            'nama_giat' => $row->nama_giat,
            'nama_kegiatan' => $row->nama_kegiatan,
            'nama_lokasi' => $row->nama_lokasi,
            'nama_kat' => $row->nama_kat,
            'tgl_1' => $row->tgl_1,
            'tgl_2' => $row->tgl_2,
            'id_produk' => $row->id_produk,
            'uraian' => $row->uraian,
            'tgl_kegiatan' => $row->tgl_kegiatan,
            'nama_calon' => $row->nama_calon,
            'tgl_lahir' => $row->tgl_lahir,
            'alamat' => $row->alamat,
            'no_wa' => $row->no_wa,
            'nik' => $row->nik,
            'foto_kegiatan' => $row->foto_kegiatan,
            'referal' => $row->referal,
            'closing' => $row->closing,
            'no_cif' => $row->no_cif,
            'tgl_closing' => $row->tgl_closing,
            'emailx' => $row->emailx,
            'maiden' => $row->maiden,
            'pekerjaan' => $row->pekerjaan,
            'ket' => $row->ket,
            'foto_ktp' => $row->foto_ktp,
            'foto_closing' => $row->foto_closing,
        ]);
    }

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

        if (!$row) {
            exit('Data tidak ditemukan');
        }
        
        return view('potwil/nasabah/nasabah_form', [
            'action' => base_url('potensiwilayah/datanasabah/update'),
            'back' => base_url('potensiwilayah/datanasabah'),
            'button' => 'UBAH DATA', 
            'id' => encrypt_url($row->id),
            'nama_calon' => $row->nama_calon,
            'tgl_lahir' => $row->tgl_lahir,
            'alamat' => $row->alamat,
            'no_wa' => $row->no_wa,
            'nik' => $row->nik,
            'emailx' => $row->emailx,
            'maiden' => $row->maiden,
            'pekerjaan' => $row->pekerjaan,
            'ket' => $row->ket,
            'foto_ktp' => $row->foto_ktp,
            'foto_closing' => $row->foto_closing,
        ]);
    }

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

        if (!priv_menu('datanasabah', 'ubah')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        $id = decrypt_url(trim($this->request->getPost('id')));
        
        // Validation rules for update
        $rules = [
            'nama_calon' => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[100]',
            'tgl_lahir' => 'required|valid_date',
            'alamat' => 'required|max_length[200]',
            'no_wa' => 'required|regex_match[/^[0-9]+$/]|max_length[15]',
            'nik' => 'required|regex_match[/^[0-9]+$/]|max_length[16]',
            'emailx' => 'required|valid_email|max_length[100]',
            'maiden' => 'required|max_length[150]',
            'pekerjaan' => 'required|max_length[150]',
            'ket' => 'permit_empty|max_length[200]',
        ];

        // Handle optional file uploads
        $foto_ktp_lama = $this->request->getPost('foto_ktp_lama');
        $foto_closing_lama = $this->request->getPost('foto_closing_lama');
        $foto_ktp = $foto_ktp_lama;
        $foto_closing = $foto_closing_lama;
        
        $file_ktp = $this->request->getFile('foto_ktp');
        if ($file_ktp && $file_ktp->isValid() && !$file_ktp->hasMoved()) {
            // Add validation for uploaded file
            $rules['foto_ktp'] = 'max_size[foto_ktp,5120]|ext_in[foto_ktp,jpg,jpeg,png,gif]';
        }
        
        $file_closing = $this->request->getFile('foto_closing');
        if ($file_closing && $file_closing->isValid() && !$file_closing->hasMoved()) {
            // Add validation for uploaded file
            $rules['foto_closing'] = 'max_size[foto_closing,5120]|ext_in[foto_closing,jpg,jpeg,png,gif]';
        }

        if (!$this->validate($rules)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        // Process foto_ktp upload if new file exists
        if ($file_ktp && $file_ktp->isValid() && !$file_ktp->hasMoved()) {
            $id_user = auth()->id();
            $timestamp = date('YmdHis');
            $newFileName = $id_user . '_ktp_' . $id . '_' . $timestamp . '.' . $file_ktp->getExtension();
            
            if ($file_ktp->move(ROOTPATH . 'public/fotoktp', $newFileName)) {
                // Delete old file if exists
                if ($foto_ktp_lama && file_exists(ROOTPATH . 'public/fotoktp/' . $foto_ktp_lama)) {
                    unlink(ROOTPATH . 'public/fotoktp/' . $foto_ktp_lama);
                }
                $foto_ktp = $newFileName;
            } else {
                return $this->fail(['message' => 'Gagal upload foto KTP'], 500);
            }
        }

        // Process foto_closing upload if new file exists
        if ($file_closing && $file_closing->isValid() && !$file_closing->hasMoved()) {
            $id_user = auth()->id();
            $timestamp = date('YmdHis');
            $newFileName = $id_user . '_closing_' . $id . '_' . $timestamp . '.' . $file_closing->getExtension();
            
            if ($file_closing->move(ROOTPATH . 'public/fotoclosing', $newFileName)) {
                // Delete old file if exists
                if ($foto_closing_lama && file_exists(ROOTPATH . 'public/fotoclosing/' . $foto_closing_lama)) {
                    unlink(ROOTPATH . 'public/fotoclosing/' . $foto_closing_lama);
                }
                $foto_closing = $newFileName;
            } else {
                return $this->fail(['message' => 'Gagal upload foto closing'], 500);
            }
        }

        $data = [
            'nama_calon' => $this->request->getPost('nama_calon', FILTER_SANITIZE_SPECIAL_CHARS),
            'tgl_lahir' => $this->request->getPost('tgl_lahir', FILTER_SANITIZE_SPECIAL_CHARS),
            'alamat' => $this->request->getPost('alamat', FILTER_SANITIZE_SPECIAL_CHARS),
            'no_wa' => $this->request->getPost('no_wa', FILTER_SANITIZE_SPECIAL_CHARS),
            'nik' => $this->request->getPost('nik', FILTER_SANITIZE_SPECIAL_CHARS),
            'emailx' => $this->request->getPost('emailx', FILTER_SANITIZE_EMAIL),
            'maiden' => $this->request->getPost('maiden', FILTER_SANITIZE_SPECIAL_CHARS),
            'pekerjaan' => $this->request->getPost('pekerjaan', FILTER_SANITIZE_SPECIAL_CHARS),
            'ket' => $this->request->getPost('ket', FILTER_SANITIZE_SPECIAL_CHARS),
            'foto_ktp' => $foto_ktp,
            'foto_closing' => $foto_closing,
        ];

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

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

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

        if (!priv_menu('datanasabah', '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->DatanasabahModel->delete($del)) {
            return $this->fail($this->DatanasabahModel->errors(), 500);
        } else {
            return $this->respond(['message' => count($del).lang('App.delete_success')]);
        }
    }
}
