<?php

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

class User extends Public_Controller {

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

    public function index($register = null) {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        $this->page_title = "Login";
        $data['url_page'] = 'login';
        if ($register == 'register') {
            $data['url_page'] = 'register';
        }
        $data['register'] = $register;
        $this->render_page('user/login', $data);
    }

    public function validate() {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        $data = $this->prepareData();
        if ((isset($data['email']) && $data['email'] != null) && (isset($data['password']) && $data['password'] != null)) {
            $this->db->trans_start();
            $user = $this->User_Model->get_single('gkpos_customer', array('email' => $data['email'], 'password' => md5($data['password'])));
            if ($user && !empty($user)) {
                if ($user->status == 1) {
                    $this->session->set_userdata('online_userphone', $user->phone);
                    $this->session->set_userdata('online_useremail', $user->email);
                    if ($this->db->update('gkpos_customer', array('last_logged_in' => date('Y-m-d H:i:s'), 'is_logged_in' => 1), array('phone' => $user->phone, 'email' => $user->email))) {
                        echo json_encode(array('success' => true, 'message' => 'ok'));
                    }
                } else {
                    echo json_encode(array('success' => false, 'message' => 'Sorry! You are not a verified user or kept suspended'));
                }
            } else {
                echo json_encode(array('success' => false, 'message' => 'Sorry! Invalid email or password'));
            }
            $this->db->trans_complete();
        } else {
            echo json_encode(array('success' => false, 'message' => 'Sorry!  Invalid email or password'));
        }
    }

    public function register() {
        $success = false;
        $message = null;
        if ($this->form_validation->run('online_user') == FALSE) {
            echo"here1";
            exit();
            $message = validation_errors();
            $success = false;
        } else {
            $data = $this->prepareData();
            unset($data['confirm_password']);
            unset($data['licence_agreement']);
            $data['password'] = md5($data['password']);
            $data['status'] = 1;
            $data['is_verified'] = 0;
            $data['is_online'] = 1;
            $data['verified_code'] = $this->User_Model->get_code();
            $doesExist = $this->Site_Model->get_single('gkpos_customer', array('phone' => $data['phone']));
            $success_message = "Your registration done successfully at " . $this->config->item('gk_name');
            if ($doesExist != null && !empty($doesExist)) {
                if ($doesExist->email != null && $doesExist->password != '') {
                    $success = false;
                    $message = 'User already exists with that email and phone';
                } else {
                    $success = $this->db->update('gkpos_customer', $data, array('phone' => $doesExist->phone));
                    $message = $success_message;
                }
            } else {
                $success = $this->db->insert('gkpos_customer', $data);
                $message = $success_message;
            }
            if ($success) {
                $user = $this->db->where(array('email' => $data['email']))->get('gkpos_customer')->row();
                $this->session->set_userdata('online_userphone', $user->phone);
                $this->session->set_userdata('online_useremail', $user->email);
                $this->db->update('gkpos_customer', array('last_logged_in' => date('Y-m-d H:i:s'), 'is_logged_in' => 1), array('phone' => $user->phone, 'email' => $user->email));
                $data['template'] = 'common';
                $success = $this->mailto_customer($data);
            }
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function mailto_customer($data) {
        $data['recipent'] = $data['name'];
        $data['to'] = $data['email'];
        $data['from'] = $this->config->item('gk_email');
        $data['from_title'] = $this->config->item('gk_name');
        $data['subject'] = "Customer Registration At " . $this->config->item('gk_name');
        $data['txt'] = "Welcome to " . $this->config->item('gk_name') . " .You are now a registered member and can login there with your credentials";
        $data['verify_link'] = site_url('user/login/');
        $data['verify_link_txt'] = 'Login Now';
        $data['message'] = $this->load->view('email_template/' . $data['template'], $data, true);
        if ($this->send_email($data)) {
            return true;
        } else {
            return false;
        }
    }

    public function mailto_admin($data) {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        $data['recipent'] = 'Admin';
        $data['to'] = $this->config->item('gk_email');
        $data['from'] = "info@gksoft.co.uk";
        $data['from_title'] = $this->config->item('gk_name');
        $data['subject'] = "New Customer Registration At " . $this->config->item('gk_name');
        $data['txt'] = "A new customer has registered at your" . $this->config->item('gk_name') . " online order system. <br/><strong>Name:" . $data['name'] . "</strong><br/><strong>Email:" . $data['email'] . "</strong><br/><strong>Phone:" . $data['phone'];
        $data['message'] = $this->load->view('email_template/' . $data['template'], $data, true);
        if ($this->send_email($data)) {
            return true;
        } else {
            return false;
        }
    }

    public function forgetpassword() {
        if ($this->User_Model->is_logged_in()) {
            redirect('/');
        }
        $data = $this->prepareData();
        $check = $this->User_Model->get_single('gkpos_customer', array('email' => $data['rocovery_email']));
        $success = false;
        $message = null;
        if ($check != null && !empty($check)) {
            $success = true;
            $message = null;
            if ($this->db->update('gkpos_customer', array('extra1' => md5($check->email)), array('email' => $check->email))) {
                $success = $this->mailto_password_changer($check);
                if ($success) {
                    $message = "A verification email sent to this account. Please verify yourself";
                }
            }
        } else {
            $success = false;
            $message = "Sorry, The user with this email does not exist at " . $this->config->item('gk_name');
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function mailto_password_changer($user) {
        $data['recipent'] = $user->name;
        $data['to'] = $user->email;
        $data['from'] = $this->config->item('gk_email');
        $data['from_title'] = $this->config->item('gk_name');
        $data['subject'] = "Password Recovery From " . $this->config->item('gk_name');
        $data['txt'] = "To confirm, please click on the link below to set new password";
        $data['verify_link'] = site_url('user/changepassword/' . md5($user->email));
        $data['verify_link_txt'] = 'Verify';
        $data['message'] = $this->load->view('email_template/common', $data, true);
        if ($this->send_email($data)) {
            return true;
        } else {
            return false;
        }
    }

    public function changepassword($email = null) {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        $data = array();
        if ($email == null) {
            $this->session->set_flashdata('app_error', "You are not allowed to do this ");
            redirect('/');
        } else {
            if ($this->Site_Model->exists('gkpos_customer', 'extra1', $email)) {
                $user = $this->User_Model->get_single('gkpos_customer', array('extra1' => $email), array('email', 'phone'));
                $this->page_title = "User Verification";
                $data['url_page'] = 'login';
                $data['recovery_email'] = $user->email;
                $this->render_page('user/changepassword', $data);
            } else {
                $this->session->set_flashdata('app_error', "You are not allowed to do this");
                redirect('/');
            }
        }
    }

    public function save_password() {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        $success = false;
        $message = null;
        $data = $this->prepareData();
        if ($this->db->update('gkpos_customer', array('password' => md5($data['password'])), array('email' => $data['recovery_email']))) {
            $success = true;
            $message = "Your password changed successfully";
        }
        if ($success) {
            $this->session->set_flashdata('app_success', $message);
        } else {
            $success = false;
            $message = "Password Change Failed! Please try again!!!";
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function verification($return = null) {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        if ($return == null) {
            $this->session->set_flashdata('app_error', "You are not allowed");
            redirect('/');
        } else {
            $this->page_title = "User Verification";
            $data['return'] = $return;
            $data['url_page'] = 'login';
            $this->render_page('user/verification', $data);
        }
    }

    public function update_verification() {
        if ($this->User_Model->is_logged_in()) {
            $this->session->set_flashdata('app_success', "You are already logged in");
            redirect('/');
        }
        $verified_code = trim($this->input->post('verified_code'));
        $return = trim($this->input->post('return'));
        $success = false;
        $message = null;
        if ($verified_code != null && $return != null) {
            $check = $this->User_Model->get_single('gkpos_customer', array('verified_code' => $verified_code));
            if ($check != null && !empty($check)) {
                if ($return == md5($check->email)) {
                    if ($this->db->update('gkpos_customer', array('is_verified' => 1, 'status' => 1), array('verified_code' => $check->verified_code))) {
                        $success = true;
                        $message = "You account has been verified successfully";
                        $this->session->set_flashdata('app_success', $message);
                    } else {
                        $message = "Your verification failed! Please contact authority";
                        $this->session->set_flashdata('app_error', $message);
                        $success = false;
                    }
                } else {
                    $message = "Your verification failed! Please contact authority";
                    $this->session->set_flashdata('app_error', $message);
                    $success = false;
                }
            } else {
                $message = "Your verification failed!Please try again with exact code";
                $this->session->set_flashdata('app_error', $message);
                $success = false;
            }
        } else {
            $message = "Your verification failed!Please try again with exact code";
            $this->session->set_flashdata('app_error', $message);
            $success = false;
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function get_country() {
        $term = $this->input->get('term');
        $this->db->select('country');
        $this->db->from('gkpos_customer');
        $this->db->where("country LIKE '%" . $term . "%'");
        $this->db->group_by('country');
        $this->db->order_by("country", "asc");
        $result = $this->db->get()->result();
        $customer = array_map('current', $result);
        echo json_encode($customer);
    }

    public function get_city() {
        $term = $this->input->get('term');
        $this->db->select('city');
        $this->db->from('gkpos_customer');
        $this->db->where("city LIKE '%" . $term . "%'");
        $this->db->group_by('city');
        $this->db->order_by("city", "asc");
        $result = $this->db->get()->result();
        $customer = array_map('current', $result);
        echo json_encode($customer);
    }

}
