<?php

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

class Epos extends Epos_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('Epos_Model');
        if ($this->Epos_Model->isThisUserAnEposLogger() && (($this->cookies && !empty($this->cookies)) || ($this->session->userdata('group') == 2))) {
            return true;
        } else {
            redirect('user/login/index/' . $this->session->userdata('branch') . '/' . $this->session->userdata('team'));
        }
    }

    public function index() {
        $data['services'] = $this->Epos_Model->get_single('service', array('branch' => $this->session->userdata('branch')))->row_array();
        $data['refresh'] = base_url(uri_string());
        $data['updates'] = $this->Epos_Model->get_list('updates', array('user' => (int) $this->session->userdata('owner'), 'status' => 2, 'branch' => $this->session->userdata('branch')))->result();
        $data['branch'] = $this->Epos_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row_array();
        $data['terminals'] = unserialize($data['branch']['terminal']);
        $this->render('epos/index', $data);
    }

    public function pendingIssues() {
        $data = array(
            'pendingCallerId' => array(),
            'pendingBooking' => array(),
            'pendingOnlineOrder' => array(),
            'pendingAppOrder' => 0,
        );
        $services = $this->Epos_Model->get_single('service', array('branch' => $this->session->userdata('branch')))->row_array();
        $branch = $this->Epos_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row_array();
        $terminals = unserialize($branch['terminal']);
        if (in_array('callerId', $this->session->userdata('userApps')) && $services['callerId'] === '3' && (!empty($terminals) && in_array('callerDevice', $terminals))) {
            $data['pendingCallerId'] = $this->__getPendingCallerId($branch['callerDeviceStyle']);
        }
        if ($services['online'] === '3' && in_array('booking', $this->session->userdata('userApps')) && $services['booking'] === '3') {
            $data['pendingBooking'] = $this->__getPendingBooking();
        }
        if (in_array('online', $this->session->userdata('userApps')) && $services['online'] === '3') {
            $data['pendingOnlineOrder'] = $this->__getPendingOnlineOrder();
        }
        if (in_array('appReceiver', $this->session->userdata('userApps')) && $services['appReceiver'] === '3' && (!empty($terminals) && in_array('appReceiver', $terminals))) {
            $data['pendingAppOrder'] = $this->__getPendingAppOrder();
        }
        echo json_encode($data);
    }

    private function __getPendingCallerId($how) {
        $this->_getUpdateCallerIds($how);
        if ($how == "yes") {
            $this->db->where('user', $this->session->userdata('owner'));
            $this->db->where('received', 'no');
        } else {
            $this->db->where('received', 'no');
        }
        $this->db->where('branch', $this->session->userdata('branch'));
        $this->db->where('team', $this->session->userdata('team'));
        $this->db->order_by('date', 'ASC');
        $this->db->limit(1);
        return $this->db->get('callerphone')->row();
    }

    private function _getUpdateCallerIds($how) {
        if ($how == "yes") {
            $this->db->where('user', $this->session->userdata('owner'));
            $this->db->where('received', 'no');
        } else {
            $this->db->where('received', 'no');
        }
        $this->db->where('branch', $this->session->userdata('branch'));
        $this->db->where('team', $this->session->userdata('team'));
        $this->db->order_by('date', 'ASC');
        $availableCallerIds = $this->db->get('callerphone')->result();
        $cuurrentTime = date('Y-m-d H:i:s');
        $cuurrentTimeObject = new DateTime($cuurrentTime);
        if (!empty($availableCallerIds)) {
            foreach ($availableCallerIds as $availableCallerId) {
                $availableCallerIdTimeObj = new DateTime($availableCallerId->date);
                $interval = $availableCallerIdTimeObj->diff($cuurrentTimeObject);
                if ($interval->format('%s') >= 15) {
                    $this->db->update('callerphone', array('received' => 'yes'), array('id' => $availableCallerId->id));
                }
            }
        }
    }

    function updateCallerPhone() {
        $phone = $this->input->post('phone');
        $status = $this->db->update('callerphone', array('received' => 'yes'), array('phone' => $phone));
        echo json_encode(array('status' => $status));
    }

    private function __getPendingBooking() {
        $onlineOrder = $this->Epos_Model->get_list('booking', array('status' => '1', 'date >=' => date('Y-m-d'), 'branch' => $this->session->userdata('branch')))->result();
        return count($onlineOrder);
    }

    private function __getPendingOnlineOrder() {
        $onlineOrder = $this->Epos_Model->get_list('order', array('source' => 'online', 'status_online' => '2', 'branch' => $this->session->userdata('branch'), 'team' => $this->session->userdata('team')))->result();
        return count($onlineOrder);
    }

    private function __getPendingAppOrder() {
        $pusshedOrders = $this->Epos_Model->get_list('order', array('isPushed' => 'yes', 'branch' => $this->session->userdata('branch'), 'team' => $this->session->userdata('team')))->result();
        return count($pusshedOrders);
    }

    function getAppOrderDetail($sid) {
        $data['theOrder'] = $this->Epos_Model->get_single('order', array('sid' => (int) $sid))->row_array();
        $this->load->view('epos/options/remoteOrderDetail', $data, false);
    }

    public function paymentOnline($lid, $sid, $status, $amount, $hasBillPrint = 2, $remote = 'no') {
        $stripe = $this->Epos_Model->get_single('paymentstripe', array('branch' => $this->session->userdata('branch'), 'status' => '3'))->row();
        $data['orderId'] = $lid;
        $data['sid'] = $sid;
        $data['status'] = (int) $status;
        $data['amount'] = (double) $amount;
        if (!empty($stripe)) {
            $data['pk'] = $stripe->mode == 3 ? $stripe->pk_live : $stripe->pk_test;
        } else {
            $data['pk'] = '';
        }
        $this->session->set_userdata('orderReference', $lid . '#' . $sid);
        $this->session->set_userdata('isTheOnlineOrderPaid', 'no');
        $this->session->set_userdata('remote', $remote);
        $this->session->set_userdata('hasBillPrint', $hasBillPrint);
        $this->load->view('epos/stripeform', $data);
    }

    public function charge() {
        $stripe = $this->Epos_Model->get_single('paymentstripe', array('branch' => $this->session->userdata('branch'), 'status' => '3'))->row();
        if (!empty($stripe)) {
            $data['sk'] = $stripe->mode == 3 ? $stripe->sk_live : $stripe->sk_test;
        } else {
            $data['sk'] = '';
        }
        require APPPATH . '/libraries/stripe/init.php';
        \Stripe\Stripe::setApiKey($data['sk']);
        $errorArray = array();
        $charge = array();
        try {
            $infoArray = array(
                'amount' => to_currency_no_money(trim($this->input->post('amount'))) * 100,
                'currency' => 'GBP',
                'description' => $this->input->post('orderId') . '#' . $this->input->post('sid') . '#' . $this->input->post('status') . '#' . $this->session->userdata('owner'),
                'source' => $this->input->post('stripeToken'),
            );
            $charge = \Stripe\Charge::create($infoArray);
        } catch (\Stripe\Error\Card $e) {
            array_push($errorArray, $e->getMessage());
        } catch (\Stripe\Error\RateLimit $e) {
            array_push($errorArray, $e->getMessage());
        } catch (\Stripe\Error\InvalidRequest $e) {
            array_push($errorArray, $e->getMessage());
        } catch (\Stripe\Error\Authentication $e) {
            array_push($errorArray, $e->getMessage());
        } catch (\Stripe\Error\ApiConnection $e) {
            array_push($errorArray, $e->getMessage());
        } catch (\Stripe\Error\Base $e) {
            array_push($errorArray, $e->getMessage());
        } catch (Exception $e) {
            array_push($errorArray, $e->getMessage());
        } finally {
            if (!empty($errorArray)) {
                $this->session->set_flashdata('error', $this->lang->line('card_payment_rejected'));
                redirect('epos/paymentOnline/' . $this->input->post('orderId') . '/' . $this->input->post('status') . '/' . trim($this->input->post('amount')));
            } else {
                if (!empty($charge)) {
                    if ($charge->id && $charge->description && $charge->paid && $charge->status === 'succeeded') {
                        $this->session->unset_userdata('isTheOnlineOrderPaid');
                        $this->session->unset_userdata('orderReference');
                        $explodedArr = explode('#', $charge->description);
                        $data = array(
                            'reference_id' => $charge->id,
                            'description' => $charge->description,
                            'amount' => $charge->amount,
                            'paid' => $charge->paid,
                            'status' => $charge->status,
                            'orderId' => $explodedArr[0],
                            'orderSid' => $explodedArr[1],
                            'orderStatus' => $explodedArr[2],
                            'orderOwner' => $explodedArr[3],
                            'hasBillPrint' => (int) $this->session->userdata('hasBillPrint'),
                            'remote' => $this->session->userdata('remote')
                        );
                        $this->session->unset_userdata('hasBillPrint');
                        $this->session->unset_userdata('remote');
                        $this->session->set_flashdata('paymentData', $data);
                        redirect('epos');
                    } else {
                        $this->session->set_flashdata('error', $this->lang->line('card_payment_rejected'));
                        redirect('epos/paymentOnline/' . $this->input->post('orderId') . '/' . $this->input->post('status') . '/' . trim($this->input->post('amount')));
                    }
                }
            }
        }
    }

}
