<?php

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

class Takeaway extends Online_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('Takeaway_Model');
        $this->load->model('Cart_Model');
        if (!$this->session->userdata('brnach')) {
            $this->session->set_userdata('branch', '1');
        }
        $this->cartTotal = $this->Cart_Model->total();
        $this->processOrder = isRestaurantOpenNow() || $this->Cart_Model->getPreOrder();
    }

    private function getPageInfo($slug) {
        $obj = $this->Takeaway_Model->get_single('page', array('slug' => $slug))->row();
        $page = array();
        if ($obj && !empty($obj)) {
            $this->page_title = $obj->title;
            $this->current_section = $obj->title;
            $this->page_meta_keywords = $obj->meta_keys;
            $this->page_meta_description = $obj->meta_desc;
            $page['content'] = $obj->content;
            $page['image'] = $obj->image;
        }
        return $page;
    }

    public function index() {
        $page = $this->getPageInfo('home');
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->render('home/index', $data);
    }

    public function about() {
        $page = $this->getPageInfo('about');
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->render('about', $data);
    }

    public function gallery() {
        $page = $this->getPageInfo('gallery');
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['images'] = $this->Takeaway_Model->get_list('gallery', array('branch' => $this->session->userdata('branch') ? $this->session->userdata('branch') : '1'))->result();
        $data['url'] = base_url(uri_string());
        $this->render('gallery', $data);
    }

    public function onlineorder($branch = '1') {
        $this->session->set_userdata('branch', $branch);
        $page = $this->getPageInfo('menu');
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $data['categories'] = $this->_getMenuCategories($branch);
        if ($data['categories'] && !empty($data['categories'])) {
            foreach ($data['categories'] as $acategory) {
                $data['menus'][$acategory->id] = $this->_getMenusByCategory($branch, $acategory->id);
                if (!empty($data['menus'][$acategory->id])) {
                    foreach ($data['menus'][$acategory->id] as $amenu) {
                        $data['selections'][$acategory->id][$amenu->id] = $this->_getMenuSelections($branch, $amenu->id);
                    }
                }
            }
        }
        $data['hideTopFooter'] = 'yes';
        $this->render('onlineorder/index', $data);
    }

    private function _getMenuCategories($branch) {
        return $this->Takeaway_Model->get_list('menucategory', array('branch' => $branch, 'online' => '3', 'status' => '3'), null, null, null, 'position', 'ASC')->result();
    }

    private function _getMenusByCategory($branch, $category) {
        return $this->Takeaway_Model->get_list('menu', array('branch' => $branch, 'online' => '3', 'status' => '3', 'category' => $category))->result();
    }

    private function _getMenuSelections($branch, $menu) {
        return $this->Takeaway_Model->get_list('menuselection', array('branch' => $branch, 'online' => '3', 'status' => '3', 'menu' => $menu))->result();
    }

    public function review() {
        $page = $this->getPageInfo('review');
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $data['url'] = base_url(uri_string());
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $data['reviews'] = $this->Takeaway_Model->get_list('review', array('status' => 3), null, 50, 0, 'date', 'DESC')->result();
        $this->render('review', $data);
    }

    public function review_submit() {
        if ($this->input->post() && $this->session->userdata('customerId')) {
            $data = $this->preparePostedData();
            $data['status'] = 3;
            $data['cid'] = $this->session->userdata('customerId');
            $data['name'] = $this->Takeaway_Model->get_single('customer', array('id' => $this->session->userdata('customerId')))->row()->name;
            $status = $this->db->insert('review', $data);
            $message = null;
            if ($status) {
                $this->session->set_flashdata('success', 'Thank you, your review rating submitted successfully');
                $message = 'Thank you, your review rating submitted successfully';
            } else {
                $message = 'Sorry, your review rating sumission failed, please try again';
            }
            echo json_encode(array('status' => $status, 'message' => $message));
        }
    }

    public function contact() {
        $page = $this->getPageInfo('contact');
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $this->render('contact', $data);
    }

    public function contact_sent() {
        $data = array();
        if ($this->input->post()) {
            $googleResponse = $this->__getGRecaptchaRespons();
            if ($this->form_validation->run('contact') == FALSE || !$googleResponse->success) {
                $errorArray = $this->form_validation->error_array();
                $errorArray['grecaptcharesponse'] = "Please verify that you are not a robot";
                $data = $this->preparePostedData();
                $data['success'] = false;
                $data['errors'] = $errorArray;
            } else {
                $data['restaurantAddress'] = $this->restaurantInfo['address_street'] . ', ' . $this->restaurantInfo['address_city'] . ', ' . $this->restaurantInfo['address_postcode'];
                $data['success'] = true;
                $data['recipent'] = 'Admin';
                $data['to'] = $this->restaurantInfo['general_email'];
                $data['from'] = $this->input->post('email');
                $data['from_title'] = $this->input->post('name');
                $data['subject'] = "Contact Mail From " . $this->config->item('general_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);
                $this->send_email($data);
                $this->session->set_flashdata('success', 'Thank you, your queries submitted successfully. We will contact soon');
            }
        }
        echo json_encode($data);
    }

    public function reservation() {
        $page = $this->getPageInfo('reservation');
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $data['times']= $this->getManagedTime();
        $this->render('reservation', $data);
    }

    public function reservation_save() {
        $data = array();
        if ($this->input->post()) {
            $googleResponse = $this->__getGRecaptchaRespons();
            if ($this->form_validation->run('reservation') == FALSE || !$googleResponse->success) {
                $errorArray = $this->form_validation->error_array();
                $errorArray['grecaptcharesponse'] = "Please verify that you are not a robot";
                $data = $this->preparePostedData();
                $data['success'] = false;
                $data['errors'] = $errorArray;
            } else {
                $data = $this->preparePostedData();
                $res_date = DateTime::createFromFormat('d/m/Y', $data['date']);
                $data['date'] = $res_date->format('Y-m-d');
                $data['status'] = 1;
                $data['branch'] = $this->restaurantInfo['id'];
                unset($data['g-recaptcha-response']);
                $id = $this->Takeaway_Model->saveBooking($data);
                if ($id) {
                    $emailData['recipent'] = 'Admin';
                    $emailData['restaurantAddress'] = $this->restaurantInfo['address_street'] . ', ' . $this->restaurantInfo['address_city'] . ', ' . $this->restaurantInfo['address_postcode'];
                    $emailData['to'] = $this->restaurantInfo['general_email'];
                    $emailData['from'] = $this->input->post('email');
                    $emailData['from_title'] = $this->input->post('first_name') . ' ' . $this->input->post('last_name');
                    $emailData['subject'] = "Reservation Mail";
                    $emailData['txt'] = "<strong>Message From: " . $this->input->post('first_name') . ' ' . $this->input->post('last_name') . "</strong><br/>";
                    $emailData['txt'] .= "<strong>Phone: " . $this->input->post('phone') . "</strong><br/>";
                    $emailData['txt'] .= "<strong>Date: " . $this->input->post('date') . "</strong><br/>";
                    $emailData['txt'] .= "<strong>Time: " . $this->input->post('time') . "</strong><br/>";
                    $emailData['txt'] .= '<strong>Guest Quantity: ' . $this->input->post('guest_qty') . '</strong>';
                    $emailData['txt'] .= '<br/>' . $this->input->post('note');
                    $emailData['verify_link'] = site_url('reservation-confirmation/' . $id . '/2/' . md5($this->restaurantInfo['general_email']));
                    $emailData['verify_link_txt'] = 'confirm';
                    $emailData['reject_link'] = site_url('reservation-confirmation/' . $id . '/3/' . md5($this->restaurantInfo['general_email']));
                    $emailData['reject_link_txt'] = 'Reject';
                    $emailData['message'] = $this->load->view('email_template/booking', $emailData, true);
                    $data['success'] = $this->send_email($emailData);
                    $this->session->set_flashdata('success', 'Thank you, your reservation request submitted successfully. You will get an confirmation email soon');
                }
            }
        }
        echo json_encode($data);
    }

    public function reservation_confirmation($id = null, $action = null, $secret = null) {
        $id = $this->uri->segment(2);
        $action = $this->uri->segment(3);
        $secret = $this->uri->segment(4);
        $success = false;
        if ($id > 0 && $action >= 2 && $secret == md5($this->restaurantInfo['general_email'])) {
            $id = $id;
            $status = $action;
            $success = $this->db->update('booking', array('status' => $status), array('id' => $id));
            if ($success && $status != 0) {
                $recepient = $this->Takeaway_Model->get_single('booking', array('id' => $id))->row();
                $branch = $this->Takeaway_Model->get_single('branch', array('id' => $recepient->branch))->row();
                $data['restaurantAddress'] = $branch->address_street . ', ' . $branch->address_city . ', ' . $branch->address_postcode;
                $data['recipent'] = 'Customer';
                $data['to'] = $recepient->email;
                $data['from'] = $branch->general_email;
                $data['from_title'] = $this->config->item('general_name');
                if ($status == 2) {
                    $data['subject'] = "Reservation Confirmation";
                    $data['txt'] = 'your reservation has been confirmed';
                }
                if ($status == 3) {
                    $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);
                $this->send_email($data);
            }
        }
        $data['success'] = $success;
        $data['action'] = $action;
        $data['url'] = base_url(uri_string());
        $this->page_title = "Reservation Confirmation";
        $this->render('reservation_confirmation', $data);
    }

    public function customer_login() {
        if ($this->isTheCustomerLoggedIn) {
            redirect($this->session->userdata('lastAccessUrl'));
        } else {
            $page = $this->getPageInfo('login');
            $data['content'] = !empty($page) ? $page['content'] : '';
            $data['image'] = !empty($page) ? $page['image'] : '';
            $data['url'] = base_url(uri_string());
            $this->render('customer_login', $data);
        }
    }

    public function customer_login_validation() {
        $data = array();
        if ($this->input->post()) {
            if ($this->form_validation->run('login') == FALSE) {
                $data['errors'] = $this->form_validation->error_array();
                $data['success'] = false;
            } else {
                $data = $this->preparePostedData();
                $customer = $this->Takeaway_Model->get_single('customer', array('email' => $data['email'], 'password' => md5($data['password'])))->row();
                if (!empty($customer)) {
                    $this->session->set_userdata('customerId', $customer->id);
                }
                if ($this->session->userdata('customerId')) {
                    $data['success'] = true;
                } else {
                    $data['success'] = false;
                }
            }
        }
        if (!$data['success']) {
            $data['message'] = "Invalid email address/password";
        }
        echo json_encode($data);
    }

    public function customer_signup() {
        $page = $this->getPageInfo('signup');
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $data['url'] = base_url(uri_string());
        $this->render('customer_signup', $data);
    }

    public function customer_signup_validation() {
        $data = array();
        if ($this->input->post()) {
            $customerId = null;
            $googleResponse = $this->__getGRecaptchaRespons();
            if ($this->form_validation->run('signup') == FALSE || !$googleResponse->success) {
                $errorArray = $this->form_validation->error_array();
                $errorArray['grecaptcharesponse'] = "Please verify that you are not a robot";
                $data = $this->preparePostedData();
                $data['success'] = false;
                $data['errors'] = $errorArray;
            } else {
                $data = $this->preparePostedData();
                $customer = $this->doesPhoneExist($data['phone']);
                unset($data['confirm_password']);
                unset($data['g-recaptcha-response']);
                unset($data['termscon']);
                $data['password'] = md5($data['password']);
                $data['status'] = '2';
                $data['verified'] = '2';
                $data['branch'] = $this->session->userdata('branch') ? $this->session->userdata('branch') : '1';
                if (!empty($customer)) {
                    $customerId = $this->Takeaway_Model->saveCustomer($data, $customer->id);
                } else {
                    $customerId = $this->Takeaway_Model->saveCustomer($data);
                }
                unset($data);
                if ($customerId) {
                    $data['success'] = true;
                    $data['success_msg'] = 'Thank you, you have been registered successfully';
                    $this->session->set_userdata('customerId', $customerId);
                } else {
                    $data['success'] = false;
                    $data['success_msg'] = 'There some internal problem please try again';
                }
            }
        }
        echo json_encode($data);
    }

    private function doesPhoneExist($phone) {
        return $this->Takeaway_Model->get_single('customer', array('phone' => $phone))->row();
    }

    public function termsandcondition() {
        $page = $this->getPageInfo('privacy_policy');
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $data['url'] = base_url(uri_string());
        $data['content'] = !empty($page) ? $page['content'] : '';
        $data['image'] = !empty($page) ? $page['image'] : '';
        $this->render('termsandcondition', $data);
    }

    public function deliveryInformation() {
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        $deliveryInformation = getDeliveryInformation();
        $data['url'] = base_url(uri_string());
        $data['areas'] = $deliveryInformation['deliveryArea'];
        $data['deliverySettings'] = (array) $deliveryInformation['apiSetting'];
        $this->current_section = "Delivery Information";
        $this->page_title = "Delivery Information";
        $this->page_meta_keywords = "Delivery,Information";
        $this->page_meta_description = "Delivery information";
        $this->render('delivery_information', $data);
    }

    private function __getGRecaptchaRespons() {
        if ($this->input->post()) {
            $secretKey = $this->restaurantInfo['captchaSecretKey'];
            $responseKey = $this->input->post('g-recaptcha-response');
            $remoteip = $_SERVER['REMOTE_ADDR'];
            $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$remoteip";
            $response = file_get_contents($url);
            return json_decode($response);
        } else {
            return array();
        }
    }

    public function checkout() {
        $this->page_title = "Checkout";
        $this->session->set_userdata('lastAccessUrl', base_url(uri_string()));
        if ($this->isTheCustomerLoggedIn) {
            redirect('my-account/checkout');
        } else {
            redirect('customer-login');
        }
    }

    public function subscribe() {
        $data['email'] = $this->input->post('email');
        $hasRow = $this->Takeaway_Model->get_single('subscription', array('email' => $data['email']))->row();
        $status = false;
        if (!empty($hasRow)) {
            $status = true;
        } else {
            $status = $this->db->insert('subscription', $data);
        }
        $message = $status ? "Thank you for your subscription, you will get our offer note very soon" : "Sorry, your subscription has failed";
        echo json_encode(array('status' => $status, 'message' => $message));
    }

    public function account_recovery() {
        $data = array();
        $this->page_title = "Account Recovery";
        $this->current_section = "Account Recovery";
        $data['url'] = base_url(uri_string());
        $this->render('account_recovery', $data);
    }

    public function validate_account_recovery() {
        $hasUser = $this->Takeaway_Model->get_single('customer', array('email' => $this->input->post('email')))->row();
        if (!empty($hasUser)) {
            $message = "ok";
            $verificationCode = $this->getVerfificationCode();
            $this->session->set_userdata('verificationCode', $verificationCode);
            $this->session->set_userdata('customerEmail', $hasUser->email);
            $success = $this->mailto_password_changer($hasUser, $verificationCode);
            if ($success) {
                $this->session->set_flashdata('verificationEmailMsg', 'A verification code sent to your email');
            }
        } else {
            $success = false;
            $message = "Sorry, The user with this email does not exist at " . $this->config->item('general_name');
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    private function mailto_password_changer($user, $verificationCode) {
        $data['recipent'] = $user->name;
        $data['to'] = $user->email;
        $data['from'] = $this->restaurantInfo['general_email'];
        $data['from_title'] = $this->config->item('general_name');
        $data['subject'] = "Password Recovery From " . $this->config->item('general_name');
        $data['txt'] = "Your verification code is " . $verificationCode;
        $data['verify_link'] = null;
        $data['verify_link_txt'] = 'Verify';
        $data['restaurantAddress'] = $this->restaurantInfo['address_street'] . ', ' . $this->restaurantInfo['address_city'] . ', ' . $this->restaurantInfo['address_postcode'];
        $data['message'] = $this->load->view('email_template/common', $data, true);
        return $this->send_email($data);
    }

    public function change_account_password($code = null) {
        if ($code && $code === $this->session->userdata('verificationCode')) {
            $this->session->unset_userdata('verificationCode');
            $this->session->set_userdata('passwordFormAccessCode', $code);
            $data['url'] = base_url(uri_string());
            $this->page_title = "Change Password";
            $this->current_section = "Change Password";
            $this->render('change_account_password', $data);
        } else {
            $this->session->unset_userdata('verificationCode');
            redirect(site_url('account-recovery'));
        }
    }

    public function change_password() {
        $s1 = false;
        if ($this->session->userdata('passwordFormAccessCode') && $this->session->userdata('customerEmail') && $this->input->post()) {
            $s1 = $this->db->update('customer', array('password' => md5($this->input->post('password'))), array('email' => $this->session->userdata('customerEmail')));
            if ($s1) {
                $this->session->unset_userdata('customerEmail');
                $this->session->unset_userdata('passwordFormAccessCode');
            }
        }
        echo json_encode(array('status' => $s1));
    }

    private function getVerfificationCode() {
        return substr(str_shuffle(str_repeat('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 6)), 1, 6);
    }

    public function verify_account_recovery_code() {
        if ($this->input->post('code') === $this->session->userdata('verificationCode')) {
            echo json_encode(array('status' => true, 'code' => $this->input->post('code')));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    public function preorder() {
        $this->Cart_Model->setPreOrder('yes');
        //$this->Cart_Model->setOrderType('collection');
        if ($this->Cart_Model->getPreOrder()) {
            redirect(site_url('online-order'));
        }
    }
     private function getManagedTime() {
        $timeSlot = array();
        $serviceTime = serviceTime();
        $todayServiceTime = array();
        if (!empty($serviceTime)) {
            foreach ($serviceTime as $st) {
                $manageSt = array(
                    'start' => $st[date('D')]->start,
                    'end' => $st[date('D')]->end,
                );
                array_push($todayServiceTime, $manageSt);
            }
        }
        if (!empty($todayServiceTime)) {
            $choosenStart = $todayServiceTime[0]['start'];
            $choosenEnd = $todayServiceTime[0]['end'];
            $choosenEndTimestamp = strtotime(date('h:i a', strtotime($choosenEnd)));
            if (count($todayServiceTime) > 1) {
                foreach ($todayServiceTime as $time) {
                    $thisStartTimestamp = strtotime(date('h:i a', strtotime($time['start'])));
                    $thisEndTimestamp = strtotime(date('h:i a', strtotime($time['end'])));
                    if ($thisEndTimestamp > $choosenEndTimestamp) {
                        $choosenEnd = $time['end'];
                    }
                }
            }
            $openedObj = new DateTime($choosenStart);
            $openingTime = $openedObj->format('h:i a');
            $closed = $choosenEnd;
            $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) / 30);
            for ($i = 0; $i < $timeSlotIndex; $i++) {
                $nowSlotDate = new DateTime($openingTime);
                $nowSlotDate->add(new DateInterval('PT30M'));
                $nowSlotTime = $nowSlotDate->format('h:i a');
                $timeSlot[] = $nowSlotTime;
                $openingTime = $nowSlotTime;
            }
        }
        return $timeSlot;
    }

}
