<?php
/**
 *  予約
 */
class Res extends MY_Controller {
    
    function Res()
    {
        parent::MY_Controller();
        $this->load->model('Common_model');
        $this->load->model('Res_model');
        $this->load->model('Hotel_model');
        $this->load->model('User_model');
    }
    
    /**
     * 条件入力
     * 
     * @param $d チェックイン日 YYYYMMDD
     */
    function index($planid, $d)
    {
        $error = array();
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->load->library('phpsession');
        
        $data['planid'] = $planid;
        $data['d'] = $d;
        $this->load->vars($data);
        
        $cin = substr($d, 0, 4) . '-'
             . substr($d, 4, 2) . '-'
             . substr($d, 6, 2);
        
        $this->form_validation->set_rules('cout', 'チェックアウト日', 'required|trim|xss_clean');
        $this->form_validation->set_rules('room_num', '部屋数', 'required|integer|trim|xss_clean');
        $this->form_validation->set_rules('basic_num', '大人人数', 'required|integer|trim|xss_clean');
        $this->form_validation->set_rules('child1_num', '子供A人数', 'required|integer|trim|xss_clean');
        $this->form_validation->set_rules('child2_num', '子供B人数', 'required|integer|trim|xss_clean');
        $this->form_validation->set_rules('child3_num', '子供C人数', 'required|integer|trim|xss_clean');
        $this->form_validation->set_rules('child4_num', '子供D人数', 'required|integer|trim|xss_clean');
        
        $this->db->where('planid', $planid);
        $query = $this->db->get('plans', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['planid'] = $planid;
        $this->load->vars($data);
        
        $roomtypeid = $row['roomtypeid'];
        $this->db->where('roomtypeid', $roomtypeid);
        $query = $this->db->get('roomtypes', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['roomtype_name'] = $row['roomtype_name'];
        $data['roomtypes_guest_min'] = $row['guest_min'];
        $data['roomtypes_guest_max'] = $row['guest_max'];
        $this->load->vars($data);
        
        if (!$this->input->post('mysubmit'))
        {
            $data['room_num'] = 1;
            $data['child1_num'] = 0;
            $data['child2_num'] = 0;
            $data['child3_num'] = 0;
            $data['child4_num'] = 0;
            $this->load->vars($data);
        }
        
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('res/index');
        }
        else
        {
            $cout = set_value('cout');
            $room_num = set_value('room_num');
            $basic_num = set_value('basic_num');
            $child1_num = set_value('child1_num');
            $child2_num = set_value('child2_num');
            $child3_num = set_value('child3_num');
            $child4_num = set_value('child4_num');
            
            // 日付のチェック
            if ($this->Common_model->checkDate($cin) == false)
            {
                $data['error'] = array();
                $data['error'][] = 'チェックインの日付の形式が不正です。';
                $this->load->vars($data);
                $this->load->view('res/index');
                return;
            }
            if ($this->Common_model->checkDate($cout) == false)
            {
                $data['error'] = array();
                $data['error'][] = 'チェックアウトの日付の形式が不正です。';
                $this->load->vars($data);
                $this->load->view('res/index');
                return;
            }
            
            // YYYY-MM-DD -> YYYYMMDD
            $cin2 = $d;
            $cout2 = substr($cout, 0, 4) . substr($cout, 5, 2) . substr($cout, 8, 2);
            $today2 = date("Ymd");
            
            if ($today2 > $cin2)
            {
                $data['error'] = array();
                $data['error'][] = 'チェックインの日付は今日以降を指定します。';
                $this->load->vars($data);
                $this->load->view('res/index');
                return;
            }
            if ($cin2 >= $cout2)
            {
                $data['error'] = array();
                $data['error'][] = 'チェックアウトの日付はチェックインの翌日以降を指定します。';
                $this->load->vars($data);
                $this->load->view('res/index');
                return;
            }
            
            // 入力値をセッションに保存する。
            $this->phpsession->save('cin', $cin);
            $this->phpsession->save('cout', $cout);
            $this->phpsession->save('planid', $planid);
            $this->phpsession->save('room_num', $room_num);
            $this->phpsession->save('basic_num', $basic_num);
            $this->phpsession->save('child1_num', $child1_num);
            $this->phpsession->save('child2_num', $child2_num);
            $this->phpsession->save('child3_num', $child3_num);
            $this->phpsession->save('child4_num', $child4_num);
            
            $ret = $this->Res_model->doRes(Res_model::RESMODE_CHECK, null);
            if ($ret >= 0)
            {
                redirect('res/estimate');
            }
            else
            {
                $s = $this->Res_model->getErrorString($ret);
                $data['error'] = array();
                $data['error'][] = $s;
                $this->load->vars($data);
                $this->load->view('res/index');
            }
        }
    }
    
    /**
     * 見積もり,ユーザ情報入力方法の選択
     * - ログインする
     * - 未登録で予約する
     * - ユーザ登録する
     */
    function estimate()
    {
        $this->load->library('phpsession');
        $this->load->helper(array('form', 'url'));
        
        $planid = $this->phpsession->get('planid');
        $this->db->where('planid', $planid);
        $query = $this->db->get('plans', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['planid'] = $planid;
        $this->load->vars($data);
        
        $roomtypeid = $row['roomtypeid'];
        $this->db->where('roomtypeid', $roomtypeid);
        $query = $this->db->get('roomtypes', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['roomtype_name'] = $row['roomtype_name'];
        $data['roomtypes_guest_min'] = $row['guest_min'];
        $data['roomtypes_guest_max'] = $row['guest_max'];
        $this->load->vars($data);
        
        // ログインしているか？
        if ($this->User_model->isUser() == true)
        {
            $data['isloggedin'] = true;
        }
        else
        {
            $data['isloggedin'] = false;
        }
        $this->load->vars($data);
        
        // 見積画面を表示する
        $this->load->view('res/estimate');
    }
    
    /**
     * ログイン (予約手続き中でのログイン)
     */
    function login()
    {
        $this->load->library('phpsession');
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('email', 'メールアドレス', 'required|valid_email|trim|xss_clean');
        $this->form_validation->set_rules('password', 'パスワード', 'required|trim|xss_clean');
        
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('res/login');
            return;
        }
        else
        {
            $email = set_value('email');
            $password = set_value('password');
            
            // email, passwordをチェックする
            $this->db->where('email', $email);
            $this->db->where('password', sha1($password));
            $this->db->where('status', 2);
            $query = $this->db->get('users', 1);
            if ($query->num_rows() > 0)
            {
                $row = $query->row_array();
                $this->phpsession->save('user',
                    array('userid' => $row['userid'],
                          'name' => $row['name'],
                          'email' => $row['email']));
                redirect('res/userinp');
            }
            else
            {
                $data['error'] = "メールアドレス、またはパスワードが間違っています。";
                $this->load->vars($data);
                $this->load->view('res/login');
                return;
            }
        }
    }
    
    /**
     * ユーザ情報の入力
     */
    function userinp()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        
        $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('email', 'メールアドレス', 'required|valid_email|trim|xss_clean');
        $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');
        $this->form_validation->set_rules('cinhour', 'チェックイン時刻', 'trim|xss_clean');
        $this->form_validation->set_rules('memo', '備考', 'xss_clean');

        // フォームの初期値設定
        // ログインしていくときは、ユーザ情報を初期値に設定する。
        if (!$this->input->post('submit'))
        {
            $user = $this->phpsession->get('user');
            if (!is_null($user))
            {
                $this->db->where('userid', $user['userid']);
                $query = $this->db->get('users', 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['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)
        {
            $this->load->view('res/userinp');
        }
        else
        {
            // ユーザ情報をセッションに保存する
            $this->phpsession->save('name', set_value('name'));
            $this->phpsession->save('name_kana', set_value('name_kana'));
            $this->phpsession->save('email', set_value('email'));
            $this->phpsession->save('postcode', set_value('postcode'));
            $this->phpsession->save('prefecture', set_value('prefecture'));
            $this->phpsession->save('city', set_value('city'));
            $this->phpsession->save('street', set_value('street'));
            $this->phpsession->save('phone', set_value('phone'));
            $this->phpsession->save('cinhour', set_value('cinhour'));
            $this->phpsession->save('memo', set_value('memo'));
            redirect('res/confirm');
        }
    }
    
    /**
     * 確認
     */
    function confirm()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $planid = $this->phpsession->get('planid');
        $this->db->where('planid', $planid);
        $query = $this->db->get('plans', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['planid'] = $planid;
        $this->load->vars($data);
        
        $roomtypeid = $row['roomtypeid'];
        $this->db->where('roomtypeid', $roomtypeid);
        $query = $this->db->get('roomtypes', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['roomtype_name'] = $row['roomtype_name'];
        $data['roomtypes_guest_min'] = $row['guest_min'];
        $data['roomtypes_guest_max'] = $row['guest_max'];
        $this->load->vars($data);
        
        if ($this->input->post('submit'))
        {
            // 
            log_message('info', 'Res_model->doRes() >>');
            
            if ($this->Hotel_model->tentative_reservation == 1)
            {
                $resid = $this->Res_model->doRes(Res_model::RESMODE_TENTATIVE, $this->Hotel_model);
            }
            else
            {
                $resid = $this->Res_model->doRes(Res_model::RESMODE_REGULAR, $this->Hotel_model);
            }
            if ($resid < 0)
            {
                log_message('info', 'Res_model->doRes() NG <<');
                // 予約失敗
                redirect('res/failure/' . $resid);
            }
            log_message('info', 'Res_model->doRes() OK <<');
            
            redirect('res/accept/');
        }
        
        $this->load->view('res/confirm');
    }
    
    /**
     * 予約完了画面
     */
    function accept()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $this->load->view('res/accept');
    }
    
    /**
     * 予約失敗画面
     * # 予約処理中に他の予約が完了したときに発生する。
     */
    function failure($errorcode)
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        switch ($errorcode)
        {
        }
        
        $this->load->view('res/failure');
    }
    
    /**
     * ひらがな文字列のチェック
     */
    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;
        }
    }
}

/* End of file res.php */
