<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Find_my_password
 */


class Find_my_password extends CI_Controller
{

    private $CI;

    function __construct()
    {
        $this->CI = & get_instance();

        $this->CI->load->library(array('email'));
    }

	function main()
	{
		$this->CI->load->model('Apps_model');

		if ( ! $this->CI->input->post_get('token')) {
			$this->CI->apilib->make_error("토큰 값이 넘어오지 않았습니다");
        }
		$token = $this->CI->input->post_get('token');


        $app_id = (int) trim($this->CI->input->post_get('app_id'));
        if (empty($app_id)) {
			$this->CI->apilib->make_error("어플 아이디가 넘어오지 않았습니다");
        }

		$email = trim($this->CI->input->post('email'));
		if ( ! $email) {
			$this->CI->apilib->make_error("이메일이 입력되지 않았습니다");
		}

        $this->CI->load->helper('string');
		if ( ! function_exists('password_hash')) {
            $this->CI->load->helper('password');
        }

        $userinfo = $this->CI->User_model->get_by_api_email($app_id, $email, 'user_id, user_email, user_denied, user_username, user_password');

        if (element('user_denied', $userinfo)) {
			$this->CI->apilib->make_error("회원님의 아이디는 접근이 금지된 아이디입니다");
        }
        if ( ! element('user_id', $userinfo)) {
			$this->CI->apilib->make_error("일치하는 회원정보가 없습니다");
        }

		$user_id = element('user_id', $userinfo);

		$new_password = rand(100000,999999);

		$hash = password_hash($new_password, PASSWORD_BCRYPT);

		$updatedata = array(
			'user_password' => $hash,
		);
		$upwhere = array(
			'app_id' => $app_id,
			'user_id' => $user_id,
		);
		$this->CI->User_model->update('', $updatedata, $upwhere);

		$appinfo = $this->CI->Apps_model->get_one($app_id);

		$email_title = '[' . element('app_name', $appinfo) . '] 회원님의 패스워드가 변경되었습니다.';
		$email_content = '<table width="100%" cellpadding="0" cellspacing="0" style="border-left: 1px solid rgb(226,226,225);border-right: 1px solid rgb(226,226,225);background-color: rgb(255,255,255);border-top:10px solid #348fe2; border-bottom:5px solid #348fe2;border-collapse: collapse;"><tbody><tr><td width="200" style="padding:20px 30px;font-family: Arial,sans-serif;color: rgb(0,0,0);font-size: 14px;line-height: 20px;">' . element('app_name', $appinfo) . '</td><td style="font-size:12px;padding:20px 30px;font-family: Arial,sans-serif;color: rgb(0,0,0);font-size: 14px;line-height: 20px;"><span style="font-size:14px;font-weight:bold;color:rgb(0,0,0)">안녕하세요 ' . html_escape(element('user_username', $userinfo)) . '님,</span><br>회원님의 패스워드 변경</td></tr><tr style="border-top:1px solid #e2e2e2; border-bottom:1px solid #e2e2e2;"><td colspan="2" style="padding:20px 30px;font-family: Arial,sans-serif;color: rgb(0,0,0);font-size: 14px;line-height: 20px;"><p>' . html_escape(element('user_username', $userinfo)) . '님, 안녕하세요!</p><p>&nbsp;</p><p>회원님의 패스워드가 변경되었습니다.</p><p>변경된 패스워드는 다음과 같습니다</p><p style="color:red;font-weight:bold;">' . $new_password . '</p><p>&nbsp;</p><p>감사합니다.</p></td></tr></tbody></table>';

		include_once(FCPATH . 'plugin/PHPMailer/PHPMailerAutoload.php');
		
		$mail = new PHPMailer;
		$mail->SMTPDebug = 0;                               // Enable verbose debug output
		$mail->CharSet = "euc-kr";
		$mail->isSMTP();                                      // Set mailer to use SMTP
		$mail->Host = config_item('email_smtp_host');  // Specify main and backup SMTP servers
		$mail->SMTPAuth = true;                               // Enable SMTP authentication
		$mail->Username = config_item('email_smtp_user');                 // SMTP username
		$mail->Password = config_item('email_smtp_pass');                           // SMTP password
		$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
		$mail->Port = 465;                                    // TCP port to connect to
		$mail->setFrom(config_item('email_smtp_user'), iconv("UTF-8", "EUC-KR", element('app_name', $appinfo)));
		$mail->addAddress($email, element('user_username', $userinfo));     // Add a recipient
		$mail->isHTML(true);                                  // Set email format to HTML

		$mail->Subject = iconv("UTF-8", "EUC-KR", $email_title);
		$mail->Body    = iconv("UTF-8", "EUC-KR", $email_content);

		if(!$mail->send()) {
			$this->CI->apilib->make_error("메일을 발송할 수가 없습니다");
			//echo 'Mailer Error: ' . $mail->ErrorInfo;
		} 

		$arr = array(
			'result' => 'ok',
			'token' => $token,
			'app_id' => $app_id,
			'user_id' => element('user_id', $userinfo),
			'user_email' => element('user_email', $userinfo),
		);
		return $arr;

	}
}
