
<?php defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-Type: text/html; charset=UTF-8");
/**
 * 인클루드 class
 *
 * cm_controller: 부모 Class(CI_Controller 확장한 custome class)
 */
include_once(APPPATH.'core/m/cm_controller.php');
class member extends cm_Controller {


	function fn_login(){


		$this->load->helper('crossmap/tool_helper');
		$redir = $this->input->get('redir');
		# view
		return $this->load->view('/m/member/login', array("redir"=>$redir), true);

	}


	function fn_change_pw(){


		$this->load->helper('crossmap/tool_helper');
		$redir = $this->input->get('redir');
		# view
		return $this->load->view('/m/member/change_pw', array("redir"=>$redir), true);

	}


	function fn_find_id(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/find_id', null, true);

	}
	function fn_find_id_with_email(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/find_id_with_email', null, true);

	}

	function fn_find_pw(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/find_pw', null, true);

	}
	function fn_find_pw_with_email(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/find_pw_with_email', null, true);

	}

	function fn_join(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/join_1', null, true);

	}

	function fn_join_1(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/join_1', null, true);

	}

	function fn_join_2(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/join_2', null, true);

	}
	function fn_join_4(){


		$this->load->helper('crossmap/tool_helper');
		# view
		return $this->load->view('/m/member/join_3', null, true);

	}


	function fn_secession(){


		$this->load->helper('crossmap/tool_helper');
		#view
		return $this->load->view('/m/member/secession',null, true);

	}



	#---------------------------------------------------------------------------
    # PURPOSE :	아이디중복체크
    # CREATE  :	2018-04-04
    #---------------------------------------------------------------------------
	function fn_ajax_member_id_check_proc() {
        # request
        $member_id             = trim($this->input->get_post('member_id', TRUE));

        # model
        $this->load->model('web/m_member');
        $member_count   = $this->m_member->member_where_member_id_count($member_id);

        if($member_count == 0) {
            $return_data['result'] = array('result_code' => '0000');
        } else {
            $return_data['result'] = array('result_code' => '9999');
        }

        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }


    #---------------------------------------------------------------------------
    # PURPOSE :	일반회원 로그인
    # CREATE  :	2018-04-05
    #---------------------------------------------------------------------------
	function fn_ajax_login_proc(){

        $this->load->helper('cookie');

        # Request
        $member_id  = trim($this->input->get_post('member_id', TRUE));    // 아이디
        $member_pwd = trim($this->input->get_post('member_pwd', TRUE));   // 비밀번호
		$save_login = trim($this->input->get_post('save_login', TRUE));
		$save_id = trim($this->input->get_post('save_id', TRUE));

		if($save_id == 'Y'){
			set_cookie('crossmap_save_login_id', $member_id, 86400 * 90);
		}
		else{
			set_cookie('crossmap_save_login_id','',1);
		}

        # valid Check
        if (empty($member_id) == true)      throw new Cm_Exception('json', '9999', '회원아이디와 비밀번호를 확인해주세요.');
        if (empty($member_pwd) == true)     throw new Cm_Exception('json', '9999', '회원아이디와 비밀번호를 확인해주세요.');




        # 로그인
        $req_data = array();
        $req_data['member_id']  = $member_id;
        $req_data['member_pwd'] = $member_pwd;

        # model
        $this->load->model('web/m_member');
        $result    = $this->m_member->member_join_member_group_where_member_id_member_pwd_select($req_data);
        if(count($result) == 0) {
            throw new Cm_Exception('json', '9999', '회원아이디와 비밀번호를 확인해주세요.');
        }

        # 비밀번호 변경확인
        $now_date =  date("Y-m-d");
        $last_pwd_change_date = date("Y-m-d", strtotime($result['last_pwd_change_date'].' + 3month'));
		$code = '0000';
        if($now_date >= $last_pwd_change_date) {
			$code = '1111';

        }


        $result['save_login'] = $save_login;
        $this->load->library('comm');
        $msg = $this->comm->fn_login_proc($result);
        

        $return_data = array();
		$return_data['result'] = array('code' => $code, 'msg'=>$msg);


        # view
        return $this->load->view('/web/comm/result_json', $return_data);
    }

    #---------------------------------------------------------------------------
    # PURPOSE :	로그아웃
    # CREATE  :	2018-04-10
    #---------------------------------------------------------------------------
    function fn_logout_proc(){

        $this->load->helper('url');

        $this->load->library('comm');
        $this->comm->fn_logout_proc();

        # 메인으로 이동
		redirect($_SERVER['HTTP_REFERER']);
	}


    #---------------------------------------------------------------------------
    # PURPOSE :	비밀번호 확인
    # CREATE  :	2018-04-11
    #---------------------------------------------------------------------------
    function fn_ajax_password_check_proc(){

        # Request
        $member_id  = trim($this->input->get_post('member_id', TRUE));    // 아이디
        $member_pwd = trim($this->input->get_post('member_pwd', TRUE));   // 비밀번호


         # 로그인
        $req_data = array();
        $req_data['member_id']  = $member_id;
        $req_data['member_pwd'] = $member_pwd;

        # model
        $this->load->model('web/m_member');
        $result    = $this->m_member->member_join_member_group_where_member_id_member_pwd_select($req_data);
        if(count($result) == 0) {
            throw new Cm_Exception('json', '9999', '비밀번호를 확인해주세요.');
        }
        
        $this->load->helper('cookie');
        set_cookie('crossmap_passwd_check', 'Y', 0);

        $return_data = array();
        $return_data['result'] = array('code' => '0000');

        # view
        return $this->load->view('/web/comm/result_json', $return_data);
	}



	#---------------------------------------------------------------------------
    # PURPOSE : 회원가입
    # CREATE  :	2018-04-24
    #---------------------------------------------------------------------------
	function fn_member_join_proc() {

		# Request
		$social_id              = trim($this->input->get_post('social_id', TRUE));
		$sns_profile_img        = trim($this->input->get_post('sns_profile_img', TRUE));
		$is_mobile_auth         = trim($this->input->get_post('is_mobile_auth', TRUE));
		$member_gender          = trim($this->input->get_post('member_gender', TRUE));
		$parent_gender          = trim($this->input->get_post('parent_gender', TRUE));
		$is_parent_auth         = trim($this->input->get_post('is_parent_auth', TRUE));
		$is_under14             = trim($this->input->get_post('is_under14', TRUE));
		$agree1                 = trim($this->input->get_post('agree1', TRUE));
		$agree2                 = trim($this->input->get_post('agree2', TRUE));
		$agree3                 = trim($this->input->get_post('agree3', TRUE));
		$member_id              = trim($this->input->get_post('member_id', TRUE));
		$member_pwd             = trim($this->input->get_post('member_pwd', TRUE));
		$member_name            = trim($this->input->get_post('member_name', TRUE));
		$birth_year             = trim($this->input->get_post('birth_year', TRUE));
		$birth_month            = trim($this->input->get_post('birth_month', TRUE));
		$birth_day              = trim($this->input->get_post('birth_day', TRUE));
		$member_calendar        = trim($this->input->get_post('member_calendar', TRUE));
		$parent_name            = trim($this->input->get_post('parent_name', TRUE));
		$parent_mobile_company  = trim($this->input->get_post('parent_mobile_company', TRUE));
		$parent_mobile          = trim($this->input->get_post('parent_mobile', TRUE));
		$under14_member_email   = trim($this->input->get_post('under14_member_email', TRUE));
		$email1                 = trim($this->input->get_post('email1', TRUE));
		$email2                 = trim($this->input->get_post('email2', TRUE));
		$country_phone_no       = trim($this->input->get_post('country_phone_no', TRUE));
		$mobile1                = trim($this->input->get_post('mobile1', TRUE));
		$mobile2                = trim($this->input->get_post('mobile2', TRUE));
		$mobile3                = trim($this->input->get_post('mobile3', TRUE));
		$member_church          = trim($this->input->get_post('member_church', TRUE));
		$etc1                   = trim($this->input->get_post('etc1', TRUE));
		$etc2                   = trim($this->input->get_post('etc2', TRUE));
		$etc3                   = trim($this->input->get_post('etc3', TRUE));
		$etc4                   = trim($this->input->get_post('etc4', TRUE));
		$etc5                   = trim($this->input->get_post('etc5', TRUE));
		$mobile_CI              = trim($this->input->get_post('mobile_CI', TRUE));
		$under14_member_name    = trim($this->input->get_post('under14_member_name', TRUE));

		# helper
		$this->load->helper('url');
		$this->load->helper('cookie');


		# valid check
		$this->load->library('form_validation');
		$this->form_validation->set_rules('agree1', '', 'required|in_list[Y]');
		$this->form_validation->set_rules('agree2', '', 'required|in_list[Y]');
		$this->form_validation->set_rules('agree3', '', 'required|in_list[Y]');
		$this->form_validation->set_rules('member_gender', '', 'required');
		if($social_id == '') {
			$this->form_validation->set_rules('member_id', '', 'required');
			$this->form_validation->set_rules('member_pwd', '', 'required');
		}
		$this->form_validation->set_rules('member_name', '', 'required');
		$this->form_validation->set_rules('birth_year', '', 'required');
		$this->form_validation->set_rules('birth_month', '', 'required');
		$this->form_validation->set_rules('birth_day', '', 'required');
		$this->form_validation->set_rules('member_calendar', '', 'required');
		$this->form_validation->set_rules('is_mobile_auth', '', 'required|in_list[Y]');
		$this->form_validation->set_rules('mobile_CI', '', 'required');
		if($this->form_validation->run() == false){
			gf_alert("잘못된 접근입니다.1", '/');

//			print_r($this->input->get_post());
			exit;
		}

		$parent_CI = '';$parent_real_name = '';
		if($is_under14=='Y') {  // 14세 미만
			$this->form_validation->set_rules('parent_name', '', 'required');
			$this->form_validation->set_rules('parent_mobile_company', '', 'required');
			$this->form_validation->set_rules('parent_mobile', '', 'required');
			if($this->form_validation->run() == false){

				gf_alert("잘못된 접근입니다.2", '/');
				exit;
			}

			$member_email       = $under14_member_email;
			$member_mobile      = '';
			$parent_real_name   = $member_name;
			$member_name        = $under14_member_name;
			$parent_CI          = $mobile_CI;
			$mobile_CI          = '';
			$is_parent_auth     = $is_mobile_auth;
			$is_mobile_auth     = 'N';


		} else {

			$this->form_validation->set_rules('email1', '', 'required');
			$this->form_validation->set_rules('email2', '', 'required');
			$this->form_validation->set_rules('country_phone_no', '', 'required');
			$this->form_validation->set_rules('mobile1', '', 'required');
			$this->form_validation->set_rules('mobile2', '', 'required');

			print_r($_POST);
			if($this->form_validation->run() == false){
				gf_alert("잘못된 접근입니다.3", '/');
				exit;
			}

			$member_email   = $email1.'@'.$email2;
			$member_mobile  = $mobile1.'-'.$mobile2.'-'.$mobile3;


		}

		$now_date =  date("Y-m-d H:i:s");


		$filename           = '';
		$social_type        = '';
		$token              = '';
		$token_secret       = '';
		$refresh_token      = '';
		$token_expires_date = $now_date;
		$member_group_idx   = 1;
		if($social_id!='') {    // sns 가입
			# model
			$this->load->model('web/m_tmp_social_member');
			$arr_social   = $this->m_tmp_social_member->tmp_social_member_select($social_id);

			$social_type        = $arr_social['social_type'];
			$token              = $arr_social['token'];
			$token_secret       = $arr_social['token_secret'];
			$refresh_token      = $arr_social['refresh_token'];
			$token_expires_date = $arr_social['token_expires_date'];

			$member_group_idx  = 2;
			$member_id_prefix = '';
			switch ($social_type) {
				case '1': $member_id_prefix = 'FB_';    break;
				case '2': $member_id_prefix = 'TW_';    break;
				case '3': $member_id_prefix = 'KK_';    break;
				case '4': $member_id_prefix = 'NB_';    break;
			}

			$member_id  = $member_id_prefix.$social_id;
			$member_pwd = time();

			$upload_path = './files/profile/' . date("Y") . "/" . date("m");
			if (!is_dir($upload_path)) {
				mkdir($upload_path, 0777, TRUE);
			}

			if($sns_profile_img!='') {
				$arr_img_type = explode('.', $sns_profile_img);

				$last_key =  count($arr_img_type)-1;
				$img_type = '';
				if(isset($arr_img_type[$last_key])==true) {
					$img_type = $arr_img_type[$last_key];
				}

				$img_name = $social_id.time().".".$img_type;
				copy($sns_profile_img, $upload_path.'/'.$img_name);
				$filename = '/files/profile/' . date("Y") . "/" . date("m").'/'.$img_name;

			}


		}


		# model - 아이디 중복체크
		$this->load->model('web/m_member');
		$member_count   = $this->m_member->member_where_member_id_count($member_id);
		if($member_count > 0) {
			gf_alert("잘못된 접근입니다.4", '/');
			exit;
		}


		# 이미지업로드
		if($_FILES['member_img']['name']!='') {
			# image upload
			$upload_path = './files/profile/'.date("Y")."/".date("m");
			if (!is_dir($upload_path)) {
				mkdir($upload_path, 0777, TRUE);
			}
			$config['upload_path']      = $upload_path;
			$config['allowed_types']    = 'gif|jpg|png';
			$config['encrypt_name']     = TRUE;

			$this->load->library('upload');
			$this->upload->initialize($config);

			if ( ! $this->upload->do_upload('member_img')) {
				$error = array('error' => $this->upload->display_errors());
				gf_alert("이미지 업로드에 실패했습니다.", '/');
				exit;
			}
			$arr_upload_data = $this->upload->data();
			$filename = str_replace($_SERVER['DOCUMENT_ROOT'], '', $arr_upload_data['full_path']);
		}


		$member_birth = $birth_year.'-'.$birth_month.'-'.$birth_day;
		$now_year = date("Y");
		$member_age = floor((($now_year+1)-$birth_year)/10)*10;


		# update data
		$req_data = array();
		$req_data['member_img']             = $filename;
		$req_data['member_id']              = $member_id;
		$req_data['member_name']            = $member_name;
		$req_data['member_group_idx']       = $member_group_idx;
		$req_data['member_pwd']             = MD5($member_pwd);
		$req_data['member_email']           = $member_email;
		$req_data['member_birth']           = $member_birth;
		$req_data['member_calendar']        = $member_calendar;
		$req_data['member_age']             = $member_age;
		$req_data['member_gender']          = $member_gender;
		$req_data['country_phone_no']       = $country_phone_no;
		$req_data['member_mobile']          = $member_mobile;
		$req_data['is_member_auth']         = $is_mobile_auth;
		$req_data['member_church']          = $member_church;
		$req_data['etc1']                   = $etc1;
		$req_data['etc2']                   = $etc2;
		$req_data['etc3']                   = $etc3;
		$req_data['etc4']                   = $etc4;
		$req_data['etc5']                   = $etc5;
		$req_data['member_church']          = $member_church;
		$req_data['last_login_date']        = $now_date;
		$req_data['last_pwd_change_date']   = $now_date;
		$req_data['visit_count']            = 1;
		$req_data['sns_type']               = $social_type;
		$req_data['sns_id']                 = $social_id;
		$req_data['sns_token']              = $token;
		$req_data['sns_token_secret']       = $token_secret;
		$req_data['sns_refresh_token']      = $refresh_token;
		$req_data['sns_token_expires_date'] = $token_expires_date;
		$req_data['is_under14']             = $is_under14;
		$req_data['parent_name']            = $parent_name;
		$req_data['parent_mobile_company']  = $parent_mobile_company;
		$req_data['parent_mobile']          = $parent_mobile;
		$req_data['parent_real_name']       = $parent_real_name;
		$req_data['parent_CI']              = $parent_CI;
		$req_data['is_parent_auth']         = $is_parent_auth;
		$req_data['member_status']          = 1;
		$req_data['reg_date']               = $now_date;
		$req_data['reg_id']                 = $member_id;
		$req_data['update_date']            = $now_date;
		$req_data['update_id']              = $member_id;
		$req_data['mobile_CI']              = $mobile_CI;

		# model
		$this->load->model('web/m_member');
		$member_idx    = $this->m_member->member_insert($req_data);
		if($member_idx==0 || $member_idx=='') {
			gf_alert("회원가입에 실패했습니다.", 'back');
			exit;
		}

		// 이메일발송
		$content ='크리스천들의 놀이터! <p></p>';
		$content.=$member_name.'님의 크로스맵 회원가입을 진심으로 축하합니다!  <p></p>';
		$content.='크리스천 놀이터 크로스맵에 자주 놀러 오실 거죠?  <p></p><p>&nbsp;</p>';
		$content.='아이디: '.$member_id.'<p></p>';
		$content.='이름/닉네임: '.$member_name.'<p></p>';
		$content.='가입일시: '.date("Y").'년 '.date("m").'월 '.date("d").'일 '.date("H").'시 '.date("i").'분 '.date("s").'초<p></p><p>&nbsp;</p>';
		$content.='닉네임 등 프로필 정보는 &#39;내 정보관리&#39; 에서 수정할 수 있어요:) <p></p>';
		$content.='<a href="'.$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'" target="_blank">-> 크로스맵에 놀러 가기!</a> <p></p><p>&nbsp;</p>';
		$content.='P.S) 하나님의 은혜와 평강이 '.$member_name.'님의 삶 가운데 늘 가득하기를 <p></p>';
		$content.='크로스맵이 응원하고 기도합니다! <p></p><p>&nbsp;</p>';
		$content.=' - 크로스맵 일동 올림 -  <p></p>';

		$mail_result['content'] = $content;
		$message = $this->load->view('/web/comm/mail_template', $mail_result, TRUE);



		$this->email->from(CROSSMAP_EMAIL, CROSSMAP_EMAIL_NAME);
		$this->email->to($member_email);
		$this->email->subject('크로스맵 회원가입을 진심으로 축하합니다!');
		$this->email->message($message);

		$this->email->send();

		$req_data['idx']                    = $member_idx;
		$req_data['member_nickname']        = $member_name;
		$req_data['member_intro']           = '';


		$this->load->library('comm');
		$this->comm->fn_login_proc($req_data);

		$this->session->set_userdata('C_Member_First', 'Y');


		# 메인으로 이동
		redirect(WWW_CROSSMAP."/m/member/join_2");


	}



	#---------------------------------------------------------------------------
    # PURPOSE :	이메일 중복체크
    # CREATE  :	2018-04-24
    #---------------------------------------------------------------------------
	function fn_ajax_member_email_check_proc() {
        # request
        $member_email  = trim($this->input->get_post('email', TRUE));

        # model
        $this->load->model('web/m_member');
        $member_count   = $this->m_member->member_where_email_count($member_email);

        if($member_count == 0) {
            $return_data['result'] = array('result_code' => '0000');
        } else {
            $return_data['result'] = array('result_code' => '9999');
        }

        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }


    #---------------------------------------------------------------------------
    # PURPOSE :	비밀번호 변경
    # CREATE  :	2018-04-24
    #---------------------------------------------------------------------------
	function fn_ajax_password_change_proc() {
        # request
        $now_pwd            = trim($this->input->get_post('now_pwd', TRUE));
        $new_member_pwd     = trim($this->input->get_post('new_member_pwd', TRUE));
        $SES_MEMBER_ID      = $this->session->userdata('C_Member_Id');

        # 현재 비밀번호 체크
        $req_data = array();
        $req_data['member_id']  = $SES_MEMBER_ID;
        $req_data['member_pwd'] = $now_pwd;

        # model
        $this->load->model('web/m_member');
        $result    = $this->m_member->member_join_member_group_where_member_id_member_pwd_select($req_data);
        if(count($result) == 0) {
            throw new Cm_Exception('json', '9999', '현재 비밀번호를 확인해주세요.');
        }

        $now_date =  date("Y-m-d");
        $next_change_date = date("Y-m-d", strtotime($now_date.' + 3month'));

        $now_date = str_replace("-", ".", $now_date);
        $next_change_date = str_replace("-", ".", $next_change_date);

        $member_email   = $result['member_email'];
        $member_name    = $result['member_name'];

        # 비밀번호 update
        $req_data = array();
        $req_data['idx']                    = $result['idx'];
        $req_data['member_pwd']             = md5($new_member_pwd);
        $req_data['last_pwd_change_date']   = $now_date;
        $req_data['update_id']              = $SES_MEMBER_ID;

        $this->m_member->member_update($req_data);

        $this->load->library('comm');
        $this->comm->fn_logout_proc();


        if($member_email!='') {
            // 이메일발송
            $content =$member_name.'님, '.date("Y").'년 '.date("m").'월 '.date("d").'일 '.date("H").'시 '.date("i").'분 '.date("s").'초에 계정 비밀번호 정보를 변경하였습니다.<p></p>';
            $content.='혹시, 변경한 적이 없는 경우 1:1 고객센터로 문의해 주시면, 도움 드리도록 하겠습니다.<p></p>';
            $content.='* 소중한 개인정보, 잊어버리지 않도록 유의해 주세요. <p></p><p>&nbsp;</p>';
            $content.='P.S) 하나님의 은혜와 평강이 '.$member_name.'님의 삶 가운데 늘 가득하기를 <p></p>';
            $content.='크로스맵이 응원하고 기도합니다! <p></p><p>&nbsp;</p>';
            $content.=' - 크로스맵 일동 올림 -  <p></p>';

            $mail_result['content'] = $content;
            $message = $this->load->view('/web/comm/mail_template', $mail_result, TRUE);

            $this->load->library('email');
            $config = array();
            $config['wordwrap'] = true;
            $config['mailtype'] = 'html';
            $this->email->initialize($config);
            $this->email->from(CROSSMAP_EMAIL, CROSSMAP_EMAIL_NAME);
            $this->email->to($member_email);
            $this->email->subject('개인 비밀번호 정보 변경 안내 메일입니다.');
            $this->email->message($message);

            $this->email->send();

            $arr_email = explode("@", $member_email);

            $email1 = mb_substr($arr_email[0], 0, 1).'**'.mb_substr($arr_email[0], 3, 1).'***';
            $email2 = mb_substr($arr_email[1], 0, 1).'******';

            $member_email = $email1.'@'.$email2;


        }

        $member_id  = $result['member_id'];
        $member_id  = mb_substr($member_id, 0, 4).'****';





        $data = array('now_date'=>$now_date, 'next_change_data'=>$next_change_date, 'member_id'=>$member_id, 'member_email'=> $member_email);
        $return_data = array();
        $return_data['result'] = array('code' => '0000', 'data'=>$data);

        $this->session->set_userdata('C_Member_Login', 'Y');

        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }



    #---------------------------------------------------------------------------
    # PURPOSE :	닉네임 중복체크
    # CREATE  :	2018-04-25
    #---------------------------------------------------------------------------
	function fn_ajax_member_nickname_check_proc() {
        # request
        $member_nickname  = trim($this->input->get_post('member_nickname', TRUE));

        # model
        $this->load->model('web/m_member');
        $member_count   = $this->m_member->member_where_member_nickname_count($member_nickname);

        if($member_count == 0) {
            $return_data['result'] = array('result_code' => '0000');
        } else {
            $return_data['result'] = array('result_code' => '9999');
        }

        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }


    #---------------------------------------------------------------------------
    # PURPOSE :	내 이메일 체크
    # CREATE  :	2018-04-25
    #---------------------------------------------------------------------------
	function fn_ajax_member_my_email_check_proc() {
        # request
        $member_email   = trim($this->input->get_post('email', TRUE));
        $SES_MEMBER_ID  = $this->session->userdata('C_Member_Id');


        # model
        $req_data = array();
        $req_data['member_id']      = $SES_MEMBER_ID;
        $req_data['member_email']   = $member_email;

        $this->load->model('web/m_member');
        $member_count   = $this->m_member->member_where_member_id_email_count($req_data);

        if($member_count > 0) {
            $return_data['result'] = array('result_code' => '0000');
        } else {
            $return_data['result'] = array('result_code' => '9999');
        }

        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }



    #---------------------------------------------------------------------------
    # PURPOSE :	이메일 변경
    # CREATE  :	2018-04-25
    #---------------------------------------------------------------------------
	function fn_ajax_member_email_edit_proc() {
        # request
        $member_email       = trim($this->input->get_post('email', TRUE));
        $SES_MEMBER_ID      = $this->session->userdata('C_Member_Id');
        $SES_MEMBER_NAME    = $this->session->userdata('C_Member_Name');


        $this->load->model('web/m_member');
        $result = $this->m_member->member_where_member_id_select($SES_MEMBER_ID);
        if(count($result)==0) {
            throw new Cm_Exception('json', '9999', '잘못된 접근입니다.');
        }

        $org_email = $result['member_email'];


        # 이메일 update
        $req_data = array();
        $req_data['member_email']           = $member_email;
        $req_data['member_id']              = $SES_MEMBER_ID;
        $req_data['update_id']              = $SES_MEMBER_ID;


        $result = $this->m_member->member_where_member_id_update($req_data);

        $return_data = array();
        if($result) {

            $content =$SES_MEMBER_NAME.'님, '.date("Y").'년 '.date("m").'월 '.date("d").'일 '.date("H").'시 '.date("i").'분 '.date("s").'초에 이메일주소 정보를 변경하셨습니다. <p></p>';
            $content.='변경된 주소는 '.$member_email.' 입니다. <p></p><p>&nbsp;</p>';
            $content.='혹시, 변경한 적이 없는 경우 1:1 고객센터로 문의 해 주시면, 도움 드리도록 하겠습니다.<p></p>';
            $content.='* 소중한 개인정보, 잊어버리지 않도록 유의해 주세요.<p></p><p>&nbsp;</p>';
            $content.='P.S) 하나님의 은혜와 평강이 '.$SES_MEMBER_NAME.'님의 삶 가운데 늘 가득하기를 <p></p>';
            $content.='크로스맵이 응원하고 기도합니다! <p></p><p>&nbsp;</p>';
            $content.=' - 크로스맵 일동 올림 -  <p></p>';

            $mail_result['content'] = $content;
            $message = $this->load->view('/web/comm/mail_template', $mail_result, TRUE);

            $this->load->library('email');
            $config = array();
            $config['wordwrap'] = true;
            $config['mailtype'] = 'html';
            $this->email->initialize($config);
            $this->email->from(CROSSMAP_EMAIL, CROSSMAP_EMAIL_NAME);
            $this->email->to($org_email, $member_email);
            $this->email->subject('개인 이메일 정보 변경 안내 메일입니다.');
            $this->email->message($message);
            $this->email->send();

            if($member_email!='') {
                $this->session->set_userdata('C_Member_Email', $member_email);
                $arr_email = explode("@", $member_email);
                $email1 = mb_substr($arr_email[0], 0, 2).'******';
                $arr_email2 = explode(".", $arr_email[1]);
                $email2 = mb_substr($arr_email[1], 0, 1).'*******'.str_replace($arr_email2[0], '', $arr_email[1]);
                $member_email = $email1.'@'.$email2;

            }



            $return_data['result'] = array('code' => '0000', 'data'=>$member_email);
        } else {
            $return_data['result'] = array('code' => '9999');
        }


        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }


    #---------------------------------------------------------------------------
    # PURPOSE :	비밀번호 확인
    # CREATE  :	2018-04-25
    #---------------------------------------------------------------------------
    function fn_ajax_member_pwd_check_proc(){

        # Request
        $SES_MEMBER_ID  = $this->session->userdata('C_Member_Id');
        $member_pwd     = trim($this->input->get_post('member_pwd', TRUE));   // 비밀번호


         # 로그인
        $req_data = array();
        $req_data['member_id']  = $SES_MEMBER_ID;
        $req_data['member_pwd'] = MD5($member_pwd);

        # model
        $this->load->model('web/m_member');
        $count    = $this->m_member->member_where_member_id_member_pwd_count($req_data);
        if($count == 0) {
            throw new Cm_Exception('json', '9999', '비밀번호를 확인해주세요.');
        }

        $return_data = array();
        $return_data['result'] = array('code' => '0000');

        # view
        return $this->load->view('/web/comm/result_json', $return_data);
	}


	#---------------------------------------------------------------------------
    # PURPOSE :	회원탈퇴
    # CREATE  :	2018-04-25
    #---------------------------------------------------------------------------
    function fn_ajax_member_leave_proc(){

        # Request
        $member_pwd         = trim($this->input->get_post('member_pwd', TRUE));   // 비밀번호
        $SES_MEMBER_EMAIL   = $this->session->userdata('C_Member_Email');
        $SES_MEMBER_NAME    = $this->session->userdata('C_Member_Name');
        $SES_MEMBER_ID      = $this->session->userdata('C_Member_Id');

        # 로그인
        $req_data = array();
        $req_data['member_id']  = $SES_MEMBER_ID;
        $req_data['member_pwd'] = MD5($member_pwd);
        

        # model
        $this->load->model('web/m_member');
        $result    = $this->m_member->member_where_member_id_member_pwd_select($req_data);
        if(count($result) == 0) {
            throw new Cm_Exception('json', '9999', '잘못된 접근입니다.');
        }

        #  상태 update
        $req_data = array();
        $req_data['idx']                    = $result['idx'];
        $req_data['member_status']          = '2';
        $req_data['update_id']              = $SES_MEMBER_ID;

        $this->m_member->member_update($req_data);


        $content =$SES_MEMBER_NAME.'님의 계정 탈퇴가 완료 되었습니다.  <p></p>';
        $content.='크로스맵이 마음에 들지 않으셨나요?  <p></p>';
        $content.='더 나은 서비스를 위해 최선을 다해 노력하겠습니다.__)<p></p>';
        $content.='개인정보 및 이용기록은 영구삭제 되며<p></p>';
        $content.='동일한 아이디로 재가입 하실 수 없습니다. <p></p>';
        $content.='좋아요, 댓글 등의 사용 기록은 삭제되지 않으니 양지 부탁 드리겠습니다.  <p></p><p>&nbsp;</p>';
        $content.='P.S) 하나님의 은혜와 평강이 '.$SES_MEMBER_NAME.'님의 삶 가운데 늘 가득하기를 <p></p>';
        $content.='크로스맵이 응원하고 기도합니다! <p></p><p>&nbsp;</p>';
        $content.=' - 크로스맵 일동 올림 -  <p></p>';

        $mail_result['content'] = $content;
        $message = $this->load->view('/web/comm/mail_template', $mail_result, TRUE);

        $this->load->library('email');
        $config = array();
        $config['wordwrap'] = true;
        $config['mailtype'] = 'html';
        $this->email->initialize($config);
        $this->email->from(CROSSMAP_EMAIL, CROSSMAP_EMAIL_NAME);
        $this->email->to($SES_MEMBER_EMAIL);
        $this->email->subject($SES_MEMBER_NAME.'님의 크로스맵 회원탈퇴가 완료 되었습니다.');
        $this->email->message($message);

        $this->email->send();


        $this->load->library('comm');
        $this->comm->fn_logout_proc();


        $return_data = array();
        $return_data['result'] = array('code' => '0000');

        # view
        return $this->load->view('/web/comm/result_json', $return_data);
	}


	#---------------------------------------------------------------------------
    # PURPOSE :	휴대폰 번호 변경
    # CREATE  :	2018-06-04
    #---------------------------------------------------------------------------
    function fn_ajax_member_mobile_change_proc(){
        # Request
        $mobile         = trim($this->input->get_post('mobile', TRUE));   // 비밀번호
        $SES_MEMBER_ID  = $this->session->userdata('C_Member_Id');

        $member_mobile = mb_substr($mobile, 0, 3).'-'.mb_substr($mobile, 3, 4).'-'.mb_substr($mobile, 7, 4);


        # 휴대폰 번호 update
        $req_data = array();
        $req_data['member_mobile']          = $member_mobile;
        $req_data['member_id']              = $SES_MEMBER_ID;
        $req_data['update_id']              = $SES_MEMBER_ID;
        $this->load->model('web/m_member');
        $this->m_member->member_where_member_id_update($req_data);

        $member_mobile  = mb_substr($member_mobile, 1, 4).'***-***'.mb_substr($member_mobile, 12, 1);

        $return_data = array();
        $return_data['result'] = array('code' => '0000', 'data'=>$member_mobile);

        # view
        return $this->load->view('/web/comm/result_json', $return_data);
	}



	#---------------------------------------------------------------------------
	# PURPOSE : 이메일로 찾기
	# CREATE  :	2018-05-30
	#---------------------------------------------------------------------------
	function fn_ajax_find_by_email_proc() {
		# request
		$content    = trim($this->input->get_post('content', TRUE));
		$email      = trim($this->input->get_post('email', TRUE));
		$type       = trim($this->input->get_post('type', TRUE));
		$SES_MEMBER_ID      = $this->session->userdata('C_Member_Id');
		$this->load->model('web/m_member');
		if($type=='id') {
			$req_data = array();
			$req_data['member_name']   = $content;
			$req_data['member_email']  = $email;


			$count   = $this->m_member->member_where_email_name_count($req_data);
			if($count>0) {
				// 인증번호 생성
				$rand_num = gf_generate_random_string(6);
				$req_data = array();
				$req_data['type']       = $type;
				$req_data['content']    = $content;
				$req_data['type_key']   = $email;
				$req_data['auth_key']   = $rand_num;
				$req_data['reg_id']     = 'system';
				$req_data['reg_date']   = date("Y-m-d H:i:s");

				$this->load->model('web/m_tmp_find_key');
				$this->m_tmp_find_key->tmp_find_key_insert($req_data);


				// 이메일발송
				$content1 ='소중한 ID 정보를 잊어버리셨군요; <p></p>';
				$content1.='아래 인증번호로 인증처리 하시면 아이디를 확인하실 수 있습니다. <p></p><p>&nbsp;</p>';
				$content1.='<b>인증번호</b>: '.$rand_num.'<p></p><p>&nbsp;</p>';
				$content1.='* 소중한 개인정보, 잊어버리지 않도록 유의해 주세요. <p></p><p>&nbsp;</p>';
				$content1.='P.S) 하나님의 은혜와 평강이 '.$content.'님의 삶 가운데 늘 가득하기를 <p></p>';
				$content1.='크로스맵이 응원하고 기도합니다! <p></p><p>&nbsp;</p>';
				$content1.=' - 크로스맵 일동 올림 -  <p></p>';

				$mail_result['content'] = $content1;
				$message = $this->load->view('/web/comm/mail_template', $mail_result, TRUE);

				$this->email->from(CROSSMAP_EMAIL_ID, CROSSMAP_EMAIL_NAME);
				$this->email->to($email);
				$this->email->subject('크로스맵 아이디찾기 인증메일입니다.');
				$this->email->message($message);

				if($this->email->send()){
					//Success email Sent
					$debug= "ok";
				}else{
					//Email Failed To Send
					$debug= "o";
				}

				$return_data['result'] = array('code' => '0000','data'=>$content1);

			} else {
				$return_data['result'] = array('code' => '9999', 'msg' => '입력하신 정보가 없습니다.');
			}

		}




		# view
		return $this->load->view('/web/comm/result_json', $return_data);

	}



	#---------------------------------------------------------------------------
	# PURPOSE : 이메일로 찾기 - 인증
	# CREATE  :	2018-05-30
	#---------------------------------------------------------------------------
	function fn_ajax_find_by_email_auth_proc() {
		# request
		$content    = trim($this->input->get_post('content', TRUE));
		$email      = trim($this->input->get_post('email', TRUE));
		$type       = trim($this->input->get_post('type', TRUE));
		$auth_key   = trim($this->input->get_post('auth_key', TRUE));


		$this->load->model('web/m_member');
		if($type=='id') {
			$this->load->model('web/m_tmp_find_key');
			$req_data = array();
			$req_data['type']       = $type;
			$req_data['content']    = $content;
			$req_data['type_key']   = $email;
			$req_data['auth_key']   = $auth_key;

			$count = $this->m_tmp_find_key->tmp_find_key_where_type_content_type_key_auth_key_count($req_data);
			if($count==0){
				throw new Cm_Exception('json', '9999', '인증에 실패했습니다.');
			}

			$req_data = array();
			$req_data['member_name']   = $content;
			$req_data['member_email']  = $email;

			$result   = $this->m_member->member_where_email_name_select_limit1($req_data);
			$return_data['result'] = array('code' => '0000', 'data'=>$result['member_id']);

		}


		# view
		return $this->load->view('/web/comm/result_json', $return_data);

	}







	#---------------------------------------------------------------------------
	# PURPOSE : 비밀번호 찾기
	# CREATE  :	2018-05-30
	#---------------------------------------------------------------------------
	function fn_ajax_find_password_proc() {
		# request
		$key    = trim($this->input->get_post('key', TRUE));
		$type   = trim($this->input->get_post('type', TRUE));

		$this->load->model('web/m_member');
		if($type=='mobile') {
			$result   = $this->m_member->member_where_mobile_CI_select($key);

		} else if($type=='email') {
			$id    = trim($this->input->get_post('id', TRUE));
			$req_data = array();
			$req_data['member_id']       = $id;
			$req_data['member_email']    = $key;
			$result   = $this->m_member->member_where_member_id_email_select($req_data);


		}

		if(count($result) ==  0)    throw new Cm_Exception('json', '9999', '일치하는 회원정보가 없습니다.');

		$member_email      = $result['member_email'];
		if($member_email=='')   throw new Cm_Exception('json', '9999', '이메일이 등록되어있지 않습니다. 관리자에게 문의해주세요.');


		// 임시비밀번호 생성
		$rand_num = gf_generate_random_string(8);

		$req_data = array();
		$req_data['member_pwd'] = MD5($rand_num);
		$req_data['idx']        = $result['idx'];
		$result   = $this->m_member->member_update($req_data);

		// 이메일발송
		$content='소중한 비밀번호 정보를 잊어버리셨군요.<p></p><p>&nbsp;</p>';
		$content.='<b>임시 비밀번호</b>: <span style="color:#44cbd2;">'.$rand_num.'</span><p></p><p>&nbsp;</p>';
		$content.='꼭! 보안수준이 높은 비밀번호로 재변경하시기 바랍니다.<p></p>';
		$content.='* 소중한 개인정보, 잊어버리지 않도록 유의해 주세요.<p></p><p>&nbsp;</p>';
		$content.='P.S) 하나님의 은혜와 평강이 '.$result['member_name'].'님의 삶 가운데 늘 가득하기를<p></p>';
		$content.='크로스맵이 응원하고 기도합니다! <p></p><p>&nbsp;</p>';
		$content.=' - 크로스맵 일동 올림 -  <p></p>';

		$mail_result['content'] = $content;
		$message = $this->load->view('/web/comm/mail_template', $mail_result, TRUE);


		$this->load->library('email');
		$config = array();
		$config['wordwrap'] = true;
		$config['mailtype'] = 'html';
		$this->email->initialize($config);
		$this->email->from(CROSSMAP_EMAIL, CROSSMAP_EMAIL_NAME);
		$this->email->to($member_email);
		$this->email->subject('크로스맵 비밀번호 찾기 임시 비밀번호 안내 메일입니다.');
		$this->email->message($message);

		$this->email->send();

		$dd = print_r($this->email,true);


		$arr_email = explode("@", $member_email);

		$email1 = mb_substr($arr_email[0], 0, 1).'**'.mb_substr($arr_email[0], 3, 1).'***';
		$email2 = mb_substr($arr_email[1], 0, 1).'******';

		$member_email = $email1.'@'.$email2;


		$return_data['result'] = array('code' => '0000', 'data' => $member_email , 'debug'=>$dd);


		# view
		return $this->load->view('/web/comm/result_json', $return_data);

	}







}

?>


