<?php

class Roombooking extends MY_Controller {

    public $page_title = 'บันทึกจองห้องประชุม';

    function __construct() {
        parent::__construct();
        $this->load->model('db_m');
        $this->load->model('script_m');
        $this->load->library('mydate');
        $this->load->model('room_m');

        $s_imeeting['activemenu'] = '004';
        $this->session->set_userdata('s_imeeting', $s_imeeting);
    }

    function index($success = '0') {
        $this->create_sess_table();
        
        $rconfig = $this->db->get('tbconfig')->row_array();
        $data['sendemail'] = '0';
        if (isset($rconfig['id'])) {
            $data['sendemail'] = $rconfig['sendemail'];
        }

        $s_login = $this->session->userdata('s_login');
        $this->db->where('id', $s_login['login_id']);
        $member = $this->db->get('tbmember')->row_array();
        $data['member'] = $member;

        $data['extraHeadContent'] = $this->script_m->modal_window();
        $data['extraHeadContent'].= $this->script_m->bootstrap_tab();
        $data['extraHeadContent'].= $this->script_m->calendar();
        $data['extraHeadContent'].= $this->script_m->formatCurrency();
        $data['extraHeadContent'].= $this->script_m->textformat();

        $data['timerange'] = $this->db->get('tbtimerange')->result_array();
        $data['room'] = $this->db->get('tbroom')->result_array();

        $data['equip'] = $this->db->get('tbequip')->result_array();

        if ($success == '1') {
            $data['msg_text'] = 'บันทึกรายการจองสำเร็จ';
        }

        $data['page_title'] = $this->page_title;
        $data['content'] = 'room/roombooking_v';
        $this->load->view('template_v', $data);
    }

    function news() {
        redirect('roombooking');
    }

    //สร้างตารางชั่วคราวเพื่อเพิ่มจำนวนวันจอง
    function create_sess_table($arr = array()) {
        $this->session->set_userdata('tmp_booking', $arr);
        return true;
    }

    //แสดงรายการจองห้องประชุมวันเพิ่มเติม
    function ajax_get_grid_tmp() {
        $data['mydate'] = $this->mydate;
        $data['query'] = $this->session->userdata('tmp_booking');
        $this->load->view('room/roombooking_grid_tmp_v', $data);
    }

    function ajax_timerange() {
        $start_time = $this->input->post('start_time');
        $this->db->where('wtime > ', $start_time);
        $data = $this->db->get('tbtimerange')->result_array();
        echo json_encode($data);
    }

    function ajax_checkbusy() {
        $room_id = $this->input->post('room_id');
        $rdate = $this->input->post('rdate');
        $start_time = $this->input->post('start_time');
        $end_time = $this->input->post('end_time');

        $ret = $this->room_m->room_busy($room_id, $this->mydate->dateToMySql($rdate), $start_time, $end_time);
        $data = array(
            'msg' => $ret['msg'],
            'busy' => $ret['busy']
        );
        echo json_encode($data);
    }

    function ajax_save_tmp() {
        $tmp_booking = $this->session->userdata('tmp_booking');
        $tmp_booking[] = array(
            'room_id' => $this->input->post('room_id'),
            'room_name' => $this->input->post('room_name'),
            'rdate' => $this->mydate->dateToMySql($this->input->post('rdate')),
            'start_time' => $this->input->post('start_time'),
            'end_time' => $this->input->post('end_time')
        );

        $this->create_sess_table($tmp_booking);
    }

    //ลบรายการจองห้องประชุมวันเพิ่มเติม
    function ajax_delete_tmp() {
        $id = $this->input->post('id');
        $tmp_booking = $this->session->userdata('tmp_booking');
        unset($tmp_booking[$id]);

        $this->create_sess_table($tmp_booking);
        echo true;
    }

    //ตรวจสอบห้องว่างอีกครั้ง เผื่อมีการจองเข้ามาในช่วงวินาทีนั้น ก่อน SAVE
    function ajax_validate() {
        $room_id = $this->input->post('room_id');
        $rdate = $this->mydate->dateToMySql($this->input->post('rdate'));
        $start_time = $this->input->post('start_time');
        $end_time = $this->input->post('end_time');

        //ตรวจสอบห้องว่างอีกครั้ง เผื่อมีการจองเข้ามาในช่วงวินาทีนั้น
        $busy_txt = '';
        $ret = $this->room_m->room_busy($room_id, $rdate, $start_time, $end_time);
        if (!$ret['busy'])
            $busy_txt.=$ret['msg'] . " \n";

        //ตรวจสอบตาราง tmp
        $tmp_booking = $this->session->userdata('tmp_booking');
        foreach ($tmp_booking as $r) {
            $ret = $this->room_m->room_busy($r['room_id'], $r['rdate'], $r['start_time'], $r['end_time']);
            if (!$ret['busy'])
                $busy_txt.=$ret['msg'] . " \n";
        }

        $data['busy_txt'] = $busy_txt;
        echo json_encode($data);
    }

    function save() {
        $this->load->model('email_m');

        $this->db->trans_begin();

        $room_id = $this->input->post('room_id');
        $rdate = $this->mydate->dateToMySql($this->input->post('rdate'));
        $start_time = $this->input->post('start_time');
        $end_time = $this->input->post('end_time');

        $s_login = $this->session->userdata('s_login');
        $login_id = $s_login['login_id'];

        $data = array(
            'cdate' => date('Y-m-d H:i:s'),
            'meet_name' => $this->input->post('meet_name'),
            'chairman' => $this->input->post('chairman'),
            'room_id' => $room_id,
            'rdate' => $rdate,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'amount_people' => $this->input->post('amount_people'),
            'employee' => $this->input->post('employee'),
            'equip' => $this->input->post('equip_detail'),
            'meet_detail' => $this->input->post('meet_detail'),
            'contact_name' => $this->input->post('contact_name'),
            'contact_tel' => $this->input->post('contact_tel'),
            'member_id' => $login_id
        );

        $this->db->insert('tbreserv', $data);
        $id = $this->db->insert_id();

        //บันทึกข้อมูลเพิ่มวันจองลง tbbooking โดย loop จากตารางชั่วคราว
        $tmp_booking = $this->session->userdata('tmp_booking');
        foreach ($tmp_booking as $r) {
            $data = array(
                'wtype' => '0',
                'doc_id' => $id,
                'room_id' => $r['room_id'],
                'rdate' => $r['rdate'],
                'start_time' => $r['start_time'],
                'end_time' => $r['end_time']
            );
            $this->db->insert('tbbooking', $data);
        }
        
        //บันทึกราการอุปกรณื
        if (isset($_POST['equip'])) {
            foreach ($this->input->post('equip') as $val) {
                $data = array(
                    'doc_id' => $id,
                    'equip_id' => $val
                );
                $this->db->insert('tbbooking_equip', $data);
            }
        }

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();

            //upload file การประชุม
            $file_element_name = 'fileToUpload';
            $config['upload_path'] = './assets/upload/';
            $config['encrypt_name'] = TRUE;
            $config['allowed_types'] = '*';
            $config['max_size'] = 1024 * 5;

            $this->load->library('upload', $config);
            if ($this->upload->do_upload($file_element_name)) {
                //$this->upload->do_upload($file_element_name);
                $data_file = $this->upload->data();
                $row = array(
                    'file_name' => $data_file['orig_name'],
                    'file_tmpname' => $data_file['file_name'],
                    'file_fullpath' => $data_file['full_path']
                );

                $this->db->where('id', $id);
                $this->db->update('tbreserv', $row);
            }

            if ($this->email_m->check_sendmail()) {
                //********************* ส่งเมลล์ ********************************
                //ส่งเมลล์รายการจอง 1 ฉบับ ต่อ 1 ผู้อนุมัติ
                $subject = 'รายการจองห้องประชุมรออนุมัติ';
                $message = '<b>วาระการประชุม</b> ' . $this->input->post('meet_name') . "<br/>";
                $message.= '<b>วันที่จอง</b> ' . $this->mydate->dateTotext($rdate) . " <b>เวลา</b> " . $start_time . " <b>ถึง</b> " . $end_time;
                $message.= " <b>ห้องประชุม</b> " . $this->room_m->get_roomname($room_id) . "<br/>";

                $this->db->where('doc_id', $id);
                $this->db->where('wtype', '0');
                $booking = $this->db->get('tbbooking')->result_array();
                foreach ($booking as $b) {
                    $message.= "วันที่ </b>" . $this->mydate->dateToText($b['rdate']) . " <b>เวลา</b> " . $b['start_time'] . " <b>ถึง</b> " . $b['end_time'];
                    $message.= " <b>ห้องประชุม</b> " . $this->room_m->get_roomname($b['room_id']) . "<br/>";
                }
                $this->db->where('id', $login_id);
                $member = $this->db->get('tbmember')->row_array();

                $message.= "<b>ผู้จอง</b> " . $member['name'] . " <b>ติดต่อ</b> " . $member['mobile'] . ", " . $member['tel'];


                $this->db->where('depart_id', $member['depart_id']);
                $query = $this->db->get('tbmembertodepart')->result_array();
                foreach ($query as $r) {
                    $this->db->where('id', $r['member_id']);
                    $member_approve = $this->db->get('tbmember')->row_array();
                    if (isset($member_approve['id'])) {
                        if ($member_approve['email'] != '') {
                            $this->email_m->sendmail($member['email'], 'ระบบ iMeeting', $member_approve['email'], $subject, $message, $member['id']);
                        }
                    }
                }

                //ส่งอีเมลล์แจ้งรายการเตรียมอุปกรณ์โดยแยกเป็น 1 ห้อง 1 วันต่ออีเมลล์ 1 ฉบับ
                //รายการนี้เฉพาะ 1 ห้องประชุมหลัก
                $this->db->where('id', $room_id);
                $room = $this->db->get('tbroom')->row_array();

                if ($room['ma_email'] != '') {
                    $sql = "SELECT tbequip.name FROM tbbooking_equip Inner Join tbequip ON tbbooking_equip.equip_id = tbequip.id";
                    $sql.= " WHERE tbbooking_equip.doc_id =  '$id'";
                    $booking_equip = $this->db->query($sql)->result_array();

                    if ($this->input->post('equip_detail') != '' || count($booking_equip) > 0) {
                        $subject = "แจ้งเตรียมอุปกรณ์ห้องประชุม วันที่ " . $this->mydate->dateToText($rdate);
                        $message = '<b>วาระการประชุม</b> ' . $this->input->post('meet_name') . "<br/>";
                        $message.= "<b>วันที่ </b>" . $this->mydate->dateToText($rdate) . " <b>เวลา</b> " . $start_time . " <b>ถึง</b> " . $end_time . " <b>ห้องประชุม</b> " . $this->room_m->get_roomname($room_id) . "<br/>";
                        $message.= "<b>รายการที่ต้องเตรียมดังนี้</b><br/>";

                        //nl2br 
                        foreach ($booking_equip as $r) {
                            $message.=$r['name'] . ", ";
                        }
                        $message.= nl2br($this->input->post('equip_detail')) . "<br/>";
                        $message.= "<b>ผู้จอง</b> " . $member['name'] . " <b>ติดต่อ</b> " . $member['mobile'] . ", " . $member['tel'];
                        $this->email_m->sendmail($member['email'], 'ระบบ iMeeting', $room['ma_email'], $subject, $message, $member['id']);
                    }
                }

                //loop ห้องใน tbbooking
                $this->db->where('doc_id', $id);
                $this->db->where('wtype', '0');
                $booking = $this->db->get('tbbooking')->result_array();
                foreach ($booking as $b) {
                    $this->db->where('id', $b['room_id']);
                    $room = $this->db->get('tbroom')->row_array();
                    if ($room['ma_email'] != '') {
                        $sql = "SELECT tbequip.name FROM tbbooking_equip Inner Join tbequip ON tbbooking_equip.equip_id = tbequip.id";
                        $sql.= " WHERE tbbooking_equip.doc_id =  '$id'";
                        $booking_equip = $this->db->query($sql)->result_array();

                        if ($this->input->post('equip_detail') != '' || count($booking_equip) > 0) {
                            $subject = "แจ้งเตรียมอุปกรณ์ห้องประชุม วันที่ " . $this->mydate->dateToText($b['rdate']);
                            $message = '<b>วาระการประชุม</b> ' . $this->input->post('meet_name') . "<br/>";
                            $message.= "<b>วันที่ </b>" . $this->mydate->dateToText($b['rdate']) . " <b>เวลา</b> " . $b['start_time'] . " <b>ถึง</b> " . $b['end_time'] . " <b>ห้องประชุม</b> " . $this->room_m->get_roomname($b['room_id']) . "<br/>";
                            $message.= "<b>รายการที่ต้องเตรียมดังนี้</b><br/>";

                            //nl2br 
                            foreach ($booking_equip as $r) {
                                $message.=$r['name'] . ", ";
                            }
                            $message.= nl2br($this->input->post('equip_detail')) . "<br/>";
                            $message.= "<b>ผู้จอง</b> " . $member['name'] . " <b>ติดต่อ</b> " . $member['mobile'] . ", " . $member['tel'];

                            $this->email_m->sendmail($member['email'], 'ระบบ iMeeting', $room['ma_email'], $subject, $message, $member['id']);
                        }
                    }
                }
            }
        }
        redirect('roombooking/index/1');
    }
}

?>
