<?php

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

class Contact extends Public_Controller {

    function __construct() {
        parent::__construct();
        $this->site_title = $this->config->item('gk_name');
        $this->load->helper('site');
    }

    public function index() {
        $data['contact'] = $contact = $this->Site_Model->get_list('page', array('slug' => 'contact'));
        $this->page_title = $contact[0]->title;
        $this->current_section = $contact[0]->title;
        $data['url_page'] = 'page_contact';
        $this->body_class[] = 'page-contact';
        $this->page_meta_keywords = $contact[0]->meta_keys;
        $this->page_meta_description = $contact[0]->meta_desc;
        $this->render_page('contact/index', $data);
    }

    public function sentmail() {
        if ($this->input->post()) {
            $this->form_validation->set_rules('name', 'Name', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
            $this->form_validation->set_rules('message', 'Message', 'required');
            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
            $message = "Server host problem";
            $success = false;
            if ($this->form_validation->run() == FALSE) {
                $message = validation_errors();
            } else {
                $data['recipent'] = 'Admin';
                $data['to'] = $this->config->item('gk_email');
                $data['from'] = $this->input->post('email');
                $data['from_title'] = $this->input->post('name');
                $data['subject'] = "Contact Mail From " . $this->config->item('gk_name') . ' Website';
                $data['txt'] = "<strong>Message From " . $this->input->post('name') . "</strong>";
                $data['txt'] .= '<br>' . $this->input->post('message');
                if ($this->input->post('phone') != '') {
                    $data['txt'] .= "<br/>For farther contact Phone: <strong>" . $this->input->post('phone') . "</strong>";
                }
                $data['verify_link'] = null;
                $data['message'] = $this->load->view('email_template/common', $data, true);
                if ($_SERVER['SERVER_NAME'] != 'localhost') {
                    if ($this->send_email($data)) {
                        $success = true;
                        $message = 'Your Message sent Successfully';
                    } else {
                        $success = false;
                        $message = 'Your Message sending failed';
                    }
                }
            }
            echo json_encode(array('success' => $success, 'message' => $message));
        }
    }

    public function reservation() {
        $data['contact'] = $contact = $this->Site_Model->get_list('page', array('slug' => 'contact'));
        $this->page_title = $contact[0]->title;
        $this->current_section = $contact[0]->title;
        $data['url_page'] = "page_reservation";
        $this->body_class[] = 'contact';
        $this->page_meta_keywords = $contact[0]->meta_keys;
        $this->page_meta_description = $contact[0]->meta_desc;
        $sevenDays = $this->Site_Model->get_list('servicetime');
        $week = array();
        foreach ($sevenDays as $key => $day) {
            $week[$day->day] = $day;
        }
        $data['week'] = $week;
        $opened = $week[strtolower(date('D'))]->open;
        $openedObj = new DateTime($opened);
        $openingTime = $openedObj->format('h:i a');
        $closed = $week[strtolower(date('D'))]->closed;
        $closedObj = new DateTime($closed);
        $interval = $openedObj->diff($closedObj);
        $totalMins = 0;
        if ($interval->h >= 1) {
            $totalMins += $interval->h * 60;
        }
        if ($interval->i >= 1) {
            $totalMins += $interval->i;
        }
        $timeSlotIndex = ceil($totalMins / 15);
        $timeSlot = array();
        for ($i = 0; $i < $timeSlotIndex; $i++) {
            $nowDate = new DateTime($openingTime);
            $nowDate->add(new DateInterval('PT15M'));
            $nowTime = $nowDate->format('h:i a');
            $timeSlot[] = $nowTime;
            $openingTime = $nowTime;
        }
        $data['time_slot'] = $timeSlot;
        $data['isRestaaurantOpened'] = $this->isRestaaurantOpened;
        $this->render_page('contact/reservation', $data);
    }

    public function sent_booking() {
        if ($this->input->post()) {
            $this->form_validation->set_rules('res_email', 'Email', 'required|valid_email');
            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
            $message = 'Saved but due to host problem mail not delivered';
            $success = false;
            $is_sent = false;
            if ($this->form_validation->run() == FALSE) {
                $message = validation_errors();
            } else {
                $data = $this->prepareData();
                $res_date = DateTime::createFromFormat('d/m/Y', $this->input->post('res_date') != null ? $this->input->post('res_date') : date($this->config->item('dateformat'), strtotime('today')));
                $res_date_value = $res_date->format('Y-m-d');
                $data['res_date'] = $res_date_value;
                $data['created_at'] = date('Y-m-d');
                $success = $this->db->insert('gkpos_booking', $data);
                $id = $this->db->insert_id();
                if ($success && $id) {
                    $data['recipent'] = 'Admin';
                    $data['to'] = $this->config->item('gk_email');
                    $data['from'] = $this->input->post('res_email');
                    $data['from_title'] = $this->input->post('first_name') . ' ' . $this->input->post('last_name');
                    $data['subject'] = "Reservation Mail";
                    $data['txt'] = "<strong>Message From: " . $this->input->post('first_name') . ' ' . $this->input->post('last_name') . "</strong><br/>";
                    $data['txt'] .= "<strong>Phone: " . $this->input->post('res_phone') . "</strong><br/>";
                    $data['txt'] .= "<strong>Date: " . $this->input->post('res_date') . "</strong><br/>";
                    $data['txt'] .= "<strong>Time: " . $this->input->post('time_from'). "</strong><br/>";
                    $data['txt'] .= '<strong>Guest Quantity: ' . $this->input->post('guest_number') . '</strong>';
                    $data['txt'] .= '<br/>' . $this->input->post('res_message');
                    $data['verify_link'] = site_url('contact/reaction/' . $id . '/1/' . md5($this->config->item('gk_email')));
                    $data['verify_link_txt'] = 'confirm';
                    $data['reject_link'] = site_url('contact/reaction/' . $id . '/2/' . md5($this->config->item('gk_email')));
                    $data['reject_link_txt'] = 'Reject';
                    $data['message'] = $this->load->view('email_template/booking', $data, true);
                    if ($data != null || !empty($data)) {
                        $config = array();
                        $config['useragent'] = "CodeIgniter";
                        $config['mailpath'] = "/usr/bin/sendmail"; // or "/usr/sbin/sendmail"
                        $config['protocol'] = "smtp";
                        $config['smtp_host'] = "localhost";
                        $config['smtp_port'] = "25";
                        $config['mailtype'] = 'html';
                        $this->load->library('email');
                        $this->email->initialize($config);
                        $this->email->from($data['from'], $data['from_title']);
                        $this->email->to($data['to']);
                        $this->email->subject($data['subject']);
                        $this->email->message($data['message']);
                        $this->email->reply_to($data['from'], $data['from_title']);
                        if ($_SERVER['SERVER_NAME'] != 'localhost') {
                            if ($this->email->send()) {
                                $message = 'Your request for booking sent successfully';
                            } else {
                                $message = 'Your reservation request sending failed';
                            }
                        }
                    }
                }
            }
            echo json_encode(array('success' => $success, 'message' => $message));
        }
    }

    public function reaction($id = null, $action = null, $secret = null) {
        $success = false;
        if ($id > 0 && ($action > 0 && $action <= 2 && $secret == md5($this->config->item('gk_email')))) {
            $id = $id;
            $status = $action;
            $success = $this->db->update('gkpos_booking', array('status' => $status), array('id' => $id));
            if ($success && $status != 0) {
                $recepient = $this->Site_Model->get_single('gkpos_booking', array('id' => $id));
                $data['recipent'] = 'Customer';
                $data['to'] = $recepient->res_email;
                $data['from'] = $this->config->item('gk_email');
                $data['from_title'] = $this->config->item('gk_name');
                if ($status == 1) {
                    $data['subject'] = "Reservation Confirmation";
                    $data['txt'] = 'your reservation has been confirmed';
                }
                if ($status == 2) {
                    $data['subject'] = "Reservation Rejected";
                    $data['txt'] = 'Sorry! your reservation has been rejected';
                }
                $data['verify_link'] = null;
                $data['message'] = $this->load->view('email_template/common', $data, true);
                if ($this->send_email($data)) {
                    $success = true;
                } else {
                    $success = false;
                }
            }
        }

        $data['contact'] = $contact = $this->Site_Model->get_list('page', array('slug' => 'contact'));
        $this->page_title = $contact[0]->title;
        $this->current_section = $contact[0]->title;
        $data['url_page'] = $contact[0]->slug;
        $this->body_class[] = 'contact';
        $this->page_meta_keywords = $contact[0]->meta_keys;
        $this->page_meta_description = $contact[0]->meta_desc;
        $data['success'] = $success;
        $data['action'] = $action;
        $this->render_page('contact/message', $data);
    }

    public function testdistance() {
        $distance = get_delivery_distance('CF51AA', 'CF54DR');
        debugPrint($distance);
    }

}
