<?php
/**
 * Members Management
 *
 */
require_once (dirname(__FILE__) . "/ADMIN_Controller.php");

class Members extends ADMIN_Controller {

    function Members()
    {
        parent::ADMIN_Controller();
        $this->load->model('User_model');
        $this->load->model('Common_model');
        $this->load->library('session');
    }
    
    public function index($hotelid)
    {
        $this->load->helper(array('form', 'url'));
        redirect('admin/members/page/' . $hotelid);
    }
    
    /**
     * 会員リストを表示する
     */
    public function page($hotelid, $offset = 0)
    {
        
        $this->load->helper(array('MY_form', 'MY_url'));
        
        $limit = 20;    // 1ページ表示件数
        
        //$this->db->order_by('ordering ASC');
        $this->db->where('status >=', 0);
        $this->db->where('hotelid', $hotelid);
        $this->db->limit($limit, $offset);
        $query = $this->db->get('members');
        $data['members'] = $query->result_array();
        
        $this->load->library('session');
        $this->load->library('pagination');
        
        // 総レコード数の取得
        $this->db->where('status >', 0);
        $query = $this->db->get('members');
        $total_rows = $query->num_rows();
        
        $pager_config['uri_segment'] = 4;
        $pager_config['base_url'] = base_url() . 'admin/members/page/';
        $pager_config['total_rows'] = $total_rows;
        $pager_config['per_page'] = $limit;
        
        $this->pagination->initialize($pager_config);
        
        $data['links'] = $this->pagination->create_links();
        
        $this->load->vars($data);
        
        $this->load->view('admin/members/page');
    }
    
    /**
     * 管理者による会員登録
     */
    public function add($hotelid)
    {
        $this->load->helper(array('MY_form', 'MY_url'));
        
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        
        $this->form_validation->set_rules('email', 'メールアドレス', 'required|valid_email|trim|xss_clean');
        $this->form_validation->set_rules('password', 'パスワード', 'required|trim|xss_clean');
        $this->form_validation->set_rules('name', '氏名', 'required|trim|xss_clean');
        $this->form_validation->set_rules('name_kana', '氏名(かな)', 'required|trim|xss_clean|callback_hiragana_check');
        $this->form_validation->set_rules('postcode', '郵便番号', 'required|trim|xss_clean|callback_postcode_check');
        $this->form_validation->set_rules('prefecture', '都道府県', 'required|trim|xss_clean');
        $this->form_validation->set_rules('city', '市区町村', 'required|trim|xss_clean');
        $this->form_validation->set_rules('street', '番地', 'required|trim|xss_clean');
        $this->form_validation->set_rules('phone', '電話番号', 'required|trim|xss_clean|callback_phone_check');
        
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('admin/members/add');
            return;
        }
        else
        {
            // 同じEメールアドレスが登録済みでないことをチェックする
            $this->db->where('email', set_value('email'));
            $this->db->where('status >= ', 0);
            $this->db->where('hotelid', $hotelid);
            $query = $this->db->get('members', 1);
            if ($query->num_rows() > 0)
            {
                $data['error'] = array();
                $data['error'][] = '同じEメールアドレスがすでに登録されています。';
                $this->load->vars($data);
                $this->load->view('admin/members/add');
                return;
            }
            
            $memberid = $this->Common_model->getMemberId();
            $data = array(
                'memberid' => $memberid,
                'hotelid' => $hotelid,
                'name' => set_value('name'),
                'name_kana' => set_value('name_kana'),
                'email' => set_value('email'),
                'postcode' => set_value('postcode'),
                'prefecture' => set_value('prefecture'),
                'city' => set_value('city'),
                'street' => set_value('street'),
                'phone' => set_value('phone'),
                'password' => sha1(set_value('password')),
                'status' => 1);
            $this->db->insert('members', $data);
            redirect('admin/members/index/' . $hotelid);
        }
        
        $this->load->view('admin/members/add');
    }
    
    /**
     * 会員情報の編集
     */
    public function edit($hotelid, $memberid)
    {
        $this->load->helper(array('MY_form', 'MY_url'));
        
        $data['memberid'] = $memberid;
        $this->load->vars($data);
        
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        
        $this->form_validation->set_rules('email', 'メールアドレス', 'required|valid_email|trim|xss_clean');
        $this->form_validation->set_rules('password', 'パスワード', 'trim|xss_clean');
        $this->form_validation->set_rules('name', '氏名', 'required|trim|xss_clean');
        $this->form_validation->set_rules('name_kana', '氏名(かな)', 'required|trim|xss_clean|callback_hiragana_check');
        $this->form_validation->set_rules('postcode', '郵便番号', 'required|trim|xss_clean|callback_postcode_check');
        $this->form_validation->set_rules('prefecture', '都道府県', 'required|trim|xss_clean');
        $this->form_validation->set_rules('city', '市区町村', 'required|trim|xss_clean');
        $this->form_validation->set_rules('street', '番地', 'required|trim|xss_clean');
        $this->form_validation->set_rules('phone', '電話番号', 'required|trim|xss_clean|callback_phone_check');
        
        if (!$this->input->post('submit'))
        {
            $this->db->where('memberid', $memberid);
            $this->db->where('hotelid', $hotelid);
            $this->db->where('status >=', 0);
            $query = $this->db->get('members', 1);
            if ($query->num_rows() > 0)
            {
                $row = $query->row_array();
                $data['name'] = $row['name'];
                $data['name_kana'] = $row['name_kana'];
                $data['email'] = $row['email'];
                $data['password'] = '';
                $data['postcode'] = $row['postcode'];
                $data['prefecture'] = $row['prefecture'];
                $data['city'] = $row['city'];
                $data['street'] = $row['street'];
                $data['phone'] = $row['phone'];
                $this->load->vars($data);
            }
        }
        
        if ($this->form_validation->run() == FALSE)
        {
        }
        else
        {
            // 同じEメールアドレスが登録済みでないことをチェックする
            $this->db->where('email', set_value('email'));
            $this->db->where('memberid <> ', $memberid);    // 自分以外
            $this->db->where('status >= ', 0);
            $query = $this->db->get('members', 1);
            if ($query->num_rows() > 0)
            {
                $data['error'] = array();
                $data['error'][] = '同じEメールアドレスがすでに登録されています。';
                $this->load->vars($data);
                $this->load->view('admin/members/edit');
                return;
            }
            
            if (set_value('password') != '')
            {
                $data = array(
                    'name' => set_value('name'),
                    'name_kana' => set_value('name_kana'),
                    'email' => set_value('email'),
                    'postcode' => set_value('postcode'),
                    'prefecture' => set_value('prefecture'),
                    'city' => set_value('city'),
                    'street' => set_value('street'),
                    'phone' => set_value('phone'),
                    'password' => sha1(set_value('password')));
            }
            else
            {
                // パスワード入力がないときはパスワードを変更しない。
                $data = array(
                    'name' => set_value('name'),
                    'name_kana' => set_value('name_kana'),
                    'email' => set_value('email'),
                    'postcode' => set_value('postcode'),
                    'prefecture' => set_value('prefecture'),
                    'city' => set_value('city'),
                    'street' => set_value('street'),
                    'phone' => set_value('phone'));
            }
            $this->db->where('memberid', $memberid);
            $this->db->update('members', $data);
            redirect('admin/members/index/' . $hotelid);
        }
        
        $this->load->view('admin/members/edit');
    }
    
    /**
     * 会員の削除
     */
    public function delete($hotelid, $memberid)
    {
        $this->load->helper(array('form', 'url'));
        
        $data = array('status' => -1);
        $this->db->where('memberid', $memberid);
        $this->db->update('members', $data);
        
        redirect('admin/members/index/' . $hotelid);
    }
    
    /**
     * ひらがな文字列のチェック
     */
    function hiragana_check($str)
    {
        mb_regex_encoding("UTF-8");
        $regex = "^[ぁ-ん]+$";
        if (mb_ereg($regex, $str))
        {
            return true;
        }
        $this->form_validation->set_message('hiragana_check', 'フィールド %s に、ひらがな以外の文字は使えません');
        return false;
    }
    
    /**
     * 電話番号チェック
     */
    function phone_check($str)
    {
        mb_regex_encoding("UTF-8");
        $regex = '/^\d{1,5}-?\d{1,5}-?\d{1,5}$/';
        $regex2 = '/^\d{10,11}$/';
        if (preg_match($regex, $str, $matches) || preg_match($regex2, $str, $matches))
        {
            return true;
        }
        else 
        {
            $this->form_validation->set_message('phone_check', 'フィールド %s が、電話番号の形式になっていません');
            return false;
        }
    }
    
    /**
     * 郵便番号チェック
     */
    function postcode_check($str)
    {
        mb_regex_encoding("UTF-8");
        $regex = '/^\d{3}-?\d{4}$/';
        $regex2 = '/^\d{7}$/';
        if (preg_match($regex, $str, $matches) || preg_match($regex2, $str, $matches))
        {
            return true;
        }
        else
        {
            $this->form_validation->set_message('postcode_check', 'フィールド %s が、郵便番号の形式になっていません');
            return false;
        }
    }
    
    public function logout()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $this->phpsession->clear('admin');
        redirect('admin/login/');
    }
}
