<?php

namespace App\Controllers\Potensiwilayah;

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

class Calonasabah extends BaseController
{
    use ResponseTrait;

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

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

    private function ruleData($id = null)
    {
        return [
            'id' => 'trim',
            'id_kegiatan' => 'required|numeric',
            'id_produk' => 'required|numeric',
            'tgl_kegiatan' => 'required|valid_date',
            '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]',
            'foto_kegiatan' => 'permit_empty',
            'closing' => 'permit_empty|in_list[0,1]',
        ];
    }

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

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

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

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

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

        return view('potwil/calonasabah/cnas_list', [
            'rekam' => $rekam,
            'link_show' => $link_show,
            'link_rekam' => $link_rekam,
            'ubah' => $ubah,
            'link_ubah' => $link_ubah,
            'hapus' => $hapus,
            'link_hapus' => $link_hapus,
            'link_closing' => base_url('potensiwilayah/calonasabah/closing/'),
        ]);
    }

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

        $user_id = auth()->id();
        $id_kantor = $this->NasabahModel->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->NasabahModel->get_rows2($rows, $start, $filterRules, $sortOrder, $id_kantor);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
            $datas[$k]->closing_text = $v->closing == 1 ? 'Y' : 'N';
        }

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

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

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

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

        return view('potwil/calonasabah/cnas_show', [
            'back' => base_url('potensiwilayah/calonasabah'),
            '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,
        ]);
    }

    public function new()
    {
        $id_kantor = $this->NasabahModel->get_user_kantor(auth()->id());
        
        return view('potwil/calonasabah/cnas_form', [
            'action' => base_url('potensiwilayah/calonasabah/create'),
            'back' => base_url('potensiwilayah/calonasabah'),
            'button' => 'SIMPAN DATA',
            'id' => '',
            'id_kegiatan' => '',
            'id_produk' => '',
            'tgl_kegiatan' => '',
            'nama_calon' => '',
            'tgl_lahir' => '',
            'alamat' => '',
            'no_wa' => '',
            'nik' => '',
            'foto_kegiatan' => '',
            'referal' => '',
            'dd_kegiatan' => $this->NasabahModel->dd_kegiatan($id_kantor),
            'dd_produk' => $this->NasabahModel->dd_produk(),
            'id_kantor' => $id_kantor,
        ]);
    }

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

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

        $file = $this->request->getFile('foto_kegiatan');
        $foto_kegiatan = '';

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $id_user = auth()->id();
            $id_kegiatan = $this->request->getPost('id_kegiatan', FILTER_SANITIZE_NUMBER_INT);
            $nama_calon = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $this->request->getPost('nama_calon', FILTER_SANITIZE_SPECIAL_CHARS)));
            $timestamp = date('YmdHis');
            
            $newFileName = $id_user . $id_kegiatan . $nama_calon . $timestamp . '.' . $file->getExtension();
            
            if ($file->move(ROOTPATH . 'public/fotokegiatan', $newFileName)) {
                $foto_kegiatan = $newFileName;
            } else {
                return $this->fail(['message' => 'Gagal upload foto'], 500);
            }
        }

        $data = [
            'id_kegiatan' => $this->request->getPost('id_kegiatan', FILTER_SANITIZE_NUMBER_INT),
            'id_produk' => $this->request->getPost('id_produk', FILTER_SANITIZE_NUMBER_INT),
            'tgl_kegiatan' => $this->request->getPost('tgl_kegiatan', FILTER_SANITIZE_SPECIAL_CHARS),
            '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),
            'foto_kegiatan' => $foto_kegiatan,
            'referal' => $this->request->getPost('referal', FILTER_SANITIZE_SPECIAL_CHARS),
            'id_rek' => auth()->id(),
            'wkt_rek' => date('Y-m-d H:i:s'),
        ];

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

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

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

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

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

        $id_kantor = $this->NasabahModel->get_user_kantor(auth()->id());
        
        return view('potwil/calonasabah/cnas_form', [
            'action' => base_url('potensiwilayah/calonasabah/update'),
            'back' => base_url('potensiwilayah/calonasabah'),
            'button' => 'UBAH DATA', 
            'id' => encrypt_url($row->id),
            'id_kegiatan' => $row->id_kegiatan,
            'id_produk' => $row->id_produk,
            '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,
            'dd_kegiatan' => $this->NasabahModel->dd_kegiatan($id_kantor),
            'dd_produk' => $this->NasabahModel->dd_produk(),
            'id_kantor' => $id_kantor,
        ]);
    }

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

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

        $id = decrypt_url(trim($this->request->getPost('id')));
        
        $file = $this->request->getFile('foto_kegiatan');
        $foto_kegiatan = $this->request->getPost('foto_kegiatan_lama');

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $id_user = auth()->id();
            $id_kegiatan = $this->request->getPost('id_kegiatan', FILTER_SANITIZE_NUMBER_INT);
            $nama_calon = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $this->request->getPost('nama_calon', FILTER_SANITIZE_SPECIAL_CHARS)));
            $timestamp = date('YmdHis');
            
            $newFileName = $id_user . $id_kegiatan . $nama_calon . $timestamp . '.' . $file->getExtension();
            
            if ($file->move(ROOTPATH . 'public/fotokegiatan', $newFileName)) {
                if ($foto_kegiatan && file_exists(ROOTPATH . 'public/fotokegiatan/' . $foto_kegiatan)) {
                    unlink(ROOTPATH . 'public/fotokegiatan/' . $foto_kegiatan);
                }
                $foto_kegiatan = $newFileName;
            } else {
                return $this->fail(['message' => 'Gagal upload foto'], 500);
            }
        }

        $data = [
            'id'  => $id,
            'id_kegiatan' => $this->request->getPost('id_kegiatan', FILTER_SANITIZE_NUMBER_INT),
            'id_produk' => $this->request->getPost('id_produk', FILTER_SANITIZE_NUMBER_INT),
            'tgl_kegiatan' => $this->request->getPost('tgl_kegiatan', FILTER_SANITIZE_SPECIAL_CHARS),
            '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),
            'foto_kegiatan' => $foto_kegiatan,
            'referal' => $this->request->getPost('referal', FILTER_SANITIZE_SPECIAL_CHARS),
        ];

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

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

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

    public function closing($id)
    {
        $row = $this->NasabahModel->find_by_id(decrypt_url($id));

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

        $id_kantor = $this->NasabahModel->get_user_kantor(auth()->id());
        
        return view('potwil/calonasabah/closing_form', [
            'action' => base_url('potensiwilayah/calonasabah/proses_closing'),
            'back' => base_url('potensiwilayah/calonasabah'),
            'button' => 'CLOSING', 
            'id' => encrypt_url($row->id),
            'id_kegiatan' => $row->id_kegiatan,
            'id_produk' => $row->id_produk,
            '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,
            '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,
            'id_kantor' => $id_kantor,
        ]);
    }

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

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

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

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

        $id = decrypt_url(trim($this->request->getPost('id')));
        
        // Validation rules for closing - validate first before file operations
        $rules = [
            'tgl_closing' => 'required|valid_date',
            'email' => 'required|valid_email|max_length[100]',
            'maiden_name' => 'required|max_length[150]',
            'pekerjaan' => 'required|max_length[150]',
            'foto_ktp' => 'uploaded[foto_ktp]|max_size[foto_ktp,5120]|ext_in[foto_ktp,jpg,jpeg,png,gif]',
            'foto_closing' => 'uploaded[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);
        }

        // Handle file uploads after validation
        $foto_ktp = '';
        $foto_closing = '';
        
        $file_ktp = $this->request->getFile('foto_ktp');
        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)) {
                $foto_ktp = $newFileName;
            } else {
                return $this->fail(['message' => 'Gagal upload foto KTP'], 500);
            }
        }
        
        $file_closing = $this->request->getFile('foto_closing');
        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)) {
                $foto_closing = $newFileName;
            } else {
                return $this->fail(['message' => 'Gagal upload foto closing'], 500);
            }
        }

        // Generate next CIF
        $no_cif = $this->NasabahModel->generateNextCif();

        $data = [
            'no_cif' => $no_cif,
            'tgl_closing' => $this->request->getPost('tgl_closing', FILTER_SANITIZE_SPECIAL_CHARS),
            'emailx' => $this->request->getPost('email', FILTER_SANITIZE_EMAIL),
            'maiden' => $this->request->getPost('maiden_name', 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,
            'closing' => 1,
            'id_clo' => auth()->id(),
            'wkt_clo' => date('Y-m-d H:i:s'),
        ];

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

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

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

        $id_kegiatan = $this->request->getPost('id_kegiatan');
        $data = $this->NasabahModel->get_kegiatan_detail($id_kegiatan);

        return json_encode($data);
    }
}
