<?php

defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';

use Restserver\Libraries\REST_Controller;

class App extends REST_Controller {

    function __construct($config = 'rest') {
        parent::__construct($config);
        $this->load->model('App_Model');
        $this->load->model('Api_Model');
    }

    public function index_post() {
        $branch = $this->post('branch');
        $orders = $this->App_Model->get_list('order', array('source' => 'online', 'status_online' => '2', 'branch' => $branch), null, 1, 0, 'sid', 'ASC')->result();
        $resturantInfo = array();
        if (!empty($orders)) {
            foreach ($orders as $key => $order) {
                //Approach-1 
                 /*
                $orders[$key]->orderInfo = unserialize($order->orderInfo);
                $orders[$key]->cart = unserialize($order->cart);
                $orders[$key]->payment = unserialize($order->payment);
                if (trim($order->onlinePaymentDetails) && $order->isPaid == 3) {
                    $orders[$key]->onlinePaymentDetails = unserialize($order->onlinePaymentDetails);
                }
                */
                
                //Approach-2 
                /*
                //$orders[$key]->orderInfo = unserialize(utf8_encode($order->orderInfo));
                $orders[$key]->orderInfo = unserialize($order->orderInfo);
                $orders[$key]->cart = unserialize(utf8_encode($order->cart));
                $orders[$key]->payment = unserialize(utf8_encode($order->payment));
                if (trim($order->onlinePaymentDetails) && $order->isPaid == 3) {
                    $orders[$key]->onlinePaymentDetails = unserialize(utf8_encode($order->onlinePaymentDetails));
                }
                */
                 //Approach-3 
                $orderInfo = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';},$order->orderInfo);
                $orders[$key]->orderInfo = unserialize($orderInfo);
                $cart = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';},$order->cart);
                $orders[$key]->cart = unserialize($cart);
                $payment = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';},$order->payment);
                $orders[$key]->payment= unserialize($payment);
                if (trim($order->onlinePaymentDetails) && $order->isPaid == 3) {
                    $onlinePaymentDetails= preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';},$order->onlinePaymentDetails);
                    $orders[$key]->onlinePaymentDetails = unserialize($onlinePaymentDetails);
                }
            }
            $branchInfo = $this->App_Model->get_single('branch', array('id' => $branch), array('title', 'address_street', 'address_postcode', 'address_city', 'general_phone', 'general_mobile', 'general_email', 'receipt_law', 'locale_currencyicon', 'default_tinnumber', 'kitchenPrinterIp', 'default_tax'))->row();
            $resturantInfo = array(
                'name' => $this->config->item('general_name'),
                'branch' => $branchInfo->title,
                'logo' => EPOS_UPLOAD_PATH . $this->config->item('general_logo'),
                'street' => $branchInfo->address_street,
                'city' => $branchInfo->address_city,
                'postcode' => $branchInfo->address_postcode,
                'phone' => $branchInfo->general_phone,
                'mobile' => $branchInfo->general_mobile,
                'email' => $branchInfo->general_email,
                'receiptText' => $branchInfo->receipt_law,
                'tin' => $branchInfo->default_tinnumber,
                'date' => date('d/m/Y'),
                'time' => date('h:i a'),
            );
        }
        $this->response(array('status' => !empty($orders) ? true : false, 'restaurantInfo' => $resturantInfo, 'data' => $orders), REST_Controller::HTTP_OK);
    }

    public function accept_post() {
        $extraTime = $this->post('extraTime');
        $sid = $this->post('sid');
        $order = $this->App_Model->get_single('order', array('sid' => $sid))->row();
        $orderInfo = unserialize($order->orderInfo);
        if ($order->type === 'collection') {
            if($orderInfo['collectionTime']!=="ASAP"){
                $collectionTimeObj = new DateTime($orderInfo['collectionTime']);
                $collectionTimeObj->add(new DateInterval('PT' . $extraTime . 'M'));
                $nowTime = $collectionTimeObj->format('h:i a');
                $orderInfo['collectionTime'] = $nowTime;
            }
            
        } else {
            if ($orderInfo['deliveryTime']!=="ASAP") {
                $deliveryTimeObj = new DateTime($orderInfo['deliveryTime']);
                $deliveryTimeObj->add(new DateInterval('PT' . $extraTime . 'M'));
                $nowTime = $deliveryTimeObj->format('h:i a');
                $orderInfo['deliveryTime'] = $nowTime;
            }
        }
        $s1 = $this->App_Model->save(array('orderInfo' => serialize($orderInfo), 'status' => 2, 'status_online' => 3), $sid);
        $this->response(array('status' => $s1 ? true : false), REST_Controller::HTTP_OK);
    }

    public function reject_post() {
        $rejectMsg = $this->post('rejectMsg');
        $sid = $this->post('sid');
        $s1 = $this->App_Model->save(array('rejectMsg' => $rejectMsg, 'status_online' => 4), $sid);
        $this->response(array('status' => $s1 ? true : false), REST_Controller::HTTP_OK);
    }
    
     public function pendingbooking_post() {
        $branch = $this->post('branch');
        $booking = $this->App_Model->get_list('booking', array('status' => '1', 'branch' => $branch, 'date >=' => date('Y-m-d')), null, 1, 0, 'id', 'ASC')->result();
         if (!empty($booking)) {
            $booking[0]->date = date('d/m/Y', strtotime($booking[0]->date));
        }
        $this->response(array('status' => !empty($booking) ? true : false, 'booking' => $booking), REST_Controller::HTTP_OK);
    }

    public function updatebookingstatus_post() {
        $statusArr = array(1 => $this->lang->line('pending'), 2 => $this->lang->line('confirmed'), 3 => $this->lang->line('rejected'));
        $id = $this->post('id');
        $status = $this->post('status');
        $branch = $this->post('branch');
        $returnId = $this->Api_Model->save_booking(array('status' => $status), $id);
        $emailStatus = false;
        if ($returnId) {
            if ((int) $status >= 2) {
                $emailStatus = $this->prepareBookingEmailTemplateAndForwardToSend($returnId, 'Booking ' . $statusArr[(int) $status], $this->lang->line('booking_status_trailer') . $statusArr[(int) $status], $branch);
            }
        }
        $this->response(array('status' => $returnId || $emailStatus ? true : false), REST_Controller::HTTP_OK);
    }

    public function prepareBookingEmailTemplateAndForwardToSend($id, $title, $msg, $branch) {
        $booking = $this->Api_Model->get_single('booking', array('id' => $id))->row_array();
        if (!empty($booking)) {
            $branch = $this->Api_Model->get_single('branch', array('id' => $branch))->row_array();
            $data['recipent'] = $booking['first_name'] . ' ' . $booking['last_name'];
            $data['to'] = $booking['email'];
            $data['from'] = $branch['general_email'];
            $data['from_title'] = $this->config->item('general_name');
            $data['subject'] = $title;
            $data['txt'] = $msg;
            $data['verify_link'] = null;
            $data['branch'] = $branch;
            $data['message'] = $this->load->view('api/email', $data, true);
            return $this->send_email($data);
        }
    }

    public function send_email($data = null) {
        if ($data != null || !empty($data)) {
            $this->load->library('email');
            $config['mailtype'] = 'html';
            $config['send_multipart'] = FALSE;
            $config['wordwrap'] = TRUE;
            $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') {
                return $this->email->send() ? TRUE : FALSE;
            } else {
                return TRUE;
            }
        }
    }

    public function bookinglist_post() {
        $branch = $this->post('branch');
        $bookingList = $this->db->where(array('date >=' => date('Y-m-d'), 'status' => 2, 'branch' => $branch))->order_by('date', 'ASC')->get('booking')->result();
        if (!empty($bookingList)) {
            foreach ($bookingList as $key => $abl) {
                $bookingList[$key]->date = date('d/m/Y', strtotime($abl->date));
            }
        }
        $this->response($bookingList, REST_Controller::HTTP_OK);
    }

}
