<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
    
    public function __construct(){
        parent::__construct();      
        $this->load->model('M_register');
        $this->load->library('mailer');
        $this->load->model('M_template_email');
        $this->load->library('whatsapplib');
    }
    private function send_mail($penerima,$pesan,$subjek){
        $email_penerima = $penerima;
        
        $logo = base_url('assets/img/logo.png');
        $template_email = $this->M_template_email->select_data_template_email()->row_array();
        // $attachment = $_FILES['attachment'];
        $content = $this->load->view('template_email/content_mail', array('pesan'=>$pesan,'logo'=>$logo,'template_email'=>$template_email), true); // Ambil isi file content.php dan masukan ke variabel $content
        $sendmail = array(
          'email_penerima'=>$email_penerima,
          'subjek'=>$subjek,
          'content'=>$content
          // 'attachment'=>$attachment
        );
        $send = $this->mailer->send($sendmail); // Panggil fungsi send yang ada di librari Mailer
        // echo "<b>".$send['status']."</b><br />";
        // echo $send['message'];
        // echo "<br /><a href='".base_url("index.php/email")."'>Kembali ke Form</a>";
        // return $send;
      }
	public function add_user(){
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "0123456789";
        $max = strlen($codeAlphabet) - 1;
        for ($i=0; $i < 8; $i++) {
            $token .= $codeAlphabet[mt_rand(0, $max)];
        } 
        $data['username'] = $this->input->post('username',TRUE);
        $data['email'] = $this->input->post('email',TRUE);
        $data['tlp'] = "62".($this->input->post('tlp',TRUE)+0);
        $data['unit_misioner'] = explode(",", $this->input->post('unit_misioner',TRUE))[0];
        $data['nama_unit_misioner'] = explode(",", $this->input->post('unit_misioner',TRUE))[1];
        $data['password'] = md5($this->input->post('password',TRUE));
        $data['kode_user'] = $token;
        ///////////////
        $template_email = $this->M_template_email->select_data_template_email()->row_array();
        ///////////////////
        ////////////pesan Admin////////////////
        $subjek_admin = $template_email['sjk_adm_reg'];
        $link_terima ='<a href="'.base_url().'register/terima/'.$token.'" class="btn btn-success"> Terima </a>';
        $link_tolak  ='<a href="'.base_url().'register/tolak/'.$token.'" class="btn btn-danger"> TOLAK </a>';
        $created_at = date("j F Y g:i a");
        $str = array("%username%","%unit_misioner%","%email%","%created_at%","%link_terima%","%link_tolak%");
        $rplc =array($data['username'],$data['nama_unit_misioner'],$data['email'],$created_at,$link_terima,$link_tolak);
        $pesan_admin = str_replace($str,$rplc,$template_email['msg_adm_reg']);



        $pesan_admin_wa = "WhatsApp Gateway \n[Pesan Otomatis Satu Arah] \n \nDear Admin cPKA,\n \nSilahkan konfirmasi registrasi akun user berikut:\nUser Name : ".$data['username']."\nUnit Misioner : ".$data['nama_unit_misioner']."\nEmail : ".$data['email']."\nWaktu Registrasi : ".$created_at;
        /////////////////////////////////////
        $subjek_user = $template_email['sjk_user_reg'];
        $pesan_user =$template_email['msg_user_reg'];
        $cek_email  = $this->M_register->cek_email($data)->num_rows();
        if($cek_email > 0){
            $cek["cek"] = "ada"; 
        }else{
            $result = $this->M_register->add_user($data);
            if ($result) {
                $ambil_email_admin = $this->M_register->ambil_email_admin($data)->result_array();
                for ($i=0; $i < count($ambil_email_admin); $i++) { 
                    $this->send_mail($ambil_email_admin[$i]['email'],$pesan_admin,$subjek_admin);
                }
                $ambil_tlp_admin = $this->M_register->ambil_tlp_admin($data)->result_array();
                for ($i=0; $i < count($ambil_tlp_admin); $i++) { 
                    // $this->send_mail($ambil_tlp_admin[$i]['tlp'],$pesan_admin,$subjek_admin);
                    $this->whatsapplib->sendwa($ambil_tlp_admin[$i]['tlp'],$pesan_admin_wa);
                }

                $this->send_mail($data['email'],$pesan_user,$subjek_user);
                $msgwa_user = "WhatsApp Gateway \n[Pesan Otomatis Satu Arah] \n \nMohon Menunggu,\n \nRegistrasi akun cPKA anda akan segera diproses oleh admin cPKA.\n \nBerikut detail akun anda:\nUser Name : ".$data['username']."\nUnit Misioner : ".$data['nama_unit_misioner']."\nEmail : ".$data['email']."\nWaktu Registrasi : ".$created_at;
                
                $this->whatsapplib->sendwa($data['tlp'],$msgwa_user);
                $cek["cek"] = "ok";
            }else{
                $cek["cek"] = "gagal";
            }
        }
        echo json_encode($cek);
    }
	public function terima($param){
        $cek_regist = $this->M_register->cek_regist($param)->num_rows();
        if($cek_regist == 0){
            echo "Maaf Data Sudah Direspon";
        }else{
            $ambil_email = $this->M_register->ambil_email($param)->row_array();
            $ambil_tlp   = $this->M_register->ambil_tlp($param)->row_array();
            $respon  = $this->M_register->terima($param);
            if($respon){
                $template_email = $this->M_template_email->select_data_template_email()->row_array();
                $subjek = $template_email['sjk_user_reg_acc'];
                $pesan = str_replace("%login%",'<a href="'.base_url('login.aspx').'">Login</a>',$template_email['msg_user_reg_acc']);
                $this->send_mail($ambil_email['email'],$pesan,$subjek);
                $pesan_wa = "Registrasi disetujui oleh admin PKA\nSilahkan Login : https://pka.gpibcinere.org/";
                $this->whatsapplib->sendwa($ambil_tlp['tlp'],$pesan_wa);
                echo "Anda berhasil menerima user";
            }else{
                echo "Gagal Proses";
            }
        }
    }
    public function tolak($param){
        $cek_regist = $this->M_register->cek_regist($param)->num_rows();
        if($cek_regist == 0){
            echo "Maaf Data Sudah Direspon";
        }else{
            $ambil_email = $this->M_register->ambil_email($param)->row_array();
            $ambil_tlp   = $this->M_register->ambil_tlp($param)->row_array();
            $respon  = $this->M_register->tolak($param);
            if($respon){
                $template_email = $this->M_template_email->select_data_template_email()->row_array();
                $subjek = $template_email['sjk_user_reg_rjk'];
                $pesan = $template_email['msg_user_reg_rjk'];
                $this->send_mail($ambil_email['email'],$pesan,$subjek);
                $pesan_wa = "Maaf, registrasi ditolak oleh admin PKA";
                $this->whatsapplib->sendwa($ambil_tlp['tlp'],$pesan_wa);
                echo "Anda berhasil Menolak user";
            }else{
                echo "Gagal Proses";
            }
        }
    }
}
