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

/**
 * usermodify class
 */

/**
 * 회원 정보 수정시 담당하는 controller 입니다.
 */
class Usermodify extends MY_Controller
{

    /**
     * 모델을 로딩합니다
     */
    protected $models = array('User_meta', 'User_auth_email');

    /**
     * 헬퍼를 로딩합니다
     */
    protected $helpers = array('form', 'array', 'string');

    function __construct()
    {
        parent::__construct();

        /**
         * 라이브러리를 로딩합니다
         */
        $this->load->library(array('querystring', 'form_validation', 'email'));
    }


    /**
     * 회원정보 수정 페이지입니다
     */
    public function index()
    {

        /**
         * 로그인이 필요한 페이지입니다
         */
        required_user_login();

        $view = array();
        $view['view'] = array();


        $user_id = (int) $this->userlib->item('user_id');

        if ( ! $this->userlib->item('user_password')) {
            redirect('usermodify/defaultinfo');
        }

        $this->load->library(array('form_validation'));

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

        $login_fail = false;
        $valid_fail = false;

        /**
         * 전송된 데이터의 유효성을 체크합니다
         */
        $config = array(
            array(
                'field' => 'user_password',
                'label' => '패스워드',
                'rules' => 'trim|required|min_length[4]|callback__cur_password_check',
            ),
        );
        $this->form_validation->set_rules($config);
        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($this->form_validation->run() === false) {


            $skin = 'user_password';

        
            /**
             * 레이아웃을 정의합니다
             */
            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => $skin,
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));
        } else {
            /**
             * 유효성 검사를 통과한 경우입니다.
             * 즉 데이터의 insert 나 update 의 process 처리가 필요한 상황입니다
             */


            $this->session->set_userdata(
                'usermodify',
                '1'
            );
            redirect('usermodify/modify');
        }

    }


    /**
     * 회원정보 수정 페이지입니다
     */
    public function modify()
    {

        if ( ! $this->session->userdata('usermodify')) {
            redirect('usermodify');
        }

        /**
         * 로그인이 필요한 페이지입니다
         */
        required_user_login();

        $user_id = (int) $this->userlib->item('user_id');

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

        $view = array();
        $view['view'] = array();


        $email_description = '';
        if ($this->configlib->item('use_register_email_auth')) {
            $email_description = '이메일을 변경하시면 메일 인증 후에 계속 사용이 가능합니다';
        }

        $configbasic = array();

        $configbasic['user_username'] = array(
            'field' => 'user_username',
            'label' => '이름',
            'rules' => 'trim|required|min_length[2]|max_length[20]|callback__user_username_check',
        );
        $configbasic['user_email'] = array(
            'field' => 'user_email',
            'label' => '이메일',
            'rules' => 'trim|required|valid_email|max_length[50]|is_unique[user.user_email.user_id.' . $user_id . ']|callback__user_email_check',
            'description' => $email_description,
        );
        $configbasic['user_homepage'] = array(
            'field' => 'user_homepage',
            'label' => '홈페이지',
            'rules' => 'prep_url|valid_url',
        );
        $configbasic['user_phone'] = array(
            'field' => 'user_phone',
            'label' => '전화번호',
            'rules' => 'trim|valid_phone',
        );
        $configbasic['user_birthday'] = array(
            'field' => 'user_birthday',
            'label' => '생년월일',
            'rules' => 'trim|exact_length[10]',
        );
        $configbasic['user_sex'] = array(
            'field' => 'user_sex',
            'label' => '성별',
            'rules' => 'trim|exact_length[1]',
        );
        $configbasic['user_zipcode'] = array(
            'field' => 'user_zipcode',
            'label' => '우편번호',
            'rules' => 'trim|min_length[5]|max_length[7]',
        );
        $configbasic['user_address1'] = array(
            'field' => 'user_address1',
            'label' => '기본주소',
            'rules' => 'trim',
        );
        $configbasic['user_address2'] = array(
            'field' => 'user_address2',
            'label' => '상세주소',
            'rules' => 'trim',
        );
        $configbasic['user_address3'] = array(
            'field' => 'user_address3',
            'label' => '참고항목',
            'rules' => 'trim',
        );
        $configbasic['user_address4'] = array(
            'field' => 'user_address4',
            'label' => '지번',
            'rules' => 'trim',
        );
        $configbasic['user_receive_email'] = array(
            'field' => 'user_receive_email',
            'label' => '이메일수신여부',
            'rules' => 'trim|exact_length[1]',
        );

        $this->load->library(array('form_validation'));
        $login_fail = false;
        $valid_fail = false;

        $registerform = $this->configlib->item('registerform');
        $form = json_decode($registerform, true);

        $config = array();
        if ($form && is_array($form)) {
            foreach ($form as $key => $value) {
                if ( ! element('use', $value)) {
                    continue;
                }
                if ($key === 'user_password') {
                    continue;
                }

                if (element('func', $value) === 'basic') {
                    if ($key === 'user_address') {
                        if (element('required', $value) === '1') {
                            $configbasic['user_zipcode']['rules'] = $configbasic['user_zipcode']['rules'] . '|required';
                        }
                        $config[] = $configbasic['user_zipcode'];
                        if (element('required', $value) === '1') {
                            $configbasic['user_address1']['rules'] = $configbasic['user_address1']['rules'] . '|required';
                        }
                        $config[] = $configbasic['user_address1'];
                        if (element('required', $value) === '1') {
                            $configbasic['user_address2']['rules'] = $configbasic['user_address2']['rules'] . '|required';
                        }
                        $config[] = $configbasic['user_address2'];
                    } else {
                        if (element('required', $value) === '1') {
                            $configbasic[$value['field_name']]['rules'] = $configbasic[$value['field_name']]['rules'] . '|required';
                        }
                        if (element('field_type', $value) === 'phone') {
                            $configbasic[$value['field_name']]['rules'] = $configbasic[$value['field_name']]['rules'] . '|valid_phone';
                        }
                        $config[] = $configbasic[$value['field_name']];
                    }
                } else {
                    $required = element('required', $value) ? '|required' : '';
                    if (element('field_type', $value) === 'checkbox') {
                        $config[] = array(
                            'field' => element('field_name', $value) . '[]',
                            'label' => $value['display_name'],
                            'rules' => 'trim' . $required,
                        );
                    } else {
                        $config[] = array(
                            'field' => element('field_name', $value),
                            'label' => $value['display_name'],
                            'rules' => 'trim' . $required,
                        );
                    }
                }
            }
        }

        $this->form_validation->set_rules($config);
        $form_validation = $this->form_validation->run();
        $file_error = '';
        $updatephoto = '';
        $file_error2 = '';
        $updateicon = '';

        if ($form_validation) {
            $this->load->library('upload');
            if ($this->configlib->item('use_user_photo')
                && $this->configlib->item('user_photo_width') > 0
                && $this->configlib->item('user_photo_height') > 0) {
                if (isset($_FILES) && isset($_FILES['user_photo']) && isset($_FILES['user_photo']['name']) && $_FILES['user_photo']['name']) {
                    $upload_path = config_item('uploads_dir') . '/user_photo/';
                    if (is_dir($upload_path) === false) {
                        mkdir($upload_path, 0707);
                        $file = $upload_path . 'index.php';
                        $f = @fopen($file, 'w');
                        @fwrite($f, '');
                        @fclose($f);
                        @chmod($file, 0644);
                    }
                    $upload_path .= cdate('Y') . '/';
                    if (is_dir($upload_path) === false) {
                        mkdir($upload_path, 0707);
                        $file = $upload_path . 'index.php';
                        $f = @fopen($file, 'w');
                        @fwrite($f, '');
                        @fclose($f);
                        @chmod($file, 0644);
                    }
                    $upload_path .= cdate('m') . '/';
                    if (is_dir($upload_path) === false) {
                        mkdir($upload_path, 0707);
                        $file = $upload_path . 'index.php';
                        $f = @fopen($file, 'w');
                        @fwrite($f, '');
                        @fclose($f);
                        @chmod($file, 0644);
                    }

                    $uploadconfig = '';
                    $uploadconfig['upload_path'] = $upload_path;
                    $uploadconfig['allowed_types'] = 'jpg|jpeg|png|gif';
                    $uploadconfig['max_size'] = '2000';
                    $uploadconfig['max_width'] = '1000';
                    $uploadconfig['max_height'] = '1000';
                    $uploadconfig['encrypt_name'] = true;

                    $this->upload->initialize($uploadconfig);

                    if ($this->upload->do_upload('user_photo')) {
                        $img = $this->upload->data();
                        $updatephoto = cdate('Y') . '/' . cdate('m') . '/' . $img['file_name'];
                    } else {
                        $file_error = $this->upload->display_errors();

                    }
                }
            }

            if ($this->configlib->item('use_user_icon')
                && $this->configlib->item('user_icon_width') > 0
                && $this->configlib->item('user_icon_height') > 0) {
                if (isset($_FILES)
                    && isset($_FILES['user_icon'])
                    && isset($_FILES['user_icon']['name'])
                    && $_FILES['user_icon']['name']) {
                    $upload_path = config_item('uploads_dir') . '/user_icon/';
                    if (is_dir($upload_path) === false) {
                        mkdir($upload_path, 0707);
                        $file = $upload_path . 'index.php';
                        $f = @fopen($file, 'w');
                        @fwrite($f, '');
                        @fclose($f);
                        @chmod($file, 0644);
                    }
                    $upload_path .= cdate('Y') . '/';
                    if (is_dir($upload_path) === false) {
                        mkdir($upload_path, 0707);
                        $file = $upload_path . 'index.php';
                        $f = @fopen($file, 'w');
                        @fwrite($f, '');
                        @fclose($f);
                        @chmod($file, 0644);
                    }
                    $upload_path .= cdate('m') . '/';
                    if (is_dir($upload_path) === false) {
                        mkdir($upload_path, 0707);
                        $file = $upload_path . 'index.php';
                        $f = @fopen($file, 'w');
                        @fwrite($f, '');
                        @fclose($f);
                        @chmod($file, 0644);
                    }

                    $uploadconfig = '';
                    $uploadconfig['upload_path'] = $upload_path;
                    $uploadconfig['allowed_types'] = 'jpg|jpeg|png|gif';
                    $uploadconfig['max_size'] = '2000';
                    $uploadconfig['max_width'] = '1000';
                    $uploadconfig['max_height'] = '1000';
                    $uploadconfig['encrypt_name'] = true;

                    $this->upload->initialize($uploadconfig);

                    if ($this->upload->do_upload('user_icon')) {
                        $img = $this->upload->data();
                        $updateicon = cdate('Y') . '/' . cdate('m') . '/' . $img['file_name'];
                    } else {
                        $file_error2 = $this->upload->display_errors();

                    }
                }
            }
        }

        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($form_validation === false OR  $file_error !== '' OR $file_error2 !== '') {


            $view['view']['message'] = $file_error . $file_error2;

            $html_content = '';
            $k = 0;
            if ($form && is_array($form)) {
                foreach ($form as $key => $value) {
                    if ( ! element('use', $value)) {
                        continue;
                    }
                    if ($key === 'user_password') {
                        continue;
                    }

                    $required = element('required', $value) ? 'required' : '';

                    $item = $this->userlib->item(element('field_name', $value));
                    $html_content[$k]['field_name'] = element('field_name', $value);
                    $html_content[$k]['display_name'] = element('display_name', $value);
                    $html_content[$k]['input'] = '';

                    //field_type : text, url, email, phone, textarea, radio, select, checkbox, date
                    if (element('field_type', $value) === 'text'
                        OR element('field_type', $value) === 'url'
                        OR element('field_type', $value) === 'email'
                        OR element('field_type', $value) === 'phone'
                        OR element('field_type', $value) === 'date') {
                        if (element('field_type', $value) === 'date') {
                            $html_content[$k]['input'] .= '<input type="text" id="' . element('field_name', $value) . '" name="' . element('field_name', $value) . '" class="form-control input datepicker" value="' . set_value(element('field_name', $value), $item) . '" readonly="readonly" ' . $required . ' />';
                        } elseif (element('field_type', $value) === 'phone') {
                            $html_content[$k]['input'] .= '<input type="text" id="' . element('field_name', $value) . '" name="' . element('field_name', $value) . '" class="form-control input validphone" value="' . set_value(element('field_name', $value), $item) . '" ' . $required . ' />';
                        } else {
                            $html_content[$k]['input'] .= '<input type="' . element('field_type', $value) . '" id="' . element('field_name', $value) . '" name="' . element('field_name', $value) . '" class="form-control input" value="' . set_value(element('field_name', $value), $item) . '" ' . $required . ' />';
                        }
                    } elseif (element('field_type', $value) === 'textarea') {
                        $html_content[$k]['input'] .= '<textarea id="' . element('field_name', $value) . '" name="' . element('field_name', $value) . '" class="form-control input" ' . $required . ' >' . set_value(element('field_name', $value), $item) . '</textarea>';
                    } elseif (element('field_type', $value) === 'radio') {
                        $html_content[$k]['input'] .= '<div class="checkbox">';
                        if (element('field_name', $value) === 'user_sex') {
                            $options = array(
                                '1' => '남성',
                                '2' => '여성',
                            );
                        } else {
                            $options = explode("\n", element('options', $value));
                        }
                        $i =1;
                        if ($options) {
                            foreach ($options as $okey => $oval) {
                                $oval = trim($oval);
                                $radiovalue = (element('field_name', $value) === 'user_sex') ? $okey : $oval;
                                $html_content[$k]['input'] .= '<label for="' . element('field_name', $value) . '_' . $i . '"><input type="radio" name="' . element('field_name', $value) . '" id="' . element('field_name', $value) . '_' . $i . '" value="' . $radiovalue . '" ' . set_radio(element('field_name', $value), $radiovalue, ($item === $radiovalue ? true : false)) . ' /> ' . $oval . ' </label> ';
                            $i++;
                            }
                        }
                        $html_content[$k]['input'] .= '</div>';
                    } elseif (element('field_type', $value) === 'checkbox') {
                        $html_content[$k]['input'] .= '<div class="checkbox">';
                        $options = explode("\n", element('options', $value));
                        $item = json_decode($item, true);
                        $i =1;
                        if ($options) {
                            foreach ($options as $okey => $oval) {
                                $oval = trim($oval);
                                $chkvalue = is_array($item) && in_array($oval, $item) ? $oval : '';
                                $html_content[$k]['input'] .= '<label for="' . element('field_name', $value) . '_' . $i . '"><input type="checkbox" name="' . element('field_name', $value) . '[]" id="' . element('field_name', $value) . '_' . $i . '" value="' . $oval . '" ' . set_checkbox(element('field_name', $value), $oval, ($chkvalue === $oval ? true : false)) . ' /> ' . $oval . ' </label> ';
                            $i++;
                            }
                        }
                        $html_content[$k]['input'] .= '</div>';
                    } elseif (element('field_type', $value) === 'select') {
                        $html_content[$k]['input'] .= '<div class="input-group">';
                        $html_content[$k]['input'] .= '<select name="' . element('field_name', $value) . '" class="form-control input" ' . $required . '>';
                        $html_content[$k]['input'] .= '<option value="" >선택하세요</option> ';
                        $options = explode("\n", element('options', $value));
                        if ($options) {
                            foreach ($options as $okey => $oval) {
                                $oval = trim($oval);
                                $html_content[$k]['input'] .= '<option value="' . $oval . '" ' . set_select(element('field_name', $value), $oval, ($item === $oval ? true : false)) . ' >' . $oval . '</option> ';
                            }
                        }
                        $html_content[$k]['input'] .= '</select>';
                        $html_content[$k]['input'] .= '</div>';
                    } elseif (element('field_name', $value) === 'user_address') {
                        $html_content[$k]['input'] .= '
                            <label for="user_zipcode">우편번호</label>
                            <label>
                                <input type="text" name="user_zipcode" value="' . set_value('user_zipcode', $this->userlib->item('user_zipcode')) . '" id="user_zipcode" class="form-control input" size="7" maxlength="7" ' . $required . ' />
                            </label>
                            <label>
                                <button type="button" class="btn btn-black btn-sm" style="margin-top:0px;" onclick="win_zip(\'fregisterform\', \'user_zipcode\', \'user_address1\', \'user_address2\', \'user_address3\', \'user_address4\');">주소 검색</button>
                            </label>
                            <div class="addr-line mt10">
                                <label for="user_address1">기본주소</label>
                                <input type="text" name="user_address1" value="' . set_value('user_address1', $this->userlib->item('user_address1')) . '" id="user_address1" class="form-control input" placeholder="기본주소" ' . $required . ' />
                            </div>
                            <div class="addr-line mt10 ">
                                <label for="user_address2">상세주소</label>
                                <input type="text" name="user_address2" value="' . set_value('user_address2', $this->userlib->item('user_address2')) . '" id="user_address2" class="form-control input" placeholder="상세주소" ' . $required . ' />
                            </div>
                            <div class="addr-line mt10 ">
                                <label for="user_address3">참고항목</label>
                                <input type="text" name="user_address3" value="' . set_value('user_address3', $this->userlib->item('user_address3')) . '" id="user_address3" class="form-control input" readonly="readonly" placeholder="참고항목" />
                            </div>
                            <input type="hidden" name="user_address4" value="' . set_value('user_address4', $this->userlib->item('user_address4')) . '" />
                        ';
                    }

                    $html_content[$k]['description'] = '';
                    if (isset($configbasic[$value['field_name']]['description']) && $configbasic[$value['field_name']]['description']) {
                        $html_content[$k]['description'] = $configbasic[$value['field_name']]['description'];
                    }
                    $k++;
                }
            }

            $view['view']['html_content'] = $html_content;

        
            /**
             * 레이아웃을 정의합니다
             */
            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'user_modify',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));

        } else {
            /**
             * 유효성 검사를 통과한 경우입니다.
             * 즉 데이터의 insert 나 update 의 process 처리가 필요한 상황입니다
             */


            $updatedata = array();
            $metadata = array();
            $updatedata['user_email'] = $this->input->post('user_email');
            if ($this->userlib->item('user_email') !== $this->input->post('user_email')) {
                $updatedata['user_email_cert'] = 0;
                $metadata['meta_email_cert_datetime'] = '';
            }
            if (isset($form['user_homepage']['use']) && $form['user_homepage']['use']) {
                $updatedata['user_homepage'] = $this->input->post('user_homepage', null, '');
            }
            if (isset($form['user_phone']['use']) && $form['user_phone']['use']) {
                $updatedata['user_phone'] = $this->input->post('user_phone', null, '');
            }
            if (isset($form['user_birthday']['use']) && $form['user_birthday']['use']) {
                $updatedata['user_birthday'] = $this->input->post('user_birthday', null, '');
            }
            if (isset($form['user_sex']['use']) && $form['user_sex']['use']) {
                $updatedata['user_sex'] = $this->input->post('user_sex', null, '');
            }
            if (isset($form['user_address']['use']) && $form['user_address']['use']) {
                $updatedata['user_zipcode'] = $this->input->post('user_zipcode', null, '');
                $updatedata['user_address1'] = $this->input->post('user_address1', null, '');
                $updatedata['user_address2'] = $this->input->post('user_address2', null, '');
                $updatedata['user_address3'] = $this->input->post('user_address3', null, '');
                $updatedata['user_address4'] = $this->input->post('user_address4', null, '');
            }
            $updatedata['user_receive_email'] = $this->input->post('user_receive_email') ? 1 : 0;

            if ($this->input->post('user_photo_del')) {
                $updatedata['user_photo'] = '';
            } elseif ($updatephoto) {
                $updatedata['user_photo'] = $updatephoto;
            }
            if ($this->userlib->item('user_photo')
                && ($this->input->post('user_photo_del') OR $updatephoto)) {
                // 기존 파일 삭제
                @unlink(config_item('uploads_dir') . '/user_photo/' . $this->userlib->item('user_photo'));
            }
            if ($this->input->post('user_icon_del')) {
                $updatedata['user_icon'] = '';
            } elseif ($updateicon) {
                $updatedata['user_icon'] = $updateicon;
            }
            if ($this->userlib->item('user_icon')
                && ($this->input->post('user_icon_del') OR $updateicon)) {
                // 기존 파일 삭제
                @unlink(config_item('uploads_dir') . '/user_icon/' . $this->userlib->item('user_icon'));
            }

            $this->User_model->update($user_id, $updatedata);
            $this->User_meta_model->save($user_id, $metadata);


            if ($this->configlib->item('use_register_email_auth')
                && $this->userlib->item('user_email') !== $this->input->post('user_email')) {

                $vericode = array('$', '/', '.');
                $verificationcode = str_replace(
                    $vericode,
                    '',
                    password_hash($user_id . '-' . $this->input->post('user_email') . '-' . random_string('alnum', 10), PASSWORD_BCRYPT)
                );

                $beforeauthdata = array(
                    'user_id' => $user_id,
                    'uae_type' => 2,
                );
                $this->User_auth_email_model->delete_where($beforeauthdata);
                $authdata = array(
                    'user_id' => $user_id,
                    'uae_key' => $verificationcode,
                    'uae_type' => 2,
                    'uae_generate_datetime' => cdate('Y-m-d H:i:s'),
                );
                $this->User_auth_email_model->insert($authdata);

                $verify_url = site_url('verify/confirmemail?user=' . $this->userlib->item('user_id') . '&code=' . $verificationcode);

                $searchconfig = array(
                    '{홈페이지명}',
                    '{홈페이지주소}',
                    '{회원명}',
                    '{회원이메일}',
                    '{변경전이메일}',
                    '{메일수신여부}',
                    '{회원아이피}',
                    '{메일인증주소}',
                );
                $receive_email = $this->userlib->item('user_receive_email') ? '동의' : '거부';
                $replaceconfig = array(
                    $this->configlib->item('site_title'),
                    site_url(),
                    $this->userlib->item('user_username'),
                    $this->input->post('user_email'),
                    $this->userlib->item('user_email'),
                    $receive_email,
                    $this->input->ip_address(),
                    $verify_url,
                );

                $replaceconfig_escape = array(
                    html_escape($this->configlib->item('site_title')),
                    site_url(),
                    html_escape($this->userlib->item('user_username')),
                    html_escape($this->input->post('user_email')),
                    html_escape($this->userlib->item('user_email')),
                    $receive_email,
                    $this->input->ip_address(),
                    $verify_url,
                );

                $title = str_replace(
                    $searchconfig,
                    $replaceconfig,
                    $this->configlib->item('send_email_changeemail_user_title')
                );
                $content = str_replace(
                    $searchconfig,
                    $replaceconfig_escape,
                    $this->configlib->item('send_email_changeemail_user_content')
                );

                $this->email->clear(true);
                $this->email->from($this->configlib->item('webmaster_email'), $this->configlib->item('webmaster_name'));
                $this->email->to($this->input->post('user_email'));
                $this->email->subject($title);
                $this->email->message($content);
                $this->email->send();

                $view['view']['result_message'] = $this->input->post('user_email') . '로 인증메일이 발송되었습니다. <br />발송된 인증메일을 확인하신 후에 사이트 이용이 가능합니다';

                $this->session->sess_destroy();

            } else {
                $view['view']['result_message'] = '회원정보가 변경되었습니다. <br />감사합니다';
            }


            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'user_modify_result',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));
        }
    }

    /**
     * 소셜로그인 한 회원의 회원정보 수정 페이지입니다
     */
    public function defaultinfo()
    {

        /**
         * 로그인이 필요한 페이지입니다
         */
        required_user_login();

        $user_id = (int) $this->userlib->item('user_id');

        if ($this->userlib->item('user_password')) {
            redirect('usermodify');
        }

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

        $view = array();
        $view['view'] = array();



        $password_length = $this->configlib->item('password_length');
        $view['view']['password_length'] = $password_length;

        $config = array();

        $config['user_password'] = array(
            'field' => 'user_password',
            'label' => '패스워드',
            'rules' => 'trim|required|min_length[' . $password_length . ']|callback__user_password_check',
        );
        $config['user_password_re'] = array(
            'field' => 'user_password_re',
            'label' => '패스워드 확인',
            'rules' => 'trim|required|min_length[' . $password_length . ']|matches[user_password]',
        );
        $config['user_username'] = array(
            'field' => 'user_username',
            'label' => '회원명',
            'rules' => 'trim|required|min_length[2]|max_length[20]|callback__user_username_check',
        );
        $config['user_email'] = array(
            'field' => 'user_email',
            'label' => '이메일',
            'rules' => 'trim|required|valid_email|max_length[50]|is_unique[user.user_email.user_id.' . $user_id . ']|callback__user_email_check',
        );

        $this->load->library(array('form_validation'));

        $this->form_validation->set_rules($config);
        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($this->form_validation->run() === false) {


            /**
             * 레이아웃을 정의합니다
             */
            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'user_defaultinfo',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));

        } else {
            /**
             * 유효성 검사를 통과한 경우입니다.
             * 즉 데이터의 insert 나 update 의 process 처리가 필요한 상황입니다
             */


            $updatedata = array();
            $metadata = array();

            $updatedata['user_email'] = $this->input->post('user_email');
            if ($this->userlib->item('user_email') !== $this->input->post('user_email')) {
                $updatedata['user_email_cert'] = 0;
                $metadata['meta_email_cert_datetime'] = '';
            }

            $updatedata['user_password'] = password_hash($this->input->post('user_password'), PASSWORD_BCRYPT);

            $this->User_model->update($user_id, $updatedata);
            $this->User_meta_model->save($user_id, $metadata);

            if ($this->configlib->item('use_register_email_auth')
                && $this->userlib->item('user_email') !== $this->input->post('user_email')) {

                $vericode = array('$', '/', '.');
                $verificationcode = str_replace(
                    $vericode,
                    '',
                    password_hash($user_id . '-' . $this->input->post('user_email') . '-' . random_string('alnum', 10), PASSWORD_BCRYPT)
                );

                $beforeauthdata = array(
                    'user_id' => $user_id,
                    'uae_type' => 2,
                );
                $this->User_auth_email_model->delete_where($beforeauthdata);
                $authdata = array(
                    'user_id' => $user_id,
                    'uae_key' => $verificationcode,
                    'uae_type' => 2,
                    'uae_generate_datetime' => cdate('Y-m-d H:i:s'),
                );
                $this->User_auth_email_model->insert($authdata);

                $verify_url = site_url('verify/confirmemail?user=' . $this->input->post('user_id') . '&code=' . $verificationcode);

                $searchconfig = array(
                    '{홈페이지명}',
                    '{홈페이지주소}',
                    '{회원명}',
                    '{회원이메일}',
                    '{변경전이메일}',
                    '{메일수신여부}',
                    '{회원아이피}',
                    '{메일인증주소}',
                );
                $receive_email = $this->userlib->item('user_receive_email') ? '동의' : '거부';
                $replaceconfig = array(
                    $this->configlib->item('site_title'),
                    site_url(),
                    $this->userlib->item('user_username'),
                    $this->input->post('user_email'),
                    $this->userlib->item('user_email'),
                    $receive_email,
                    $this->input->ip_address(),
                    $verify_url,
                );

                $replaceconfig_escape = array(
                    html_escape($this->configlib->item('site_title')),
                    site_url(),
                    html_escape($this->userlib->item('user_username')),
                    html_escape($this->input->post('user_email')),
                    html_escape($this->userlib->item('user_email')),
                    $receive_email,
                    $this->input->ip_address(),
                    $verify_url,
                );

                $title = str_replace(
                    $searchconfig,
                    $replaceconfig,
                    $this->configlib->item('send_email_changeemail_user_title')
                );
                $content = str_replace(
                    $searchconfig,
                    $replaceconfig_escape,
                    $this->configlib->item('send_email_changeemail_user_content')
                );

                $this->email->clear(true);
                $this->email->from($this->configlib->item('webmaster_email'), $this->configlib->item('webmaster_name'));
                $this->email->to($this->input->post('user_email'));
                $this->email->subject($title);
                $this->email->message($content);
                $this->email->send();

                $view['view']['result_message'] = $this->input->post('user_email') . '로 인증메일이 발송되었습니다. <br />발송된 인증메일을 확인하신 후에 사이트 이용이 가능합니다';


            } else {
                $view['view']['result_message'] = '회원정보가 변경되었습니다. <br />감사합니다';
            }

            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'user_modify_result',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));
        }
    }


    /**
     * 회원정보 수정중 패스워드 변경 페이지입니다
     */
    public function password_modify()
    {

        /**
         * 로그인이 필요한 페이지입니다
         */
        required_user_login();

        $user_id = (int) $this->userlib->item('user_id');

        if ( ! $this->session->userdata('usermodify')) {
            redirect('usermodify');
        }

        $view = array();
        $view['view'] = array();


        /**
         * Validation 라이브러리를 가져옵니다
         */
        $this->load->library('form_validation');

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

        /**
         * 전송된 데이터의 유효성을 체크합니다
         */

        $password_length = $this->configlib->item('password_length');
        $view['view']['password_length'] = $password_length;

        $config = array(
            array(
                'field' => 'cur_password',
                'label' => '현재패스워드',
                'rules' => 'trim|required|callback__cur_password_check',
            ),
            array(
                'field' => 'new_password',
                'label' => '새로운패스워드',
                'rules' => 'trim|required|min_length[' . $password_length . ']|callback__user_password_check',
            ),
            array(
                'field' => 'new_password_re',
                'label' => '새로운패스워드',
                'rules' => 'trim|required|min_length[' . $password_length . ']|matches[new_password]',
            ),
        );
        $this->form_validation->set_rules($config);

        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($this->form_validation->run() === false) {



            $password_description = '비밀번호는 ' . $password_length . '자리 이상이어야 ';
            if ($this->configlib->item('password_uppercase_length')
                OR $this->configlib->item('password_numbers_length')
                OR $this->configlib->item('password_specialchars_length')) {
                $password_description .= '하며 ';
                if ($this->configlib->item('password_uppercase_length')) {
                    $password_description .= ', ' . $this->configlib->item('password_uppercase_length') . '개의 대문자';
                }
                if ($this->configlib->item('password_numbers_length')) {
                    $password_description .= ', ' . $this->configlib->item('password_numbers_length') . '개의 숫자';
                }
                if ($this->configlib->item('password_specialchars_length')) {
                    $password_description .= ', ' . $this->configlib->item('password_specialchars_length') . '개의 특수문자';
                }
                $password_description .= '를 포함해야 ';
            }
            $password_description .= '합니다';

            $view['view']['info'] = $password_description;

        
            /**
             * 레이아웃을 정의합니다
             */
            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'password_modify',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));

        } else {


            $hash = password_hash($this->input->post('new_password'), PASSWORD_BCRYPT);

            $updatedata = array(
                'user_password' => $hash,
            );
            $this->User_model->update($user_id, $updatedata);
            $metadata = array(
                'meta_change_pw_datetime' => cdate('Y-m-d H:i:s'),
            );
            $this->User_meta_model->save($user_id, $metadata);


            $emailsendlistadmin = array();
            $emailsendlistuser = array();

            $superadminlist = '';
            if ($this->configlib->item('send_email_changepw_admin')) {
                $mselect = 'user_id, user_email, user_username, user_phone';
                $superadminlist = $this->User_model->get_superadmin_list($mselect);
            }
            if ($this->configlib->item('send_email_changepw_admin') && $superadminlist) {
                foreach ($superadminlist as $key => $value) {
                    $emailsendlistadmin[$value['user_id']] = $value;
                }
            }
            if (($this->configlib->item('send_email_changepw_user') && $this->userlib->item('user_receive_email'))
                OR $this->configlib->item('send_email_changepw_alluser')) {
                $emailsendlistuser['user_email'] = $this->userlib->item('user_email');
            }

            $searchconfig = array(
                '{홈페이지명}',
                '{홈페이지주소}',
                '{회원명}',
                '{회원이메일}',
                '{메일수신여부}',
                '{회원아이피}',
            );
            $receive_email = $this->userlib->item('user_receive_email') ? '동의' : '거부';
            $replaceconfig = array(
                $this->configlib->item('site_title'),
                site_url(),
                $this->userlib->item('user_username'),
                $this->userlib->item('user_email'),
                $receive_email,
                $this->input->ip_address(),
            );
            $replaceconfig_escape = array(
                html_escape($this->configlib->item('site_title')),
                site_url(),
                html_escape($this->userlib->item('user_username')),
                html_escape($this->userlib->item('user_email')),
                $receive_email,
                $this->input->ip_address(),
            );
            if ($emailsendlistadmin) {
                $title = str_replace(
                    $searchconfig,
                    $replaceconfig,
                    $this->configlib->item('send_email_changepw_admin_title')
                );
                $content = str_replace(
                    $searchconfig,
                    $replaceconfig_escape,
                    $this->configlib->item('send_email_changepw_admin_content')
                );
                foreach ($emailsendlistadmin as $akey => $aval) {
                    $this->email->clear(true);
                    $this->email->from($this->configlib->item('webmaster_email'), $this->configlib->item('webmaster_name'));
                    $this->email->to(element('user_email', $aval));
                    $this->email->subject($title);
                    $this->email->message($content);
                    $this->email->send();
                }
            }
            if ($emailsendlistuser) {
                $title = str_replace(
                    $searchconfig,
                    $replaceconfig,
                    $this->configlib->item('send_email_changepw_user_title')
                );
                $content = str_replace(
                    $searchconfig,
                    $replaceconfig_escape,
                    $this->configlib->item('send_email_changepw_user_content')
                );
                $this->email->clear(true);
                $this->email->from($this->configlib->item('webmaster_email'), $this->configlib->item('webmaster_name'));
                $this->email->to(element('user_email', $emailsendlistuser));
                $this->email->subject($title);
                $this->email->message($content);
                $this->email->send();
            }
            $view['view']['result_message'] = '회원님의 패스워드가 변경되었습니다';

            /**
             * 레이아웃을 정의합니다
             */
            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'user_modify_result',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));
        }
    }


    /**
     * 회원탈퇴 페이지입니다
     */
    public function userleave()
    {

        /**
         * 로그인이 필요한 페이지입니다
         */
        required_user_login();

        $user_id = (int) $this->userlib->item('user_id');

        $view = array();
        $view['view'] = array();


        $this->load->library(array('form_validation'));
        $login_fail = false;
        $valid_fail = false;

        /**
         * 전송된 데이터의 유효성을 체크합니다
         */
        $config = array(
            array(
                'field' => 'user_password',
                'label' => '패스워드',
                'rules' => 'trim|required|min_length[4]|callback__cur_password_check',
            ),
        );
        $this->form_validation->set_rules($config);
        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($this->form_validation->run() === false) {


            /**
             * 레이아웃을 정의합니다
             */
            if ($this->userlib->is_admin() === 'super') {
                $skin = 'user_admin';
            } else {
                $skin = 'userleave_password';
            }

            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => $skin,
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));

        } else {
            /**
             * 유효성 검사를 통과한 경우입니다.
             * 즉 데이터의 insert 나 update 의 process 처리가 필요한 상황입니다
             */


            $emailsendlistadmin = array();
            $emailsendlistuser = array();

            $superadminlist = '';
            if ($this->configlib->item('send_email_userleave_admin')) {
                $mselect = 'user_id, user_email, user_username, user_phone';
                $superadminlist = $this->User_model->get($mselect);
            }

            if ($this->configlib->item('send_email_userleave_admin') && $superadminlist) {
                foreach ($superadminlist as $key => $value) {
                    $emailsendlistadmin[$value['user_id']] = $value;
                }
            }
            if (($this->configlib->item('send_email_userleave_user') && $this->userlib->item('user_receive_email'))
                OR $this->configlib->item('send_email_userleave_alluser')) {
                $emailsendlistuser['user_email'] = $this->userlib->item('user_email');
            }

            $searchconfig = array(
                '{홈페이지명}',
                '{홈페이지주소}',
                '{회원명}',
                '{회원이메일}',
                '{메일수신여부}',
                '{회원아이피}',
            );
            $receive_email = $this->userlib->item('user_receive_email') ? '동의' : '거부';
            $replaceconfig = array(
                $this->configlib->item('site_title'),
                site_url(),
                $this->userlib->item('user_username'),
                $this->userlib->item('user_email'),
                $receive_email,
                $this->input->ip_address(),
            );
            $replaceconfig_escape = array(
                html_escape($this->configlib->item('site_title')),
                site_url(),
                html_escape($this->userlib->item('user_username')),
                html_escape($this->userlib->item('user_email')),
                $receive_email,
                $this->input->ip_address(),
            );
            if ($emailsendlistadmin) {
                $title = str_replace(
                    $searchconfig,
                    $replaceconfig,
                    $this->configlib->item('send_email_userleave_admin_title')
                );
                $content = str_replace(
                    $searchconfig,
                    $replaceconfig_escape,
                    $this->configlib->item('send_email_userleave_admin_content')
                );
                foreach ($emailsendlistadmin as $akey => $aval) {
                    $this->email->clear(true);
                    $this->email->from($this->configlib->item('webmaster_email'), $this->configlib->item('webmaster_name'));
                    $this->email->to(element('user_email', $aval));
                    $this->email->subject($title);
                    $this->email->message($content);
                    $this->email->send();
                }
            }
            if ($emailsendlistuser) {
                $title = str_replace(
                    $searchconfig,
                    $replaceconfig,
                    $this->configlib->item('send_email_userleave_user_title')
                );
                $content = str_replace(
                    $searchconfig,
                    $replaceconfig_escape,
                    $this->configlib->item('send_email_userleave_user_content')
                );
                $this->email->clear(true);
                $this->email->from($this->configlib->item('webmaster_email'), $this->configlib->item('webmaster_name'));
                $this->email->to(element('user_email', $emailsendlistuser));
                $this->email->subject($title);
                $this->email->message($content);
                $this->email->send();
            }

            $this->userlib->delete_user($user_id);
            $this->session->sess_destroy();

        
            /**
             * 레이아웃을 정의합니다
             */
            $layoutconfig = array(
                'path' => 'mypage',
                'layout' => 'layout',
                'skin' => 'userleave',
            );
            $view['layout'] = $this->layoutlib->front($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));
        }
    }



    /**
     * 회원명체크 함수입니다
     */
    public function _user_username_check($str)
    {
        if ($str === $this->userlib->item('user_username')) {
            return true;
        }

        $this->load->helper('chkstring');
        if (chkstring($str, _HANGUL_ + _ALPHABETIC_ + _NUMERIC_) === false) {
            $this->form_validation->set_message(
                '_user_username_check',
                '회원명은 공백없이 한글, 영문, 숫자만 입력 가능합니다'
            );
            return false;
        }

        if (preg_match("/[\,]?{$str}/i", $this->configlib->item('denied_username_list'))) {
            $this->form_validation->set_message(
                '_user_username_check',
                $str . ' 은(는) 예약어로 사용하실 수 없는 회원명입니다'
            );
            return false;
        }

        return true;
    }


    /**
     * 이메일 체크 함수입니다
     */
    public function _user_email_check($str)
    {
        list($emailid, $emaildomain) = explode('@', $str);
        $denied_list = explode(',', $this->configlib->item('denied_email_list'));
        $emaildomain = trim($emaildomain);
        $denied_list = array_map('trim', $denied_list);
        if (in_array($emaildomain, $denied_list)) {
            $this->form_validation->set_message(
                '_user_email_check',
                $emaildomain . ' 은(는) 사용하실 수 없는 이메일입니다'
            );
            return false;
        }
        return true;
    }


    /**
     * 현재 패스워드가 맞는지 체크합니다
     */
    public function _cur_password_check($str)
    {
         if ( ! function_exists('password_hash')) {
            $this->load->helper('password');
        }

        if ( ! $this->userlib->item('user_id') OR ! $this->userlib->item('user_password')) {
            $this->form_validation->set_message(
                '_cur_password_check',
                '패스워드가 맞지 않습니다'
            );
            return false;
        } elseif ( ! password_verify($str, $this->userlib->item('user_password'))) {
            $this->form_validation->set_message(
                '_cur_password_check',
                '패스워드가 맞지 않습니다'
            );
            return false;
        }
        return true;
    }


    /**
     * 새로운 패스워드가 환경설정에 정한 글자수를 채웠는지를 체크합니다
     */
    public function _user_password_check($str)
    {
        $uppercase = $this->configlib->item('password_uppercase_length');
        $number = $this->configlib->item('password_numbers_length');
        $specialchar = $this->configlib->item('password_specialchars_length');

        $this->load->helper('chkstring');
        $str_uc = count_uppercase($str);
        $str_num = count_numbers($str);
        $str_spc = count_specialchars($str);

        if ($str_uc < $uppercase OR $str_num < $number OR $str_spc < $specialchar) {

            $description = '비밀번호는 ';
            if ($str_uc < $uppercase) {
                $description .= ' ' . $uppercase . '개 이상의 대문자';
            }
            if ($str_num < $number) {
                $description .= ' ' . $number . '개 이상의 숫자';
            }
            if ($str_spc < $specialchar) {
                $description .= ' ' . $specialchar . '개 이상의 특수문자';
            }
            $description .= '를 포함해야 합니다';

            $this->form_validation->set_message(
                '_user_password_check',
                $description
            );
            return false;
        }
        return true;
    }
}
