<?php
/**
 *  予約
 */
require_once (dirname(__FILE__) . "/FRONT_Controller.php");

class Res extends FRONT_Controller {
    
    function Res()
    {
        parent::FRONT_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($hotelid, $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);
        $this->db->where('status', 1);
        $query = $this->db->get('plans', 1);
        if ($query->num_rows() <= 0)
        {
            die('planid error!');
        }
        
        $row = $query->row_array();
        $data = $row;
        
        $data['hotelid'] = $hotelid;
        $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 = array();
        $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['basic_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->db->where('planid', $planid);
            $query = $this->db->get('planprice', 1);
            if ($query->num_rows() <= 0)
            {
                die('planprice error!');
            }
            $planprice = $query->row_array();
            
            // resroomsテーブルと同じ構成の配列を作成し、セッションに保存する。
            $tmp_y = substr($cin, 0, 4);
            $tmp_m = substr($cin, 5, 2);
            $tmp_d = substr($cin, 8, 2);
            $k = 0;
            $resrooms = array();
            
            $total_price = 0;
            for ($i = 0;; $i++)
            {
                $tmp_date = date('Y-m-d', mktime(0, 0, 0, $tmp_m, $tmp_d + $i, $tmp_y));
                if ($tmp_date >= $cout)
                {
                    break;
                }
                // 日程取得
                $dayType = 'A';
                $this->db->where('day', $tmp_date);
                $this->db->where('hotelid', $hotelid);
                $query = $this->db->get('daytype', 1);
                if ($query->num_rows() > 0)
                {
                    $row = $query->row_array();
                    $dayType = $row['value'];
                    if ($dayType == 'Z')
                    {
                        $data['error'] = array();
                        $data['error'][] = '休館日が含まれています。';
                        $this->load->vars($data);
                        $this->load->view('res/index');
                        return;
                    }
                }
                switch ($dayType)
                {
                    case 'A':
                        $basic_price = $planprice['a_basic_price'];
                        $child1_price = $planprice['a_child1_price'];
                        $child2_price = $planprice['a_child2_price'];
                        $child3_price = $planprice['a_child3_price'];
                        $child4_price = $planprice['a_child4_price'];
                        break;
                    case 'B':
                        $basic_price = $planprice['b_basic_price'];
                        $child1_price = $planprice['b_child1_price'];
                        $child2_price = $planprice['b_child2_price'];
                        $child3_price = $planprice['b_child3_price'];
                        $child4_price = $planprice['b_child4_price'];
                        break;
                    case 'C':
                        $basic_price = $planprice['c_basic_price'];
                        $child1_price = $planprice['c_child1_price'];
                        $child2_price = $planprice['c_child2_price'];
                        $child3_price = $planprice['c_child3_price'];
                        $child4_price = $planprice['c_child4_price'];
                        break;
                    case 'D':
                        $basic_price = $planprice['d_basic_price'];
                        $child1_price = $planprice['d_child1_price'];
                        $child2_price = $planprice['d_child2_price'];
                        $child3_price = $planprice['d_child3_price'];
                        $child4_price = $planprice['d_child4_price'];
                        break;
                }
                
                for ($j = 0; $j < $room_num; $j++)
                {
                    $subtotal =
                        $basic_num[$j] * $basic_price
                        + $child1_num[$j] * $child1_price
                        + $child2_num[$j] * $child2_price
                        + $child3_num[$j] * $child3_price
                        + $child4_num[$j] * $child4_price;
                    $total_price += $subtotal;
                    
                    $resrooms[$k++] = array(
                        'day' => $tmp_date,
                        'room_no' => $j + 1,
                        'daytype' => $dayType,
                        'basic_num' => $basic_num[$j],
                        'child1_num' => $child1_num[$j],
                        'child2_num' => $child2_num[$j],
                        'child3_num' => $child3_num[$j],
                        'child4_num' => $child4_num[$j],
                        'basic_price' => $basic_price,
                        'child1_price' => $child1_price,
                        'child2_price' => $child2_price,
                        'child3_price' => $child3_price,
                        'child4_price' => $child4_price,
                        'subtotal' => $subtotal);
                }
            }
            $this->phpsession->save('resrooms', $resrooms);
            
            // 入力値をセッションに保存する。
            $this->phpsession->save('reservation',
                array('cin' => $cin,
                      'cout' => $cout,
                      'hotelid' => $hotelid,
                      'planid' => $planid,
                      'roomtypeid' => $roomtypeid,
                      'room_num' => $room_num,
                      'total_price' => $total_price));
            
            $ret = $this->Res_model->doRes(Res_model::RESMODE_CHECK, null);
            if ($ret >= 0)
            {
                redirect('res/estimate/' . $hotelid);
            }
            else
            {
                $s = $this->Res_model->getErrorString($ret);
                $data['error'] = array();
                $data['error'][] = $s;
                $this->load->vars($data);
                $this->load->view('res/index');
            }
        }
    }
    
    /**
     * 見積もり,ユーザ情報入力方法の選択
     * - ログインする
     * - 未登録で予約する
     * - ユーザ登録する
     */
    function estimate($hotelid)
    {
        $this->load->library('phpsession');
        $this->load->helper(array('form', 'url'));
        
        $reservation = $this->phpsession->get('reservation');
        $planid = $reservation['planid'];
        $this->db->where('planid', $planid);
        $query = $this->db->get('plans', 1);
        if ($query->num_rows() < 0)
        {
            die('planid error!');
        }
        $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)
        {
            die('roomtypeid error!');
        }
        $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->isMember() == true)
        {
            $data['isloggedin'] = true;
        }
        else
        {
            $data['isloggedin'] = false;
        }
        $this->load->vars($data);
        
        // 見積画面を表示する
        $this->load->view('res/estimate');
    }
    
    /**
     * ログイン (予約手続き中でのログイン)
     */
    function login($hotelid)
    {
        $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', 1);
            $query = $this->db->get('members', 1);
            if ($query->num_rows() > 0)
            {
                $row = $query->row_array();
                $this->phpsession->save('member',
                    array('memberid' => $row['memberid'],
                          'name' => $row['name'],
                          'hotelid' => $row['hotelid'],
                          'email' => $row['email']));
                // 最終ログイン日時を更新する
                $data = array('last_login' => date("Y-m-d H:i:s"));
                $this->db->where('memberid', $row['memberid']);
                $this->db->update('members', $data);
                redirect('res/userinp');
            }
            else
            {
                $data['error'] = "メールアドレス、またはパスワードが間違っています。";
                $this->load->vars($data);
                $this->load->view('res/login');
                return;
            }
        }
    }
    
    /**
     * ユーザ情報の入力
     */
    function userinp($hotelid)
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $data['hotelid'] = $hotelid;
        $this->load->vars($data);
        
        $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'))
        {
            $member = $this->phpsession->get('member');
            if (!is_null($member))
            {
                $this->db->where('memberid', $member['memberid']);
                $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['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('resmember',
                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'),
                    'cinhour' => set_value('cinhour'),
                    'memo' => set_value('memo')));
            redirect('res/confirm/' . $hotelid);
        }
    }
    
    /**
     * 確認
     */
    function confirm($hotelid)
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $this->Hotel_model->load($hotelid);
        
        $reservation = $this->phpsession->get('reservation');
        $planid = $reservation['planid'];
        $this->db->where('planid', $planid);
        $query = $this->db->get('plans', 1);
        if ($query->num_rows() > 0)
        {
            $row = $query->row_array();
            $data = $row;
        }
        $data['hotelid'] = $hotelid;
        $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/' . $hotelid . '/' . $resid);
            }
            log_message('info', 'Res_model->doRes() OK <<');
            
            redirect('res/accept/' . $hotelid);
        }
        
        $this->load->view('res/confirm');
    }
    
    /**
     * 予約完了画面
     */
    function accept($hotelid)
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $data['hotelid'] = $hotelid;
        $this->load->vars($data);
        
        $this->load->view('res/accept');
    }
    
    /**
     * 予約失敗画面
     * # 予約処理中に他の予約が完了したときに発生する。
     */
    function failure($hotelid, $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 */
