<?php

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

class Report extends Epos_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('Report_Model');
        if ($this->Report_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($dateFrom = null, $dateTo = null, $id = null, $source = null, $type = null, $payment = null, $branch = null) {
        $start_date = DateTime::createFromFormat('d-m-Y', $dateFrom != 0 ? $dateFrom : date('d-m-Y'));
        $end_date = DateTime::createFromFormat('d-m-Y', $dateTo != 0 ? $dateTo : date('d-m-Y'));
        $start_date_value = $start_date->format('Y-m-d');
        $end_date_value = $end_date->format('Y-m-d');
        if ((int) $branch <= 0) {
            $branch = $this->session->userdata('branch');
        }
        $orderList = $this->Report_Model->getReportData($start_date_value, $end_date_value, $id, $source, $type, $branch)->result();
        if ($payment) {
            foreach ($orderList as $key => $obj) {
                $payments = unserialize($obj->payment);
                $found = 0;
                if (count($payments) > 0) {
                    foreach ($payments as $aPayment) {
                        if ($aPayment['type'] === $payment) {
                            $found++;
                        }
                    }
                }
                if ($found === 0) {
                    unset($orderList[$key]);
                }
            }
        }
        $data['orderList'] = $orderList;
        if ($id) {
            $idArr = explode('-', $id);
            $id = $idArr[0] . '/' . $idArr[1];
        }
        $data['filterData'] = array($start_date->format('d-m-Y'), $end_date->format('d-m-Y'), $id, $source, $type, $payment, $branch);
        $data['expenseFromTill'] = $this->Report_Model->getExpenseTotal($start_date->format('Y-m-d'), $end_date->format('Y-m-d'));
        $data['branches'] = $this->Report_Model->get_list('branch', array('status' => 3), array('id', 'title'))->result();
        $data['refresh'] = base_url(uri_string());
        $data['statementDateFrom'] = $start_date->format('d-m-Y');
        $data['statementDateTo'] = $end_date->format('d-m-Y');
        $data['incomeData'] = $this->Report_Model->getIncomeDataInReport($start_date->format('Y-m-d'), $end_date->format('Y-m-d'));
        if ($dateFrom === 'verified') {
            $this->render('index', $data);
        } else {
            $this->load->view('index', $data, false);
        }
    }

    public function online($dateFrom = null, $dateTo = null, $id = null, $source = 'online', $type = null, $payment = null, $branch = null) {
        $start_date = DateTime::createFromFormat('d-m-Y', $dateFrom != 0 ? $dateFrom : date('d-m-Y'));
        $end_date = DateTime::createFromFormat('d-m-Y', $dateTo != 0 ? $dateTo : date('d-m-Y'));
        if ((int) $branch <= 0) {
            $branch = $this->session->userdata('branch');
        }
        $data['filterData'] = array($start_date->format('d-m-Y'), $end_date->format('d-m-Y'), $id, $source, $type, $payment, $branch);
        $data['orderList'] = $this->Report_Model->getOnlineReportData($start_date->format('Y-m-d'), $end_date->format('Y-m-d'), $id, $source, $type, $branch)->result();
        $data['branches'] = $this->Report_Model->get_list('branch', array('status' => 3), array('id', 'title'))->result();
        $data['refresh'] = base_url(uri_string());
        $this->load->view('online', $data, false);
    }

    public function listItem($sid) {
        $data['theOrder'] = $this->Report_Model->get_single('order', array('sid' => (int) $sid))->row_array();
        $this->load->view('report/listItem', $data, false);
    }

    public function deleteOrder($orderId) {
        if ((int) $orderId > 0) {
            $status = $this->Report_Model->deleteOrder($orderId);
            if ($status) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has deleted order #' . $orderId
                );
                $this->Report_Model->posactivity($activity);
            }
            echo json_encode(array('status' => $status));
        }
    }

    public function refund() {
        if (trim($this->input->post('charge')) && trim($this->input->post('sid'))) {
            $charge = $this->input->post('charge');
            $sid = $this->input->post('sid');
            $stripe = $this->Report_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/stripe3d/init.php';
            \Stripe\Stripe::setApiKey($data['sk']);
            try {
                $refundObj = \Stripe\Refund::create([
                            'payment_intent' => $charge,
                ]);
                //$refundObj = \Stripe\Refund::create(array("charge" => $charge));
                if ($refundObj->status === 'succeeded') {
                    $status = $this->Report_Model->deleteOrder($sid);
                    echo json_encode(array('status' => true || $status, 'message' => 'success'));
                } else {
                    echo json_encode(array('status' => false, 'message' => 'success'));
                }
            } catch (Exception $e) {
                echo json_encode(array('status' => false, 'message' => $e->getMessage()));
            }
        } else {
            echo json_encode(array('status' => false, 'message' => 'Opps'));
        }
    }

    public function expense($dateFrom = null, $dateTo = null) {
        $start_date = DateTime::createFromFormat('d-m-Y', $dateFrom != 0 ? $dateFrom : date('d-m-Y'));
        $end_date = DateTime::createFromFormat('d-m-Y', $dateTo != 0 ? $dateTo : date('d-m-Y'));
        $start_date_value = $start_date->format('Y-m-d');
        $end_date_value = $end_date->format('Y-m-d');
        $data['expenseList'] = $this->Report_Model->getExpenseData($start_date_value, $end_date_value)->result();
        $data['ledgers'] = $this->Report_Model->get_list('expenseledger', array('branch' => $this->session->userdata('branch')))->result();
        $data['filterData'] = array($start_date->format('d-m-Y'), $end_date->format('d-m-Y'));
        $data['refresh'] = base_url(uri_string());
        $this->load->view('report/expense', $data, false);
    }

    public function income($dateFrom = null, $dateTo = null) {
        $start_date = DateTime::createFromFormat('d-m-Y', $dateFrom != 0 ? $dateFrom : date('d-m-Y'));
        $end_date = DateTime::createFromFormat('d-m-Y', $dateTo != 0 ? $dateTo : date('d-m-Y'));
        $start_date_value = $start_date->format('Y-m-d');
        $end_date_value = $end_date->format('Y-m-d');
        $data['expenseList'] = $this->Report_Model->getIncomeData($start_date_value, $end_date_value)->result();
        $data['ledgers'] = $this->Report_Model->get_list('incomeledger', array('branch' => $this->session->userdata('branch')))->result();
        $data['filterData'] = array($start_date->format('d-m-Y'), $end_date->format('d-m-Y'));
        $data['refresh'] = base_url(uri_string());
        $this->load->view('report/income', $data, false);
    }

    public function saveExpense() {
        $data = $this->preparePostedData();
        $data['created_by'] = 1;
        $data['branch'] = $this->session->userdata('branch');
        $data['dateD'] = date('d');
        $data['dateM'] = date('m');
        $data['dateY'] = date('Y');
        $status = $this->Report_Model->saveExpense($data);
        if ($status) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added expense #' . to_currency($data['expenseAmount'])
            );
            $this->Report_Model->posactivity($activity);
        }
        echo json_encode(array('status' => $status ? true : false, 'message' => $status ? 'ok' : 'Error in saving ledger'));
    }

    public function saveIncome() {
        $data = $this->preparePostedData();
        $data['created_by'] = 1;
        $data['branch'] = $this->session->userdata('branch');
        $status = $this->Report_Model->saveIncome($data);
        if ($status) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added income #' . to_currency($data['expenseAmount'])
            );
            $this->Report_Model->posactivity($activity);
        }
        echo json_encode(array('status' => $status ? true : false, 'message' => $status ? 'ok' : 'Error in saving income'));
    }

    public function saveExpenseLedger() {
        $data['title'] = $this->input->post('title');
        $data['created_by'] = 1;
        $data['branch'] = $this->session->userdata('branch');
        $status = $this->Report_Model->saveExpenseLedger($data);
        if ($status) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added expense ledger ' . $data['title']
            );
            $this->Report_Model->posactivity($activity);
        }
        echo json_encode(array('status' => $status ? true : false, 'message' => $status ? 'ok' : 'Error in saving ledger'));
    }

    public function saveIncomeLedger() {
        $data['title'] = $this->input->post('title');
        $data['created_by'] = 1;
        $data['branch'] = $this->session->userdata('branch');
        $status = $this->Report_Model->saveIncomeLedger($data);
        if ($status) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added income source ' . $data['title']
            );
            $this->Report_Model->posactivity($activity);
        }
        echo json_encode(array('status' => $status ? true : false, 'message' => $status ? 'ok' : 'Error in saving ledger'));
    }

    public function checkIncomeledger() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $result = $this->Report_Model->checkIncomeledger($column, $value);
        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function checkledger() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $result = $this->Report_Model->checkledger($column, $value);
        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function deleteExpense($id) {
        if ((int) $id > 0) {
            echo json_encode(array('status' => $this->db->delete('expense', array('id' => $id))));
        }
    }

    public function deleteIncome($id) {
        if ((int) $id > 0) {
            echo json_encode(array('status' => $this->db->delete('income', array('id' => $id))));
        }
    }

    public function printTransaction() {
        $json = $this->input->post('json');
        $status = $this->db->insert('transactionsummary', array('data' => serialize($json), 'branch' => $this->session->userdata('branch'), 'team' => $this->session->userdata('team')));
        echo json_encode(array('status' => $status ? true : false));
    }

    public function reportBulkDelete() {
        $this->db->where_in('sid', $this->input->post('ids'));
        $deleteOrder = $this->db->delete('order');
        $this->db->where_in('sid', $this->input->post('ids'));
        $deletePrint = $this->db->delete('printing');
        echo json_encode(array('status' => $deleteOrder && $deletePrint ? true : false));
    }

}
