<?php

namespace App\Controllers\Cusen;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Shield\Entities\User;

class KirimPesan extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->CnasModel = model('App\Models\Potensiwilayah\NasabahModel'); //yg sdh closing
        $this->NasModel = model('App\Models\Potensiwilayah\DatanasabahModel'); //yg sdh closing
        $this->PesanModel = model('App\Models\Cusen\PesanModel');
        $this->PesanChildModel = model('App\Models\Cusen\PesanChildModel');
    }

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

    public function index()
    {
        //cek privilege dan link
        if (priv_menu('kirim_pesan', 'rekam')) {
            $rekam = 1;
            $link_rekam = base_url('cusen/kirim_pesan/send_wa');
        } else {
            $rekam = 0;
            $link_rekam = '';
        }

        return view('cusen/kirim/user_list', [
            'rekam' => $rekam,
            'action' => $link_rekam,
        ]);
    }

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

        $page        = $this->request->getPost('page') ?: 1;
        $rows        = $this->request->getPost('rows') ?: 10;
        $sort        = $this->request->getPost('sort');
        $order       = $this->request->getPost('order');
        $filterRules = $this->request->getPost('filterRules');
        $filter_type = $this->request->getPost('filter_type') ?: 'all'; // all, closing, belum_closing
        $start       = ($page - 1) * $rows;

        $user_id = auth()->id();
        $id_kantor = $this->CnasModel->kantor_user($user_id);

        if ($sort && $order) {
            $sortOrder = multi_sort($sort, $order);
        } else {
            $sortOrder = multi_sort('id', 'ASC');
        }

        // Pilih model berdasarkan filter
        switch ($filter_type) {
            case 'closing':
                // Gunakan DatanasabahModel untuk yang sudah closing
                $datas = $this->NasModel->get_rows2($rows, $start, $filterRules, $sortOrder, $id_kantor);
                $total = $this->NasModel->get_total2($filterRules, $id_kantor);
                break;
            case 'belum_closing':
                // Gunakan NasabahModel untuk yang belum closing
                $datas = $this->CnasModel->get_rows2($rows, $start, $filterRules, $sortOrder, $id_kantor);
                $total = $this->CnasModel->get_total2($filterRules, $id_kantor);
                break;
            default:
                // Gabungan semua data
                $datas = $this->getAllNasabah($rows, $start, $filterRules, $sortOrder, $id_kantor);
                $total = $this->getTotalAllNasabah($filterRules, $id_kantor);
                break;
        }

        foreach ($datas as $k => $v) {
            $datas[$k]->id = encrypt_url($v->id);
            $datas[$k]->closing_text = isset($v->closing) ? ($v->closing == 1 ? 'Y' : 'N') : 'N';
        }

        $res['total'] = $total;
        $res['rows']  = $datas;

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

    private function getAllNasabah($limit, $start, $filterRules, $sortOrder, $id_kantor)
    {
        $db = \Config\Database::connect();
        $builder = $db->table('nasabah_calon as n');
        $builder->select('n.id, n.nama_calon, n.nik, n.tgl_lahir, n.tgl_kegiatan, n.no_wa, n.closing, n.no_cif, n.tgl_closing, n.emailx, p.nama_giat, l.nama_lokasi, u.username, n.wkt_rek');
        $builder->join('promosi_main as p', 'n.id_kegiatan = p.id', 'left');
        $builder->join('lokasi_main as l', 'p.id_lokasi = l.id', 'left');
        $builder->join('users as u', 'n.id_rek = u.id', 'left');
        $builder->where('p.id_kantor', $id_kantor);
        
        if ($filterRules) {
            $this->applyFilters($builder, $filterRules);
        }

        if ($sortOrder) {
            $builder->orderBy($sortOrder);
        } else {
            $builder->orderBy('n.id', 'ASC');
        }

        $builder->limit($limit, $start);
        return $builder->get()->getResult();
    }

    private function getTotalAllNasabah($filterRules, $id_kantor)
    {
        $db = \Config\Database::connect();
        $builder = $db->table('nasabah_calon as n');
        $builder->join('promosi_main as p', 'n.id_kegiatan = p.id', 'left');
        $builder->join('lokasi_main as l', 'p.id_lokasi = l.id', 'left');
        $builder->join('users as u', 'n.id_rek = u.id', 'left');
        $builder->where('p.id_kantor', $id_kantor);
        
        if ($filterRules) {
            $this->applyFilters($builder, $filterRules);
        }

        return $builder->countAllResults();
    }

    private function applyFilters($builder, $filterRules)
    {
        $filterRules = json_decode($filterRules);
        
        foreach ($filterRules as $filter) {
            $value = $filter->value;
            $pecah = explode(';', $value);
            if (count($pecah) > 1) {
                $builder->groupStart();
                foreach ($pecah as $p) {
                    if (trim($p) <> '') {
                        $field = $this->getFieldName($filter->field);
                        if (trim($filter->field) == 'closing') {
                            $builder->orWhere($field, trim(urldecode($p)));
                        } else {
                            $builder->orLike($field, trim(urldecode($p)));
                        }
                    }
                }
                $builder->groupEnd();
            } else {
                $field = $this->getFieldName($filter->field);
                if (trim($filter->field) == 'closing') {
                    $builder->where($field, trim(urldecode($value)));
                } else {
                    $builder->like($field, trim(urldecode($value)));
                }
            }
        }
    }

    private function getFieldName($field)
    {
        $fieldMap = [
            'nama_calon' => 'n.nama_calon',
            'nik' => 'n.nik',
            'tgl_lahir' => 'n.tgl_lahir',
            'tgl_kegiatan' => 'n.tgl_kegiatan',
            'no_wa' => 'n.no_wa',
            'closing' => 'n.closing',
            'no_cif' => 'n.no_cif',
            'tgl_closing' => 'n.tgl_closing',
            'emailx' => 'n.emailx',
            'nama_giat' => 'p.nama_giat',
            'nama_lokasi' => 'l.nama_lokasi',
            'username' => 'u.username',
            'wkt_rek' => 'n.wkt_rek'
        ];
        
        return $fieldMap[$field] ?? $field;
    }

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

        $user_id = auth()->id();
        $id_kantor = $this->CnasModel->kantor_user($user_id);

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

        //collect data form
        $ids = trim($this->request->getPost('id_penerima'));
        $ar_id = str_getcsv($ids);

        //cek apakah ada penerima
        if (count($ar_id) == 0) {
            return $this->fail(['message' => NOT_COMPLETE], 400);
        }

        //validasi require
        if (!$this->validatePesan()) {
            return $this->fail($this->validation->getErrors(), 400);
        }

        //jika lolos validasi, simpan data pesan
        $pesan = $this->request->getPost('pesan', FILTER_SANITIZE_SPECIAL_CHARS);
        $data = [
            'judul' => $this->request->getPost('judul', FILTER_SANITIZE_SPECIAL_CHARS),
            'isi'   => $pesan,
            'id_kantor' => $id_kantor,
            'id_user' => auth()->id(),
            'wkt_rekam' => timestamp(),
        ];

        //proses insert data master
        $newID = $this->PesanModel->insert($data);

        //proses kirim pesan
        $datac = [];
        foreach ($ar_id as $k) {
            sleep(1);
            $id = decrypt_url($k);
            //ambil data nama dan nomor wa dari nasabah
            $dtu = $this->CnasModel->find_by_id($id);
            if (!$dtu) {
                $dtu = $this->NasModel->find_by_id($id);
            }
            
            if ($dtu) {
                $msg = 'Halo Kak.. '.$dtu->nama_calon.', '.$pesan.' (G-Round Pegadaian)';

                // Default kirim pakai WA Resmi Tasya ===================
                $body = send_wax($dtu->no_wa, $msg);

                //print_r($body); exit;

                $agen = 'G-Round';

                //buat array data child pesan
                $datac[] = array(
                    'id_pesan' => $newID,
                    'id_penerima' => $id,
                    'agen' => $agen,
                    'wkt_kirim' => timestamp(),
                );
            }
        } //end loop kirim pesan

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

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

    private function validatePesan()
    {
        $rules = [
            'judul'  => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
            'pesan' => 'required|regex_match[/^[a-zA-Z0-9\s.,@\-\/%?:]*$/]',
        ];
        return $this->validate($rules);
    }
}