<?php
class AdminAjax extends CI_Controller{
    private $context;
    private $response;
    public function __construct(){
        parent::__construct();
        $this->context = array(
            md5('acl/removeconfigimage') => '__acl_remove_config_image',
            md5('acl/paybkashmanual') => '__acl_pay_bkash_manual',
            md5('acl/paydynamicmanual') => '__acl_pay_dynamic_manual',
            md5('acl/canceltransaction') => '__acl_cancel_transaction',
            md5('acl/removetransaction') => '__acl_remove_transaction',
            md5('acl/reviewtransaction') => '__acl_review_transaction',
            md5('acl/allexpiretransaction') => '__acl_allowexpire_transaction',
            md5('acl/algeneratechartdata') => '__acl_generate_chart_data',
            md5('acl/aclunpaidtransaction') => '__acl_rollback_transaction'
        );
        $this->response = array(
            'state' => false,
            'message' => '404:UNKOWN EVENT'
        );
    }

    public function index(){
        $context = $this->input->post('context', true);
        $data = $this->input->post('data', true);


        if($this->input->is_ajax_request() && $this->session->has_userdata('logged')){
            if($context!=null && !empty($context) && array_key_exists($context, $this->context) && method_exists($this, $this->context[$context]) && is_array($data)){
                call_user_func_array(array($this, $this->context[$context]), array($data));
            }
        }
        echo 0;
    }

    private function __acl_remove_config_image(array $data){
        $this->response['message'] = 'There is nothing to remove';
        $config  = array_key_exists('cir', $data)?$data['cir']:'';
        if(!empty($config)){
            $filename = $this->settings_model->get($config);
            $flag = 0;
            if(!empty($filename) && file_exists(FCPATH . 'images/'.$filename)){
                if(@unlink(FCPATH . 'images/'.$filename)){
                    $flag++;
                }
            }
            if(!empty($filename)){
                if($this->settings_model->update($config)) {
                    $flag++;
                }
            }
            if($flag>0){
                $this->response['state'] = true;
                $this->response['message'] = 'removed successfully';
            }
        }
        $this->sendResponse();
    }

    private function __acl_pay_bkash_manual(array $data) {
        $this->response['message'] = 'There is nothing to pay';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        $trxid = trim(array_key_exists('trxid', $data) ? $data['trxid'] : '');
        $mobile = trim(array_key_exists('mobile', $data) ? $data['mobile'] : '');

        if(!empty($reference) && !empty($trxid) && !empty($mobile)) {
            if(strtolower($trxid) == strtolower('N/A') || !$this->transaction_model->existsByTrxId($trxid)){
                if( $transaction = $this->transaction_model->getByReference($reference)){
                    if($transaction->aclstatus=='N' && empty($transaction->acltrxid)) {
                        if($this->transaction_model->storePayment($transaction->transid, $reference, array(
                            "acltrxid" => $trxid,
                            "acldescription" => 'Manually Paid By Admin',
                            "aclmethodnote" => $mobile,
                            "aclmanual" => '1',
                        ))) {
                            $key = $this->settings_model->get('bkrskey');
                            $defaultCurrency = $this->currency_model->getDefault(true);
                            $acl_transId = $transaction->transid;
                            $acl_sellingCurrencyAmount = number_format(currencyConvertFromBDT($transaction->aclbdtamount, $defaultCurrency->rate), aclCalPLen($transaction->sellingcurrencyamount), '.', '');
                            $acl_accountingCurrencyAmount = $acl_sellingCurrencyAmount;
                            $acl_status = 'Y';
                            $acl_rKey = generateRkey();
                            $acl_checksum = generateChecksum(array($acl_transId, $acl_sellingCurrencyAmount, $acl_accountingCurrencyAmount, $acl_status, $acl_rKey, $key));
                            $acl_parameters = generateURLParameter(array(
                                "transid" => $acl_transId,
                                "status" => $acl_status,
                                "rkey" => $acl_rKey,
                                "checksum" => $acl_checksum,
                                "sellingamount" => $acl_sellingCurrencyAmount,
                                "accountingamount" => $acl_accountingCurrencyAmount
                            ));
                            $acl_redirect = $transaction->redirecturl.'?'.$acl_parameters;
                            $this->load->library('curl');
                            $this->curl->ssl(false);
                            $this->curl->simple_get($acl_redirect);
                            $this->response['state'] = true;
                            $this->response['message'] = 'Transaction paid successfully';
                        } else {
                            $this->response['message'] = 'Transaction Payment Failed. Please Try Again Later';
                        }
                    } else {
                        $this->response['message'] = 'May Transaction already paid or cancelled.';
                    }
                } else {
                    $this->response['message'] = 'Transaction not found.';
                }
            } else {
                $this->response['message'] = 'Trxid already used.';
            }
        } else {
            $this->response['message'] = 'Trxid and Mobile Number is required';
        }
        $this->sendResponse();
    }

    private function __acl_pay_dynamic_manual(array $data) {
        $this->response['message'] = 'There is nothing to pay';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        if(!empty($reference)) {
            if( $transaction = $this->transaction_model->getByReference($reference)){
                if($transaction->aclstatus=='N' && $transaction->aclrequested=='1' && $gateway = $this->gateway_model->get($transaction->aclmethod) ) {
                    if($this->transaction_model->payDynamicPayment($transaction->transid, $reference, array())) {
                        $key = $gateway->resellbizkey;
                        $defaultCurrency = $this->currency_model->getDefault(true);
                        $acl_transId = $transaction->transid;
                        $acl_sellingCurrencyAmount = number_format(currencyConvertFromBDT($transaction->aclbdtamount, $defaultCurrency->rate), aclCalPLen($transaction->sellingcurrencyamount), '.', '');
                        $acl_accountingCurrencyAmount = $acl_sellingCurrencyAmount;
                        $acl_status = 'Y';
                        $acl_rKey = generateRkey();
                        $acl_checksum = generateChecksum(array($acl_transId, $acl_sellingCurrencyAmount, $acl_accountingCurrencyAmount, $acl_status, $acl_rKey, $key));
                        $acl_parameters = generateURLParameter(array(
                            "transid" => $acl_transId,
                            "status" => $acl_status,
                            "rkey" => $acl_rKey,
                            "checksum" => $acl_checksum,
                            "sellingamount" => $acl_sellingCurrencyAmount,
                            "accountingamount" => $acl_accountingCurrencyAmount
                        ));
                        $acl_redirect = $transaction->redirecturl.'?'.$acl_parameters;
                        $this->load->library('curl');
                        $this->curl->ssl(false);
                        $this->curl->simple_get($acl_redirect);
                        $this->response['state'] = true;
                        $this->response['message'] = 'Transaction paid successfully';
                    } else {
                        $this->response['message'] = 'Transaction Payment Failed. Please Try Again Later';
                    }
                } else {
                    $this->response['message'] = 'May Transaction already paid / cancelled / Not Pending.';
                }
            } else {
                $this->response['message'] = 'Transaction not found.';
            }
        } else {
            $this->response['message'] = 'Invalid transaction';
        }
        $this->sendResponse();
    }

    private function __acl_cancel_transaction(array $data){
        $this->response['message'] = 'There is nothing to cancel';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        if(!empty($reference)) {
            if( $transaction = $this->transaction_model->getByReference($reference)){
                if($transaction->aclstatus=='N') {
                    if($this->transaction_model->cancelTransaction($transaction->transid, $reference)) {
                        $this->response['state'] = true;
                        $this->response['message'] = 'Transaction cancelled successfully';
                    } else {
                        $this->response['message'] = 'Transaction not cancelled. Please try again later';
                    }
                } else {
                    $this->response['message'] = 'May Transaction already paid / cancelled ';
                }
            } else {
                $this->response['message'] = 'Transaction not found.';
            }
        } else {
            $this->response['message'] = 'Invalid Transaction';
        }
        $this->sendResponse();
    }

    private function __acl_rollback_transaction(array $data){
        $this->response['message'] = 'There is nothing to unpaid';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        if(!empty($reference)) {
            if( $transaction = $this->transaction_model->getByReference($reference)){
                if($transaction->aclstatus=='Y') {
                    if($this->transaction_model->rollBackTransaction($transaction->transid, $reference)) {
                        $this->response['state'] = true;
                        $this->response['message'] = 'Transaction unpaid successfully';
                    } else {
                        $this->response['message'] = 'Transaction cannot be unpaid. Please try again later';
                    }
                } else {
                    $this->response['message'] = 'May Transaction not paid / cancelled ';
                }
            } else {
                $this->response['message'] = 'Transaction not found.';
            }
        } else {
            $this->response['message'] = 'Invalid Transaction';
        }
        $this->sendResponse();
    }

    private function __acl_allowexpire_transaction(array $data){
        $this->response['message'] = 'There is no restriction to remove';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        if(!empty($reference)) {
            if( $transaction = $this->transaction_model->getByReference($reference)){
                if($transaction->aclstatus=='N' && $transaction->acldisableexpire=='0') {
                    if($this->transaction_model->allowExpireTransaction($transaction->transid, $reference)) {
                        $this->response['state'] = true;
                        $this->response['message'] = 'Transaction Expire restriction removed successfully';
                    } else {
                        $this->response['message'] = 'Transaction Expire restriction not removed. Please try again later';
                    }
                } else {
                    $this->response['message'] = 'May Transaction has no restriction or Paid / Cancelled';
                }
            } else {
                $this->response['message'] = 'Transaction not found.';
            }
        } else {
            $this->response['message'] = 'Invalid Transaction';
        }
        $this->sendResponse();
    }

    private function __acl_remove_transaction(array $data) {
        $this->response['message'] = 'There is nothing to remove';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        if(!empty($reference)) {
            if( $transaction = $this->transaction_model->getByReference($reference)){
                if($this->transaction_model->removeTransaction($transaction->transid, $reference)) {
                    $this->response['state'] = true;
                    $this->response['message'] = 'Transaction removed successfully';
                } else {
                    $this->response['message'] = 'Transaction not removed. Please try again later';
                }
            } else {
                $this->response['message'] = 'Transaction not found.';
            }
        } else {
            $this->response['message'] = 'Invalid Transaction';
        }
        $this->sendResponse();
    }

    private function __acl_generate_chart_data(array $data) {
        $this->response['message'] = 'Invalid Request';

        $type = array_key_exists('type', $data) ? $data['type'] : '';
        if(!empty($type)) {
            switch ($type) {
                case 'today':
                    $this->response['label'] = array();
                    $this->response['data'] = array();
                    if($this->transaction_model->generateTodaySummary( $this->response['label'],$this->response['data'] )) {
                        $this->response['state'] = true;
                        $this->response['message'] = "Ready to procced";
                    }
                    break;
                case 'month':
                    $this->response['label'] = array();
                    $this->response['data'] = array();
                    if($this->transaction_model->generateMonthSummary( $this->response['label'],$this->response['data'] )) {
                        $this->response['state'] = true;
                        $this->response['message'] = "Ready to procced";
                    }
                    break;
                case 'year':
                    $this->response['label'] = array();
                    $this->response['data'] = array();
                    if($this->transaction_model->generateYearSummary( $this->response['label'],$this->response['data'] )) {
                        $this->response['state'] = true;
                        $this->response['message'] = "Ready to procced";
                    }
                    break;
            }
        }
        $this->sendResponse();
    }

    private function __acl_review_transaction(array $data) {
        $this->response['message'] = 'There is nothing to remove';
        $reference = array_key_exists('reference', $data) ? $data['reference'] : '';
        if(!empty($reference)) {
            if( $transaction = $this->transaction_model->getByReference($reference)) {
                $this->response['state'] = true;
                $tags = array($this->aclDecodeStatus($transaction->aclstatus, $transaction->aclrequested, true));
                if ($transaction->acldisableexpire == '1' && $transaction->aclstatus != 'C') {
                    $tags[] = '<span class="badge bg-orange" data-toggle="tooltip" data-placement="bottom" title="There is no time restriction. Expired transaction is allowed">Unrestricted</span>';
                }

                if ($transaction->aclmanual == '1') {
                    $tags[] = '<span class="badge bg-blue-grey" data-toggle="tooltip" data-placement="bottom" title="Transaction paid manually">Manual</span>';
                }
                $gateway = $transaction->aclmethod != 'bkash' ? $this->gateway_model->get($transaction->aclmethod) : false;
                ob_start(); ?>
                <div class="row">
                    <div class="col-sm-7 col-xs-8 text-left">
                        <p>
                            <b>FROM</b><br><?php echo html_escape($transaction->name) ?>
                            <br>[ <?php echo ucwords(html_escape($transaction->usertype)) ?>
                            : <?php echo html_escape($transaction->userid) ?> ]<br>
                            <?php echo html_escape($transaction->emailAddr) ?><br>
                            Mob: <?php echo html_escape($transaction->telNo) ?><br>
                            Created: <?php echo strtoupper($this->aclGetDate($transaction->aclcreated, "j M Y, g:i a")) ?>
                        </p>
                    </div>
                    <div class="col-sm-5 col-xs-4 text-right">
                        <p>
                            <b>STATUS</b><br>
                            <?php
                            $i = 1;
                            $j = count($tags);
                            $k = 0;
                            foreach ($tags as $tag) {
                                echo $tag;
                                if ($i != $j) {
                                    if ($k == 1) {
                                        echo '<br>';
                                        $k = 0;
                                    } else {
                                        echo ' ';
                                        $k++;
                                    }
                                }
                                $i++;
                            }
                            ?>
                        </p>
                    </div>
                </div>
                <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                    <tr>
                        <th width="5%" class="text-center">SN</th>
                        <th width="35%" class="text-left">Item Description</th>
                        <th width="20%" class="text-left">Reference</th>
                        <th width="20%" class="text-right">Fund
                            (<?php echo strtoupper(html_escape($transaction->resellerCurrency)) ?>)
                        </th>
                        <th width="20%" class="text-right">Payable (BDT)</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td class="text-right">1.</td>
                        <td class="text-left"><?php echo html_escape($transaction->transid) ?></td>
                        <td class="text-left"><?php echo html_escape($transaction->aclreference) ?></td>
                        <td class="text-right"><?php echo html_escape(number_format($transaction->sellingcurrencyamount, '3', '.', '')) ?></td>
                        <td class="text-right"><?php echo html_escape(number_format($transaction->aclbdtamount, '3', '.', '')) ?></td>
                    </tr>
                    </tbody>
                    <tfoot>
                    <tr>
                        <th colspan="4" class="text-right">Sub Total :</th>
                        <th class="text-right"><?php echo html_escape(number_format($transaction->aclbdtamount, '3', '.', '')) ?></th>
                    </tr>
                    <tr>
                        <th colspan="4" class="text-right">Gateway Fee :</th>
                        <th class="text-right"><?php echo html_escape(number_format($transaction->aclgatewayfee, '3', '.', '')) ?></th>
                    </tr>
                    <tr>
                        <th colspan="4" class="text-right">Grand Total :</th>
                        <th class="text-right"><?php echo html_escape(number_format($transaction->aclgatewayfee + $transaction->aclbdtamount, '3', '.', '')) ?></th>
                    </tr>
                    </tfoot>
                </table>
                </div>
                <div style="padding: 5px 10px; border-bottom: 1px solid #ddd; background-color: #eaeaea; margin-bottom: 10px">
                    <b>PAYMENT DETAILS</b>
                </div>
                <?php if ($transaction->aclstatus == 'Y') : ?>
                <div class="row">
                    <div class="col-sm-6">
                    <p>
                        <b>Gateway:</b><br> <?php echo $transaction->aclmethod == 'bkash' ? 'bKash Merchant' : ($gateway ? $gateway->name : 'Unknown') ?>
                    </p>
                    </div>
                    <div class="col-sm-6 text-right">
                    <p>
                        <b>Paid:</b><br> <?php echo strtoupper($this->aclGetDate($transaction->aclpaid, "j M Y, g:i a")) ?>
                    </p>
                    </div>
                </div>
                <?php else: ?>
                <p>
                    <b>Gateway:</b><br> <?php echo $transaction->aclmethod == 'bkash' ? 'bKash Merchant' : ($gateway ? $gateway->name : 'Unknown') ?>
                </p>
                <?php endif; ?>

                <?php if ($transaction->aclstatus == 'Y' || $transaction->aclrequested == '1') : ?>
                    <?php if($transaction->aclmethod=='bkash') : ?>
                        <p>
                            <b>trxId:</b><br> <?php echo !empty($transaction->acltrxid) ? $transaction->acltrxid : 'N/A' ?>
                        </p>
                        <?php if($transaction->aclmanual=='0') : ?>
                            <p>
                                <b>Via:</b><br> <?php echo !empty($transaction->aclmethodnote) ? $this->aclDecodeBkashMethod($transaction->aclmethodnote) : 'N/A' ?>
                            </p>
                            <p>
                                <b>bKash Response:</b><br><?php echo !empty($transaction->acldescription) ? '<pre>' . str_replace(array('":', '",', '"'),array('": ','',''),aclPretifyJson($transaction->acldescription )). '</pre>' : 'N/A' ?>
                            </p>
                        <?php else : ?>
                            <p>
                                <b>Sender:</b><br> <?php echo !empty($transaction->aclmethodnote) ? $transaction->aclmethodnote : 'N/A' ?>
                            </p>
                            <p>
                                <b>Remarks:</b><br> <?php echo !empty($transaction->acldescription) ? $transaction->acldescription : 'N/A' ?>
                            </p>
                        <?php endif; ?>
                    <?php elseif ($gateway) :
                        $fields = @json_decode($gateway->fields, true);
                        $fieldsSort = explode(',', $gateway->fields_sort);
                        foreach ($fieldsSort as $fs) {
                            if(array_key_exists($fs, $fields)) {
                                if(array_key_exists("enable", $fields[$fs]) && $fields[$fs]["enable"]=="on") {
                                    $fields[$fs];
                                    switch ($fs) {
                                        case 'trxid': ?>
                                            <p>
                                                <b><?php echo html_escape($fields[$fs]['label']); ?></b> <br> <?php echo !empty($transaction->acltrxid) ? $transaction->acltrxid : 'N/A'?>
                                            </p>
                                        <?php break;
                                        case 'senderac': ?>
                                            <p>
                                                <b><?php echo html_escape($fields[$fs]['label']); ?></b> <br> <?php echo !empty($transaction->aclmethodnote) ? $transaction->aclmethodnote : 'N/A'?>
                                            </p>
                                        <?php break;
                                        case 'docupload': $expn = !empty($transaction->acldocupload) ? explode('/', $transaction->acldocupload) : array(); ?>
                                            <p>
                                                <b><?php echo html_escape($fields[$fs]['label']); ?></b> <br> <?php echo !empty($transaction->acldocupload) ? '<a href="'.base_url($transaction->acldocupload).'" target="_blank" data-toggle="tooltip" data-placement="bottom" title="Download">'.end($expn).'</a>' : 'N/A'?>
                                            </p>
                                        <?php break;
                                        case 'trxnote': ?>
                                            <p>
                                                <b><?php echo html_escape($fields[$fs]['label']); ?></b> <br> <?php echo !empty($transaction->acldescription) ? $transaction->acldescription : 'N/A'?>
                                            </p>
                                        <?php break;
                                    }
                                }
                            }
                        }
                    endif;
                endif;
                $this->response['message'] = ob_get_clean();
            } else {
                $this->response['message'] = 'Transaction not found.';
            }
        } else {
            $this->response['message'] = 'Invalid Transaction';
        }
        $this->sendResponse();
    }

    private function aclGetDate($date, $def = "Y-m-d H:i:s", $format = 'Y-m-d H:i:s')
    {
        $d = \DateTime::createFromFormat($format, $date);
        return $d->format($def);
    }

    private function aclDecodeBkashMethod($key) {
        $methods = array(
                "#mob_ussd" => "Mobile (USSD)",
                "#bkash_app" => "bKash App",
        );

        return array_key_exists($key, $methods) ? $methods[$key] : "Unknown";
    }

    private function aclDecodeStatus($state, $requested='0', $tag=false) {
        $status = array(
            "Y" => "Paid",
            "N" => "Unpaid",
            "C" => "Cancelled"
        );

        $tag = array(
            "Y" => "bg-green",
            "N" => "bg-red",
            "C" => "bg-grey"
        );

        return array_key_exists($state, $status) ? ( $state=='N' && $requested=='1' ? (
        $tag ? '<span class="badge bg-orange">Pending</span>': 'Pending'
        ) : (
        $tag ? '<span class="badge '.$tag[$state].'">'.$status[$state].'</span>': $status[$state] )
        ) : (
        $tag ? '<span class="badge bg-black">Unknown</span>': 'Unknown'
        );
    }


    private function sendResponse(){
        header('Content-Type: application/json');
        echo json_encode($this->response);
        exit;
    }
}