<?php

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

use Restserver\Libraries\REST_Controller;

class GksoftApi extends REST_Controller
{

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

    public function epos_post()
    {
        $branch = $this->post('branch');
        $user = $this->post('user');
        $data['services'] = $this->GksoftApi_Model->get_single('service', array('branch' => $branch))->row_array();
        $data['updates'] = $this->GksoftApi_Model->get_list('updates', array('user' => (int) $user, 'status' => 2, 'branch' => $branch))->result();
        $data['branch'] = $this->GksoftApi_Model->get_single('branch', array('id' => $branch))->row_array();
        $data['terminals'] = unserialize($data['branch']['terminal']);
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function users_post()
    {
     
        $branch = $this->post('branch');
        $team = $this->post('branch');
        $users = $this->GksoftApi_Model->getUserList($branch, $team);
        $this->response($users, REST_Controller::HTTP_OK);
    }

    public function uservalidate_post()
    {
        $username = $this->post('username');
        $password = $this->post('password');
        $userID = $this->post('userId') ? $this->post('userId') : null;
        $employeeId = $this->post('employeeId') ? $this->post('employeeId') : null;
        $branch = $this->post('branch');
        $team = $this->post('team');
        $user = $this->GksoftApi_Model->getUser($username, $password, $userID, $employeeId, $branch, $team);
        $this->response($user, REST_Controller::HTTP_OK);
    }

    public function boot_post()
    {
        $data = $this->GksoftApi_Model->boot($this->post('param'));
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function reboot_post()
    {
        $data = $this->GksoftApi_Model->reboot($this->post('param'));
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function configuration_post()
    {
        $data = $this->db->get('configuration')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function branch_post()
    {
        $data = $this->db->where(array('id' => $this->post('branch')))->get('branch')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menucategory_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->order_by('position', 'ASC')->get('menucategory')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menu_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->order_by('position', 'ASC')->get('menu')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menuselection_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->order_by('position', 'ASC')->get('menuselection')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menuset_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('menuset')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menusetitem_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('menusetitem')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menuattrcategory_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('menuattrcategory')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menuattr_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('menuattr')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function modifiercategory_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('modifiercategory')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function modifiermenu_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('modifiermenu')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function nattrcategory_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('nattrcategory')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function nattr_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('nattr')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function modifier_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('modifier')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function menufixeddeal_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('menufixeddeal')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function discountitem_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('discountitem')->result();
        if (!empty($data)) {
            foreach ($data as $key => $obj) {
                $data[$key]->type = unserialize($obj->type);
                $data[$key]->item = unserialize($obj->item);
            }
        }
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function lcountry_post()
    {
        $data = $this->GksoftApi_Model->get_list('lcountry', null, array('id', 'title', 'position', 'status'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function lregion_post()
    {
        $data = $this->GksoftApi_Model->get_list('lregion', null, array('id', 'title', 'country', 'position', 'status'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function lcity_post()
    {
        $data = $this->GksoftApi_Model->get_list('lcity', null, array('id', 'title', 'region', 'position', 'status'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function larea_post()
    {
        $data = $this->GksoftApi_Model->get_list('larea', null, array('id', 'title', 'city', 'position', 'status'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function lpostcode_post()
    {
        $data = $this->GksoftApi_Model->get_list('lpostcode', null, array('id', 'city', 'area', 'title'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function ldooraddress_post()
    {
        $data = $this->Api_Model->get_list('ldooraddress')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function customer_post()
    {
        $data = $this->GksoftApi_Model->get_list('customer', null, array('id', 'name', 'phone', 'email'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function customeraddress_post()
    {
        $data = $this->GksoftApi_Model->get_list('customer_address', null, array('cid', 'country', 'region', 'city', 'area', 'postcode', 'street', 'building', 'floor', 'apartment'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function discountplan_post()
    {
        $data = $this->GksoftApi_Model->get_list('discountplan', array('branch' => $this->post('branch')))->result();
        if (!empty($data)) {
            foreach ($data as $key => $discountPlan) {
                $data[$key]->onday = unserialize($discountPlan->onday);
                $data[$key]->onapp = unserialize($discountPlan->onapp);
                $data[$key]->onitem = unserialize($discountPlan->onitem);
                $data[$key]->min_order = (int) $discountPlan->min_order;
                $data[$key]->discount = (int) $discountPlan->discount;
                $startTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->start_time);
                $data[$key]->start_time = $startTimeObject->format('g:i:s A');
                $endTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->end_time);
                $data[$key]->end_time = $endTimeObject->format('g:i:s A');
            }
        }
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function discountmulti_post()
    {
        $data = $this->GksoftApi_Model->get_list('discountmulti', array('branch' => $this->post('branch')))->result();
        if (!empty($data)) {
            foreach ($data as $key => $discountPlan) {
                $data[$key]->onday = unserialize($discountPlan->onday);
                $data[$key]->onapp = unserialize($discountPlan->onapp);
                $data[$key]->min_order = (int) $discountPlan->min_order;
                $data[$key]->buy = (float) $discountPlan->buy;
                $data[$key]->get = (float) $discountPlan->get;
                $data[$key]->category = (int) $discountPlan->category;
                $data[$key]->menu = (int) $discountPlan->menu;
                $data[$key]->selection = (int) $discountPlan->selection;
                $startTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->start_time);
                $data[$key]->start_time = $startTimeObject->format('g:i:s A');
                $endTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->end_time);
                $data[$key]->end_time = $endTimeObject->format('g:i:s A');
            }
        }
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function deliveryplan_post()
    {
        $data = $this->db->where(array('branch' => $this->post('branch')))->get('deliveryplan')->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function changeownerupdatestatus_post()
    {
        $status1 = $this->db->update('user', array('hasUpdate' => 'no'), array('id' => (int) $this->post('owner')));
        $status2 = $this->db->update('updates', array('status' => 3), array('user' => $this->post('owner')));
        $this->response(array('status' => $status1 || $status2 ? true : false), REST_Controller::HTTP_OK);
    }

    public function update_post()
    {
        $issue = $this->post('issue');
        $owner = $this->post('owner');
        $issueId = $this->GksoftApi_Model->get_single('updateissue', array('title' => $issue))->row()->id;
        $status = false;
        $thisUser = $this->db->where(array('id' => $owner, 'hasUpdate' => 'yes'))->get('user')->row();
        if (!empty($thisUser)) {
            $status = $this->db->update('updates', array('status' => 3), array('user' => $thisUser->id, 'issue' => $issueId));
        }
        $pendingUpdates = $updates = $this->db->where(array('status' => 2, 'user' => $thisUser->id))->get('updates')->result();
        if (count($pendingUpdates) < (int) 1) {
            $this->db->update('user', array('hasUpdate' => 'no'), array('id' => (int) $thisUser->id));
        }
        $this->response(array('status' => true, 'issuesPending' => count($pendingUpdates)), REST_Controller::HTTP_OK);
    }

    public function updateprofile_post()
    {
        $data = $this->post();
        $owner = $data['id'];
        unset($data['id']);
        $status = $this->db->update('user', $data, array('id' => $owner));
        $this->response(array('status' => $status ? true : false), REST_Controller::HTTP_OK);
    }

    public function paymentoption_post()
    {
        $data = $this->GksoftApi_Model->get_list('paymentoption', null, array('id', 'title', 'status'))->result();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function paymentonline_post()
    {
        $data = $this->GksoftApi_Model->get_single('paymentstripe', array('branch' => $this->post('branch'), 'status' => '3'))->row();
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function getpendingonlineOrder_post()
    {
        $branch = $this->post('branch');
        $team = $this->post('team');
        $onlineOrder = $this->GksoftApi_Model->get_list('order', array('source' => 'online', 'status_online' => '2', 'branch' => $branch, 'team' => $team))->result();
        $this->response(count($onlineOrder), REST_Controller::HTTP_OK);
    }

    public function getonlineorder_post()
    {
        $branch = $this->post('branch');
        $orders = $this->db->where(array('status <' => 5, 'status_online <' => 3, 'source' => 'online', 'branch' => $branch))->order_by('status_online', 'ASC')->get('order')->result();
        if (!empty($orders)) {
            foreach ($orders as $key => $order) {
                $orders[$key]->orderInfo = unserialize($order->orderInfo);
                $orders[$key]->cart = unserialize($order->cart);
                if (trim($order->payment) && $order->isPaid == 3) {
                    $orders[$key]->payment = unserialize($order->payment);
                }
                if (trim($order->onlinePaymentDetails) && $order->isPaid == 3) {
                    $orders[$key]->onlinePaymentDetails = unserialize($order->onlinePaymentDetails);
                }
                $timeType = "ASAP";
                if ($order->type === "collection") {
                    $timeType = $orders[$key]->orderInfo['collectionTime'];
                }
                if ($order->type === "delivery") {
                    $timeType = $orders[$key]->orderInfo['deliveryTime'];
                }
                $orders[$key]->timeType = $timeType;
                if ($timeType === 'ASAP') {
                    $timeSlot = array();
                    $timeSlot[0] = "ASAP";
                    $startObj = new DateTime(date('h:i a'));
                    $startTime = $startObj->format('h:i a');
                    $endObj = new DateTime(date('h:i a'));
                    $endObj->add(new DateInterval('PT3H'));
                    $interval = $startObj->diff($endObj);
                    $totalMins = 0;
                    if ($interval->h >= 1) {
                        $totalMins += $interval->h * 60;
                    }
                    if ($interval->i >= 1) {
                        $totalMins += $interval->i;
                    }
                    $rem = $totalMins % 15;
                    $totalMins += 15 - $rem;
                    $timeSlotIndex = ceil(($totalMins) / 15);
                    for ($i = 1; $i <= $timeSlotIndex; $i++) {
                        $nowSlotDate = new DateTime($startTime);
                        $nowSlotDate->add(new DateInterval('PT15M'));
                        $nowSlotTime = $nowSlotDate->format('h:i a');
                        $timeSlot[] = $nowSlotTime;
                        $startTime = $nowSlotTime;
                    }
                    $orders[$key]->interval = $timeSlot;
                } else {
                    $timeSlot = array();
                    $timeSlot[0] = 0;
                    for ($i = 1; $i < 12; $i++) {
                        $timeSlot[$i] = $timeSlot[$i - 1] + 5;
                    }
                    $orders[$key]->interval = $timeSlot;
                }
            }
        }
        $this->response($orders, REST_Controller::HTTP_OK);
    }

    public function acceptonlineorder_post()
    {
        $extraTime = $this->post('extraTime');
        $sid = $this->post('sid');
        $timeType = $this->post('timeType');
        $order = $this->Api_Model->get_single('order', array('sid' => $sid))->row();
        $orderInfo = unserialize($order->orderInfo);
        if ($order->type === 'collection') {
            if ($timeType === "ASAP") {
                $orderInfo['collectionTime'] = $extraTime;
            } else {
                $collectionTimeObj = new DateTime($orderInfo['collectionTime']);
                $collectionTimeObj->add(new DateInterval('PT' . $extraTime . 'M'));
                $nowTime = $collectionTimeObj->format('h:i a');
                $orderInfo['collectionTime'] = $nowTime;
            }
        } else {
            if ($timeType === "ASAP") {
                $orderInfo['deliveryTime'] = $extraTime;
            } else {
                $deliveryTimeObj = new DateTime($orderInfo['deliveryTime']);
                $deliveryTimeObj->add(new DateInterval('PT' . $extraTime . 'M'));
                $nowTime = $deliveryTimeObj->format('h:i a');
                $orderInfo['deliveryTime'] = $nowTime;
            }
        }
        $this->Api_Model->save(array('orderInfo' => serialize($orderInfo), 'status' => 2, 'status_online' => 3), $sid);
        $orderNow = $this->Api_Model->get_single('order', array('sid' => $sid))->row_array();

        /* message required part */
        $orderInfo = unserialize($orderNow['orderInfo']);
        $text = "";
        if ($orderNow['type'] === "collection") {
            $text = $orderInfo['collectionTime'] === "ASAP" ? "Thank you for placing order with us. Your order will be ready to collect ASAP" : "Thank you for placing order with us. Your order will be ready to collect at around " . $orderInfo['collectionTime'];
        } else {
            $text = $orderInfo['deliveryTime'] === "ASAP" ? "Thank you for placing order with us. Your order will be ready to collect ASAP" : "Thank you for placing order with us. Your order will be ready to delivery at around " . $orderInfo['deliveryTime'];
        }
        /* message required part end*/

        /* sms sending required part */
        if (!empty($orderInfo['phone']) && config_item('sms_service') === TRUE) {
            $ref = $orderNow['sid'] . '/' . $orderNow['orderId'];
            $sms = sms($orderInfo['phone'], $text, $ref);
        }
        /* sms sending required part end */

        /* email sending required part */
        if (!empty($orderInfo['email']) && config_item('email_service') === TRUE) {
            $orderInfo['branch'] = $orderNow['branch'];
            $this->__send_email($orderInfo, 'Order Accepted', $text);
        }
        /*email sending required part End */
        $this->response($orderNow, REST_Controller::HTTP_OK);
    }

    public function rejectonlineorder_post()
    {
        $rejectMsg = $this->post('rejectMsg');
        $sid = $this->post('sid');
        $s1 = $this->Api_Model->save(array('rejectMsg' => $rejectMsg, 'status_online' => 4), $sid);
        $orderNow = $this->Api_Model->get_single('order', array('sid' => $sid))->row_array();
        /* message required part */
        $orderInfo = unserialize($orderNow['orderInfo']);
        $text = empty(trim($rejectMsg)) ? $rejectMsg : $rejectMsg . ". Your order has been rejected.";
        /* message required part end */

        /* sms sending required part */
        if (!empty($orderInfo['phone']) && config_item('sms_service') === TRUE) {
            $ref = $orderNow['sid'] . '/' . $orderNow['orderId'];
            $sms = sms($orderInfo['phone'], $text, $ref);
        }
        /* sms sending required part end */

        /* email sending required part */
        if (!empty($orderInfo['email']) && config_item('email_service') === TRUE) {
            $orderInfo['branch'] = $orderNow['branch'];
            $this->__send_email($orderInfo, 'Order Rejected', $text);
        }
        /*email sending required part End */

        $this->response($orderNow, REST_Controller::HTTP_OK);
    }

    /* email sending required part */
    private function __send_email($to, $title, $msg)
    {
        $branch = $this->Api_Model->get_single('branch', array('id' => $to['branch']))->row_array();
        $data['recipent'] = $to['name'];
        $data['to'] = $to['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 send_api_email($data);
    }
    /* email sending required part end*/
    public function deleteonlineorder_post()
    {
        $invoice = $this->post('invoice');
        $status = $this->db->delete('order', array('invoice' => $invoice));
        $this->response($status, REST_Controller::HTTP_OK);
    }

    public function getpendingbooking_post()
    {
        $branch = $this->post('branch');
        $onlineOrder = $this->Api_Model->get_list('booking', array('status' => '1', 'date >=' => date('Y-m-d'), 'branch' => $branch))->result();
        $this->response(count($onlineOrder), REST_Controller::HTTP_OK);
    }

    public function getbookinglist_post()
    {
        $bookingList = array();
        $today = $this->post('today');
        $branch = $this->post('branch');
        if ($today === 'yes') {
            $bookingList = $this->db->where(array('date' => date('Y-m-d'), 'branch' => $branch))->order_by('date', 'ASC')->get('booking')->result();
        } else {
            $bookingList = $this->db->where(array('date >=' => date('Y-m-d'), '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);
    }

    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($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;
            $text = "Thank you for your booking,<br/>" . $msg . "<br/> Details below <br/>";
            $text .= "Name :" . $booking['first_name'] . ' ' . $booking['last_name'];
            $text .= "<br/>Date :" . date('d/m/Y', strtotime($booking['date']));
            $text .= "<br/>Quantity :" . $booking['guest_qty'];
            $text .= "<br/>Time :" . $booking['time'];
            $text .= "<br/><br/>";
            $text .= "If you have any query please call us <br/>";
            $text .= "Phone:" . $this->config->item('general_phone');
            $data['txt'] = $text;
            $data['verify_link'] = null;
            $data['branch'] = $branch;
            $data['message'] = $this->load->view('api/email', $data, true);
            return $this->send_email($data);
        }
    }

    public function saveeposbooking_post()
    {
        $data = $this->post();
        if (isset($data['id']) && $data['id'] > 0) {
            $BookingDate = DateTime::createFromFormat('d/m/Y', $data['date'] != null ? $data['date'] : date('d/m/Y', strtotime('today')));
            $data['date'] = $BookingDate->format('Y-m-d');
            $id = $this->Api_Model->save_booking($data, $data['id']);
            if ($id > 0) {
                $this->response(true, REST_Controller::HTTP_OK);
            } else {
                $this->response(false, REST_Controller::HTTP_OK);
            }
        } else {
            $data['status'] = 2;
            $BookingDate = DateTime::createFromFormat('d/m/Y', $data['date'] != null ? $data['date'] : date('d/m/Y', strtotime('today')));
            $data['date'] = $BookingDate->format('Y-m-d');
            $id = $this->Api_Model->save_booking($data, NULL);
            if ($id > 0) {
                if (!empty($data['email'])) {
                    $status = $this->prepareBookingEmailTemplateAndForwardToSend($id, $this->lang->line('booking') . ' ' . $this->lang->line('confirmed'), $this->lang->line('booking_create_confirm'), $data['branch']);
                }
                $this->response(true, REST_Controller::HTTP_OK);
            } else {
                $this->response(false, REST_Controller::HTTP_OK);
            }
        }
    }

    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 getbookingreport_post()
    {
        $bookingReport = $this->GksoftApi_Model->getbookingreport($this->post('start'), $this->post('end'), $this->post('branch'), $this->post('type'));
        $this->response($bookingReport, REST_Controller::HTTP_OK);
    }

    public function deletebooking_post()
    {
        $id = $this->post('id');
        if ((int) $id > 0) {
            $status = $this->db->delete('booking', array('id' => $id));
            $this->response($status, REST_Controller::HTTP_OK);
        }
    }

    public function uploaddata_post()
    {
        $this->response($this->post(), REST_Controller::HTTP_OK);
        $orders = unserialize($this->post('orders'));
        $expense = unserialize($this->post('expense'));
        $expenseledger = unserialize($this->post('expenseledger'));
        $income = unserialize($this->post('income'));
        $incomeledger = unserialize($this->post('incomeledger'));
        $invoices = array();
        $expenses = array();
        $expenseledgers = array();
        $incomes = array();
        $incomeledgers = array();
        if (!empty($orders)) {
            $orders = objectToArray($orders);
            foreach ($orders as $order) {
                unset($order['sid']);
                unset($order['uploaded']);
                if ($this->Api_Model->get_single('order', array('invoice' => $order['invoice']))->row()) {
                    $update = $this->db->update('order', $order, array('invoice' => $order['invoice']));
                    $update ? array_push($invoices, $order['invoice']) : '';
                } else {
                    $insert = $this->db->insert('order', $order);
                    $insert ? array_push($invoices, $order['invoice']) : '';
                }
            }
        }
        if (!empty($expense)) {
            $expense = objectToArray($expense);
            foreach ($expense as $exp) {
                if ($this->Api_Model->get_single('expense', array('id' => $exp['id']))->row()) {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $update = $this->db->update('expense', $exp, array('id' => $id));
                    $update ? array_push($expenses, $id) : '';
                } else {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $insert = $this->db->insert('expense', $exp);
                    $insert ? array_push($expenses, $id) : '';
                }
            }
        }

        if (!empty($expenseledger)) {
            $expenseledger = objectToArray($expenseledger);
            foreach ($expenseledger as $exp) {
                if ($this->Api_Model->get_single('expenseledger', array('id' => $exp['id']))->row()) {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $update = $this->db->update('expenseledger', $exp, array('id' => $id));
                    $update ? array_push($expenseledgers, $id) : '';
                } else {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $insert = $this->db->insert('expenseledger', $exp);
                    $insert ? array_push($expenseledgers, $id) : '';
                }
            }
        }
        if (!empty($income)) {
            $income = objectToArray($income);
            foreach ($income as $exp) {
                if ($this->Api_Model->get_single('income', array('id' => $exp['id']))->row()) {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $update = $this->db->update('income', $exp, array('id' => $id));
                    $update ? array_push($incomes, $id) : '';
                } else {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $insert = $this->db->insert('income', $exp);
                    $insert ? array_push($incomes, $id) : '';
                }
            }
        }
        if (!empty($incomeledger)) {
            $incomeledger = objectToArray($incomeledger);
            foreach ($incomeledger as $exp) {
                if ($this->Api_Model->get_single('incomeledger', array('id' => $exp['id']))->row()) {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $update = $this->db->update('incomeledger', $exp, array('id' => $id));
                    $update ? array_push($incomeledgers, $id) : '';
                } else {
                    $id = $exp['id'];
                    unset($exp['id']);
                    unset($exp['uploaded']);
                    $insert = $this->db->insert('incomeledger', $exp);
                    $insert ? array_push($incomeledgers, $id) : '';
                }
            }
        }
        $this->response(array('invoices' => $invoices, 'expense_ids' => $expenses, 'expenseledger_ids' => $expenseledgers, 'income_ids' => $incomes, 'incomeledger_ids' => $incomeledgers), REST_Controller::HTTP_OK);
    }
}
