<?php

namespace App\Http\Controllers\Administrator;

use App\BankAgencyModel;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\User;
use App\Fun\Fun;
use Auth;
use DB;
use Gate;
use App\FundsRegisterModel;
use App\ItemModel;
use App\FundsTransactionModel;
use Illuminate\Support\Facades\Crypt;

use App\CategoryModel;
use App\ProjectModel;
use App\AccessoriesModel;
use App\BankAccountModel;
use App\JournalModel;
use DataTables;
use Session;
use Spatie\Permission\Models\Role;
use Hash;
use GuzzleHttp\Client;
use App\PositionModel;
use App\SearchModel;

class FundsTransactionController extends Controller
{
    function __construct()
    {
        // Register
        $this->middleware('permission:Wallet-Registration-Request-List', ['only' => ['account_funds_request']]);
        $this->middleware('permission:Wallet-Registration-Approve', ['only' => ['approve_funds_register', 'reject_funds_register']]);

        // Desposite
        $this->middleware('permission:Deposit-Fund-Request-List', ['only' => ['account_funds_requested_deposite']]);
        $this->middleware('permission:Deposit-Fund-Approve', ['only' => ['approve_funds_request_add', 'reject_funds_request_add']]);
        $this->middleware('permission:Request-Funds-Print', ['only' => ['funds_requested_deposite_print']]);

        // Withdraw
        $this->middleware('permission:Withdraw-Fund-Request-List', ['only' => ['request_withdraw_view']]);
        $this->middleware('permission:Withdraw-Fund-Approve', ['only' => ['withdraw_approve_pay', 'withdraw_reject']]);
        $this->middleware('permission:Withdraw-Fund-Request-Print', ['only' => ['request_withdraw_print']]);

        // History
        $this->middleware('permission:Fund-Transaction-Report', ['only' => ['history_fundstransation']]);
    }



    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    /**
     *  Show Request Deposit List
     */
    public function account_funds_requested_deposite(Request $request, $status = null)
    {
        Session::put('status', $status);
        return view('administrator.funds-transaction.request-deposit');
    }
    public function datatable_get_funds_request_add(Request $request)
    {
        $new_status = Session::get('status');

        $model_searching = new SearchModel();
        $search_date =  (empty($request->start_date)) ? '' : ' SUBSTRING(nso007_funds_transaction.request_date, 1, 10) BETWEEN "' . $request->start_date . '" AND "' . $request->end_date . '" ';
        $status = '';
        if ($request->action == 3) {
            $status = ' nso007_funds_transaction.status = 0 ';
        } else if ($request->action == 1 || $request->action == 2) {
            $status = ' nso007_funds_transaction.status = ' . $request->action;
        } else if ($request->action == 0) {
            $status = '';
        }

        $data_search = array(
            'requested_date' => $search_date,
            'status' => $status,
        );
        $search = $model_searching->search($data_search);
        $search = (empty($search) ? " WHERE nso007_funds_transaction.operation_type = 1 " : $search . " AND nso007_funds_transaction.operation_type = 1");

        if ($new_status  == 1) {

            $transac = DB::select("SELECT 
                                    nso007_funds_transaction.id,
                                    nso007_funds_transaction.request_date,
                                    nso007_funds_transaction.operation_type,
                                    nso007_funds_transaction.account_number,
                                    nso007_funds_transaction.amount,
                                    nso007_funds_transaction.reference,
                                    nso007_funds_transaction.status,
                                    nso007_funds_transaction.app_rej_date,
                                    nso007_funds.account_name
                                    FROM nso007_funds_transaction
                                    INNER JOIN nso007_funds ON nso007_funds_transaction.account_number = nso007_funds.account_number
                                    $search ");
        } else if ($new_status == 0) {
            $transac = DB::select("SELECT 
                                    nso007_funds_transaction.id,
                                    nso007_funds_transaction.request_date,
                                    nso007_funds_transaction.operation_type,
                                    nso007_funds_transaction.account_number,
                                    nso007_funds_transaction.amount,
                                    nso007_funds_transaction.reference,
                                    nso007_funds_transaction.status,
                                    nso007_funds_transaction.app_rej_date,
                                    nso007_funds.account_name
                                    FROM nso007_funds_transaction 
                                    INNER JOIN nso007_funds ON nso007_funds_transaction.account_number = nso007_funds.account_number
                                    WHERE nso007_funds_transaction.operation_type = 1 AND nso007_funds_transaction.status = 0");
        }
        return Datatables::of($transac)

            ->addIndexColumn()
            ->addColumn('status', function ($transac) {

                if ($transac->status == 1) {
                    if (Gate::check('Deposit-Fund-Approve')) {
                        return ' <strong class="text-success"><span class="fa fa-check"></span> Approved   / ' . $this->re_formatdate($transac->app_rej_date) . '</strong>
                        ';
                    }
                } elseif ($transac->status == 2) {
                    if (Gate::check('Deposit-Fund-Approve')) {
                        return ' <strong class="text-danger"><span class="fa fa-close"></span> Rejected   / ' . $this->re_formatdate($transac->app_rej_date) . '</strong>
                        ';
                    }
                } else {
                    $appro_re = '';
                    $edit_re = '';
                    $reject_re = '';
                    if (Gate::check('Deposit-Fund-Approve')) {
                        $appro_re = '<button class="viewPopLinkApprove btn btn-default btn-sm" type="button" data-toggle="modal tooltip" data-target="#popUpApprove" data-placement="top" data-id="' . $transac->id . '" data-amount="' . $transac->amount . '" data-to_account="' . $transac->account_number . '"><strong class=" text-primary"><span class="fa fa-check"></span> Approve</strong></button>
                            ';
                    }
                    if (Gate::check('Deposit-Fund-Edit')) {
                        $edit_re = '<button class="EditAmountFund btn btn-default btn-sm" type="button" data-toggle="modal tooltip" data-target="#popUpEditAmount" data-placement="top" data-id="' . $transac->id . '" data-amount="' . $transac->amount . '" data-to_account="' . $transac->account_number . '"><strong class=" text-primary"><span class="fa fa-edit"></span> Edit</strong></button>
                            ';
                    }
                    if (Gate::check('Deposit-Fund-Approve')) {
                        $reject_re = '<button class="viewPopLinkReject btn btn-default btn-sm" role="button" type="button" data-toggle="modal tooltip" data-target="#popUpReject" data-placement="top" data-id="' . $transac->id . '"><strong class=" text-danger"><span class="fa fa-close"></span> Reject</strong></button>';
                    }
                    return $appro_re . $edit_re . $reject_re;
                }
            })
            ->addColumn('request_date', function ($transac) {
                return $this->re_formatdate($transac->request_date);
            })
            ->addColumn('operation_type', function ($transac) {
                return 'Add Funds';
            })

            ->addColumn('amount', function ($transac) {
                return '$ ' . number_format($transac->amount, 2);
            })
            ->addColumn('account_number', function ($transac) {
                return $transac->account_name . ' (' . $transac->account_number . ')';
            })
            ->addColumn('reference', function ($transac) {
                return "
                <button class='viewPopLinkImage btn btn-default btn-sm' type='button' data-toggle='modal tooltip' data-target='#popUpImage' data-placement='top' data-img='" . $transac->reference . "'><strong class='text-info'>View</strong></button>
                ";
            })

            ->rawColumns([
                'status' => 'status',
                'reference' => 'reference',
            ])
            ->make(true);
    }

    public function funds_requested_deposite_print(Request $request)
    {
        $model_searching = new SearchModel();
        $search_date =  (empty($request->start_date)) ? '' : ' SUBSTRING(nso007_funds_transaction.request_date, 1, 10) BETWEEN "' . $request->start_date . '" AND "' . $request->end_date . '" ';
        $status = '';
        if ($request->action == 3) {
            $status = ' nso007_funds_transaction.status = 0 ';
        } else if ($request->action == 1 || $request->action == 2) {
            $status = ' nso007_funds_transaction.status = ' . $request->action;
        } else if ($request->action == 0) {
            $status = '';
        }

        $data_search = array(
            'requested_date' => $search_date,
            'status' => $status,
        );
        $search = $model_searching->search($data_search);
        $search = (empty($search) ? " WHERE nso007_funds_transaction.operation_type = 1 " : $search . " AND nso007_funds_transaction.operation_type = 1");
        $transac = DB::select("SELECT 
                                    nso007_funds_transaction.id,
                                    nso007_funds_transaction.request_date,
                                    nso007_funds_transaction.operation_type,
                                    nso007_funds_transaction.account_number,
                                    nso007_funds_transaction.amount,
                                    nso007_funds_transaction.reference,
                                    nso007_funds_transaction.status,
                                    nso007_funds_transaction.app_rej_date,
                                    nso007_funds.account_name
                                    FROM nso007_funds_transaction
                                    INNER JOIN nso007_funds ON nso007_funds_transaction.account_number = nso007_funds.account_number
                                    $search ");
        $total = 0;
        foreach ($transac as $key => $value) {
            $total += $value->amount;
        }
        return view('administrator.funds-transaction.request-deposit-print', compact('transac', 'total'));
    }


    public function withdraw_proccess_pay(Request $request)
    {
        $ids = $request->ids;

        FundsTransactionModel::whereIn('id', explode(",", $ids))->update(['status' => 1]);

        return response()->json(['status' => true, 'message' => "Category deleted successfully."]);
    }
    /**
     *  Get list request withdraw
     */

    public function request_withdraw_view(Request $request, $status = null)
    {
        Session::put('status', $status);
        $agencys = User::select(
            DB::raw('CONCAT(user_code," / ",user_firstname," ",user_lastname) AS name_mixed'),
            'id'
        )
            ->where('user_status', '=', 2)
            ->pluck('name_mixed', 'id')
            ->prepend('Please Select', '')
            ->toArray();
        return view('administrator.funds-transaction.request-withdraw', compact('agencys'));
    }
    public function datatable_get_funds_request_withdrawal(Request $request)
    {
        $new_status = Session::get('status');

        $model_searching = new SearchModel();
        $search_date =  (empty($request->form_date)) ? '' : ' SUBSTRING(nso007_funds_transaction.request_date, 1, 10) BETWEEN "' . $request->form_date . '" AND "' . $request->to_date . '" ';

        $status = '';
        if ($request->action == 4) {
            $status = ' nso007_funds_transaction.status = 0 ';
        } else if ($request->action == 1 || $request->action == 2 || $request->action == 3) {
            $status = ' nso007_funds_transaction.status = ' . $request->action . ' ';
        } else if ($request->action == 0) {
            $status = '';
        }

        $agency = (empty($request->agencys)) ? '' : ' users.id = "' . $request->agencys . '"';

        $data_search = array(
            'requested_date' => $search_date,
            'status' => $status,
            'agency' => $agency,
        );
        $search = $model_searching->search($data_search);
        $search =  (empty($search)) ? ' WHERE nso007_funds_transaction.operation_type = 6 ' : $search . ' AND nso007_funds_transaction.operation_type = 6';

        if ($new_status  == 1) {
            $transac = DB::select("SELECT 
                               nso007_funds_transaction.id,
                               nso007_funds_transaction.operation_type,
                               nso007_funds_transaction.balance,
                               nso007_funds_transaction.request_date,
                               IFNULL(nso007_funds_transaction.app_rej_date,'N/A') as app_rej_date,
                               nso007_funds_transaction.account_number,
                               nso007_funds.account_name,
                               nso007_funds_transaction.amount,
                               nso007_funds_transaction.bank_account,
                               nso007_funds_transaction.bank_id,
                               nso007_funds_transaction.confirm_withdraw,
                               IFNULL(nso007_funds_transaction.remark,'N/A') as remark,
                               nso007_funds_transaction.status,
                               users.user_phone AS phone,
                               nso007_funds_transaction.done_date,
                               nso007_bank_agency.name as bank_name,
                               nso007_funds_transaction.bank_account_name,
                               nso007_funds_transaction.bank_account_number
                               
                               FROM nso007_funds_transaction 
                               INNER JOIN nso007_funds ON nso007_funds.account_number = nso007_funds_transaction.account_number
                               INNER JOIN users ON users.id = nso007_funds_transaction.user_log
                               LEFT JOIN nso007_bank_agency on nso007_bank_agency.id = nso007_funds_transaction.bank_id 
                               $search
							   order by id asc
							   ");
        } else if ($new_status == 0) {
            $transac = DB::select("SELECT 
                               nso007_funds_transaction.id,
                               nso007_funds_transaction.operation_type,
                               nso007_funds_transaction.balance,
                               nso007_funds_transaction.request_date,
                               nso007_funds_transaction.app_rej_date,
                               nso007_funds_transaction.account_number,
                               nso007_funds.account_name,
                               nso007_funds_transaction.amount,
                               nso007_funds_transaction.bank_account,
                               nso007_funds_transaction.confirm_withdraw,
                               nso007_funds_transaction.remark,
                               nso007_funds_transaction.bank_id,
                               nso007_funds_transaction.status,
                               nso007_funds_transaction.done_date,
                               nso007_bank_agency.name as bank_name,
                               users.user_phone AS phone,
                               nso007_funds_transaction.bank_account_name,
                               nso007_funds_transaction.bank_account_number
                               FROM nso007_funds_transaction 
                               INNER JOIN nso007_funds ON nso007_funds.account_number = nso007_funds_transaction.account_number
                               INNER JOIN users ON users.id = nso007_funds_transaction.user_log
                               LEFT JOIN nso007_bank_agency on nso007_bank_agency.id = nso007_funds_transaction.bank_id 
                               where nso007_funds_transaction.operation_type = 6 and nso007_funds_transaction.status = 0
							   order by id asc");
        }
        return Datatables::of($transac)
            ->addIndexColumn()
            ->addColumn('status', function ($transac) {
                if ($transac->status == 1) {
                    return ' <strong class="text-success"><span class="fa fa-check"></span> Done  / ' . $this->re_formatdate($transac->done_date) . '</strong>';
                } elseif ($transac->status == 2) {
                    return ' <strong class="text-danger"><span class="fa fa-close"></span> Rejected</strong>';
                } elseif ($transac->status == 3) {
                    return '<strong class="text-primary"><span class="fa fa-spinner"></span> Proccessing</strong>';
                } else {
                    $appro_w = '';
                    $reject_w = '';
                    if (Gate::check('Withdraw-Fund-Approve')) {
                        $appro_w = '<button class="viewPopLinkApprove btn btn-default btn-sm" type="button" data-toggle="modal tooltip" data-target="#popUpApprove" data-placement="top" data-id="' . $transac->id . '" data-amount="' . $transac->amount . '"><strong class=" text-primary"><span class="fa fa-check"></span> Approve</strong></button>
                            ';
                        $reject_w = '<button class="viewPopLinkReject btn btn-default btn-sm" type="button" data-toggle="modal tooltip" data-target="#popUpReject" data-placement="top" data-id="' . $transac->id . '" data-amount="' . $transac->amount . '" data-account_number="' . $transac->account_number . '"><strong class="text-danger"><span class="fa fa-close"></span> Reject</strong></button>
                            ';
                    }
                    return $appro_w . $reject_w;
                }
            })

            ->addColumn('request_date', function ($transac) {
                return $this->re_formatdate($transac->request_date);
            })
            ->addColumn('phone', function ($transac) {
                return '<a href="tel:' . $transac->phone . '">' . $transac->phone . '</a>';
            })
            ->addColumn('app_rej_date', function ($transac) {
                return ($transac->app_rej_date == 'N/A') ? 'N/A' :  $this->re_formatdate($transac->app_rej_date);
            })
            ->editColumn('operation_type', 'Withdraw Funds')
            ->addColumn('amount', function ($transac) {
                return '$ ' . number_format($transac->amount, 2);
            })
            ->addColumn('confirm_withdraw', function ($transac) {
                return '$ ' . number_format($transac->confirm_withdraw, 2);
            })
            ->addColumn('account_funds', function ($transac) {
                return $transac->account_name . " (" . $transac->account_number . ")";
            })
            ->addColumn('bank_account_info', function ($transac) {
                $account = BankAccountModel::where([['bank_id', $transac->bank_id], ['account_number', $transac->bank_account]])->first();
                return empty($transac->bank_name) ? "" : $transac->bank_name . ': <span class="text-bold text-info">' . $transac->bank_account_number . '</span>';
            })
            ->rawColumns(['status' => 'status', 'phone' => 'phone', 'bank_account_info' => 'bank_account_info'])
            ->make(true);
    }
    public function re_formatdate($datetime)
    {
        $date = substr($datetime, 0, 10);
        $date = date('d-m-Y', strtotime($date));
        $time = substr($datetime, 10);
        return $date . $time;
    }
    public function request_withdraw_print(Request $request)
    {
        $model_searching = new SearchModel();
        $search_date =  (empty($request->form_date)) ? '' : ' SUBSTRING(nso007_funds_transaction.request_date, 1, 10) BETWEEN "' . $request->form_date . '" AND "' . $request->to_date . '" ';

        $status = '';
        if ($request->action == 4) {
            $status = ' nso007_funds_transaction.status = 0 ';
        } else if ($request->action == 1 || $request->action == 2 || $request->action == 3) {
            $status = ' nso007_funds_transaction.status = ' . $request->action . ' ';
        } else if ($request->action == 0) {
            $status = '';
        }

        $agency = (empty($request->agencys)) ? '' : ' users.id = "' . $request->agencys . '"';

        $data_search = array(
            'requested_date' => $search_date,
            'status' => $status,
            'agency' => $agency,
        );
        $search = $model_searching->search($data_search);
        $search =  (empty($search)) ? ' WHERE nso007_funds_transaction.operation_type = 6 ' : $search . ' AND nso007_funds_transaction.operation_type = 6';
        $transac = DB::select("SELECT 
                               nso007_funds_transaction.id,
                               nso007_funds_transaction.operation_type,
                               nso007_funds_transaction.balance,
                               nso007_funds_transaction.request_date,
                               IFNULL(nso007_funds_transaction.app_rej_date,'N/A') as app_rej_date,
                               nso007_funds_transaction.account_number,
                               nso007_funds.account_name,
                               nso007_funds_transaction.amount,
                               IFNULL(nso007_funds_transaction.remark,'N/A') as remark,
                               nso007_funds_transaction.status,
                               users.user_phone AS phone,
                               nso007_funds_transaction.done_date,
                               nso007_bank.name as bank_name,
                               nso007_funds_transaction.bank_account_name,
                               nso007_funds_transaction.bank_account_number
                               
                               FROM nso007_funds_transaction 
                               INNER JOIN nso007_funds ON nso007_funds.account_number = nso007_funds_transaction.account_number
                               INNER JOIN users ON users.id = nso007_funds_transaction.user_log
                               LEFT JOIN nso007_bank on nso007_bank.id = nso007_funds_transaction.bank_id 
                               $search
                               order by id asc
                               ");
        $total = 0;
        foreach ($transac as $key => $value) {
            $total += $value->amount;
        }
        return view('administrator.funds-transaction.request-withdraw-print', compact('transac', 'total'));
    }

    public function withdraw_approve_pay(Request $request)
    {
        $funds_tran = FundsTransactionModel::find($request->id);
        $funds_account = $funds_tran->account_number;
        $funds_balance = $funds_tran->balance;
        $tranction_code = $funds_tran->transaction_code;

        $data = DB::table('nso007_funds')->where('account_number', $funds_account)->get();
        $balance = $data[0]->balance;
        $total_amount_pay = $request->amount - $request->amount_pay;

        if ($request->amount_pay != "" and $request->amount >= $request->amount_pay) {
            if ($request->amount == $request->amount_pay) {
                DB::table('nso007_funds_transaction')
                    ->where('id', $request->id)
                    ->update([
                        'amount' => $request->amount_pay,
                        'confirm_withdraw' => $request->amount_pay,
                        'remark' => "Amount Confirm " . number_format($request->amount_pay, 2) . " USD (" . $request->remark . ")",
                        'status' => 3,
                        'app_rej_date' => date('Y-m-d H:i:s A'),
                    ]);
            } else {
                DB::table('nso007_funds')->where('account_number', $funds_account)->increment('balance', $total_amount_pay);
                DB::table('nso007_funds_transaction')
                    ->where('id', $request->id)
                    ->update([
                        'confirm_withdraw' => $request->amount_pay,
                        'remark' => "Amount Confirm " . number_format($request->amount_pay, 2) . " USD (" . $request->remark . ")",
                        'status' => 3,
                        'app_rej_date' => date('Y-m-d H:i:s A'),
                    ]);
                // MENGHORT

                $balance = FundsRegisterModel::where('account_number', $funds_account)->first()->balance;
                $refund = new FundsTransactionModel;
                $refund->operation_type    = 7;
                $refund->account_number    = $funds_account;
                $refund->amount            = $total_amount_pay;
                $refund->balance           = $balance;
                $refund->transaction_code           = $tranction_code;
                $refund->request_date      = date('Y-m-d H:i:s A');
                $refund->remark            = number_format($total_amount_pay, 2) . " USD was refund to your account" . ' ' . $request->remark;
                $refund->user_log          = Auth::user()->id;
                $refund->status            = 1;
                $refund->save();
            }
            \LogActivity::addToLog('Approved successfully!');
            return back()->with('success', 'You have approved successfully!');
        } else {
            \LogActivity::addToLog('Plase Enter Amount Befor Approve !');
            return back()->with('danger', 'Wrong Information');
        }

        return back();
    }

    public function withdraw_reject(Request $request)
    {
        $id = $request->id;
        $funds_tran = FundsTransactionModel::find($id);
        $tranction_code = $funds_tran->transaction_code;
        $amount = $request->amount;
        $account_number = $request->account_number;
        if ($request->remark == '') {
            FundsTransactionModel::where('id', $id)->update([
                'status' => 2,
                'remark' => 'Withdraw Funds Rejected',
                'app_rej_date' => date('Y-m-d H:i:s A'),
            ]);
            DB::table('nso007_funds')->where('account_number', $account_number)->increment('balance', $amount);
        } else {
            FundsTransactionModel::where('id', $id)->update([
                'status' => 2,
                'remark' => $request->remark,
                'app_rej_date' => date('Y-m-d H:i:s A'),
            ]);
            DB::table('nso007_funds')->where('account_number', $account_number)->increment('balance', $amount);
        }
        $balance = FundsRegisterModel::where('account_number', $account_number)->first()->balance;
        $refund = new FundsTransactionModel;
        $refund->operation_type    = 7;
        $refund->account_number    = $account_number;
        $refund->amount            = $amount;
        $refund->balance           = $balance;
        $refund->transaction_code    = $tranction_code;
        $refund->request_date      = date('Y-m-d H:i:s A');
        $refund->app_rej_date      = date('Y-m-d H:i:s A');
        $refund->remark            = number_format($amount, 2) . " USD was refund to your account" . ' ' . $request->remark;
        $refund->user_log          = Auth::user()->id;
        $refund->status            = 1;
        $refund->save();

        return back();
    }

    /**
     *
     *  Approve _funds_request_add
     *
     */
    public function approve_funds_request_add($id, $amount, $to_account, Request $request)
    {
        $con = 0;
        $remark = "";
        if (isset($_POST['con'])) $con = $_POST['con'];
        if (empty($con)) $con = 0;
        if ($con == 1) {
            $request->validate([
                'amount' => 'required|numeric'
            ]);
            $amount = $_POST['amount'];
            $remark = $request->input("remark");
        }
        $data = FundsTransactionModel::find($id);
        $cash_flow_type = ($data->add_funds_bank == 1) ? 10000 : 10001;
        $invoice = 'ADDFUNDS-' . str_pad($id, 6, "0", STR_PAD_LEFT);

        DB::table('nso007_funds')->where('account_number', $to_account)->increment('balance', $amount);
        DB::table('nso007_funds')->where('account_number', $to_account)->increment('received​_balance', $amount);
        $funds = DB::table('nso007_funds')->where('account_number', $to_account)->select('user_id')->get();
        $user_branch = (empty($funds[0]->user_id) ? null : $funds[0]->user_id);
        $branch_id   = User::select('branch_id')->find($user_branch);
        $get_balance = FundsRegisterModel::select('balance')
            ->where('account_number', $to_account)
            ->get();

        $add_funds = FundsTransactionModel::find($id);
        $add_funds->status = 1;
        $add_funds->app_rej_date    = date('Y-m-d H:i:s A');
        $add_funds->remark          = "You was deposited. " . $remark;
        $add_funds->balance = $get_balance[0]->balance;
        $add_funds->amount = $amount;
        $add_funds->update();

        $jounal = new JournalModel;
        $jounal1 = new JournalModel;

        $jounal->journal_parentid    = 0;
        $jounal->branch_id           = $branch_id->branch_id;
        $jounal->journal_type        = 30;
        $jounal->journal_acccode     = 30001;
        $jounal->journal_des         = 'Add fund to account ' . $to_account;
        $jounal->journal_credit      = $amount;
        $jounal->journal_currency    = 1;
        $jounal->journal_by          = Auth::user()->id;
        $jounal->journal_paydate     = date('Y-m-d');
        $jounal->pay_to              = $data->add_funds_bank;
        $jounal->journal_invoice     = $invoice;
        $jounal->save();

        $max_jounal_id = DB::table('nso007_journal')->max('id');

        $jounal1->journal_parentid    = $max_jounal_id;
        $jounal1->branch_id           = $branch_id->branch_id;
        $jounal1->journal_type        = 30;
        $jounal1->journal_acccode     = $cash_flow_type;
        $jounal1->journal_des         = 'Add fund to account ' . $to_account;
        $jounal1->journal_debit       = $amount;
        $jounal1->journal_currency    = 1;
        $jounal1->journal_by          = Auth::user()->id;
        $jounal1->journal_paydate     = date('Y-m-d');
        $jounal1->pay_to              = $data->add_funds_bank;
        $jounal1->journal_invoice     = $invoice;
        $jounal1->save();

        \LogActivity::addToLog('You have approved fund successfully !');
        return back()
            ->with('success', 'You have approved successfully!');
    }
    /**
     *
     *  Reject _funds_request_add
     *
     */
    public function reject_funds_request_add($id)
    {
        FundsTransactionModel::where('id', $id)->update(['status' => 2, 'app_rej_date' => date('Y-m-d H:i:s A')]);
        \LogActivity::addToLog('You have rejected successfully!');
        return back()
            ->with('success', 'You have rejected successfully!');
    }

    /**
     *
     *  Get account funds requested
     *
     */

    public function account_funds_request(Request $request, $status = null)
    {

        Session::put('status', $status);
        return view('administrator.funds-transaction.register-funds');
    }

    public function datatable_get_funds_request_account(Request $request)
    {

        $new_status = Session::get('status');
        if ($new_status  == 1) {
            $acc_funds = FundsRegisterModel::with(['get_agency'])->get();
        } else if ($new_status == 0) {
            $acc_funds = FundsRegisterModel::with(['get_agency'])
                ->where('status', 0)
                ->get();
        }


        return Datatables::of($acc_funds)
            ->addIndexColumn()
            ->addColumn('status', function ($acc_funds) {

                if ($acc_funds->status == 0) {
                    if (Gate::check('Wallet-Registration-Approve')) {
                        return '
                        <a href="#" class="viewPopUpApprove btn btn-default btn-sm" role="button" data-toggle="modal tooltip" data-target="#popUpApprove" data-placement="top" data-id="' . $acc_funds->id . '"><strong class="text-info"><span class="fa fa-check"></span> Approve </strong></a>
                        <a href="#" class="viewPopUpReject btn btn-default btn-sm" role="button" data-toggle="modal tooltip" data-target="#popUpReject" data-placement="top" data-id="' . $acc_funds->id . '"><strong class="text-danger"><span class="fa fa-close"></span> Reject</strong></a>
                        ';
                    }
                } elseif ($acc_funds->status == 1) {
                    if (Gate::check('Wallet-Registration-Approve'))
                        return ' 
                        <a href="#" class="viewPopUpReject" role="button" data-toggle="modal tooltip" data-target="#popUpReject" data-placement="top" data-id="' . $acc_funds->id . '"><strong class="text-info"><span class="fa fa-check"></span> Activated   / ' . $this->re_formatdate($acc_funds->reject_approve_date) . '</strong></a>
                        ';
                    else return '<a href="#" role="button"><strong class="text-info"><span class="fa fa-check"></span> Activated   / ' . $this->re_formatdate($acc_funds->reject_approve_date) . '</strong></a>';
                } elseif ($acc_funds->status == 2) {
                    if (Gate::check('Wallet-Registration-Approve'))
                        return '<a href="#" class="viewPopUpApprove" role="button" data-toggle="modal tooltip" data-target="#popUpApprove" data-placement="top" data-id="' . $acc_funds->id . '"><strong class="text-danger"><span class="fa fa-check"></span> Deactivated   / ' . $this->re_formatdate($acc_funds->reject_approve_date) . '</strong></a>';
                    else return '<a href="#"><strong class="text-danger"><span class="fa fa-check"></span> Deactivated   / ' . $this->re_formatdate($acc_funds->reject_approve_date) . '</strong></a>';
                }
            })

            ->addColumn('fullname', function ($acc_funds) {
                return $acc_funds['get_agency']->user_firstname . " " . $acc_funds['get_agency']->user_lastname;
            })
            ->addColumn('user_code', function ($acc_funds) {
                return $acc_funds['get_agency']->user_code;
            })
            ->addColumn('check_id', function ($transac) {
                return '    <label class="checkbox-list">
                                                    <input type="checkbox" class="checkbox" data-id="' . $transac->id . '">
                                                    <span class="checkmark"></span></label>';
            })
            ->addColumn('created_at', function ($acc_funds) {
                return $this->re_formatdate($acc_funds->request_date);
            })


            ->rawColumns(['status' => 'status', 'fullname' => 'fullname', 'user_code' => 'user_code', 'check_id' => 'check_id'])
            ->make(true);
    }
    /**
     *
     *  Approve Funds Register
     *
     */
    public function approve_funds_register($id)
    {
        $funds_regis = FundsRegisterModel::find($id);
        $funds_regis->status = 1;
        $funds_regis->reject_approve_date = date('Y-m-d H:i:s A');
        $funds_regis->update();
        \LogActivity::addToLog('You have approved successfully!');
        return back()
            ->with('success', 'You have approved successfully!');
    }
    /**
     *
     *  Reject Funds Register
     *
     */
    public function reject_funds_register($id)
    {
        $funds_regis = FundsRegisterModel::find($id);
        $funds_regis->status = 2;
        $funds_regis->reject_approve_date = date('Y-m-d H:i:s A');
        $funds_regis->update();
        \LogActivity::addToLog('You have rejected successfully!');
        return back()
            ->with('success', 'You have rejected successfully!');
    }
    public function AgencyFundAccount($id)
    {
        $AccountInfo = FundsRegisterModel::where('user_id', $id)->first();
        $bank_account = BankAccountModel::select(DB::raw('group_concat(bank_id) as bank'))->where('agency_id', $id)->first();
        $bank_list = BankAgencyModel::whereIn('id', explode(',', $bank_account->bank))->select('name', 'id')->get();
        $data = array('bank_list' => $bank_list, 'acc_info' => $AccountInfo);
        return response()->json($data);
    }
    public function history_fundstransation()
    {
        $agencys = User::select(
            DB::raw('CONCAT(user_code," / ",user_firstname," ",user_lastname) AS name_mixed'),
            'id'
        )
            ->where('user_status', '=', 2)
            ->pluck('name_mixed', 'id')
            ->prepend('Please Select', '')
            ->toArray();
        return view('administrator.funds-transaction.history-funds', compact('agencys'));
    }
    public function datatable_get_history_funds(Request $request)
    {
        $status     = $request->status;
        $start_date = !empty($request->start_date)?date('Y-m-d',strtotime($request->start_date)):'';
        $end_date   = !empty($request->end_date)?date('Y-m-d',strtotime($request->end_date)):'';
        $agency_id  = $request->agency_id;

        $history = DB::table('nso007_funds_transaction as ftr')
            ->join('nso007_funds as f', 'f.account_number', 'ftr.account_number')
            ->join('users', 'users.id', 'f.user_id')
            ->leftjoin('nso007_bank_agency as b', 'b.id', 'ftr.bank_id')
            ->select(
                'ftr.id',
                'ftr.operation_type',
                'ftr.balance',
                'ftr.request_date',
                'ftr.app_rej_date',
                'ftr.account_number',
                'f.account_name',
                'ftr.amount',
                'ftr.remark',
                'bank_account',
                'ftr.status',
                'ftr.done_date',
                'users.user_phone AS phone',
                'ftr.bank_account_name',
                'ftr.bank_account_number'
            )
            ->when($status,function($q,$status){
                $q->where('ftr.status',$status);
            })
            ->when($agency_id,function($q,$agency_id){
                $q->where('users.id',$agency_id);
            })
            ->when(!empty($start_date) || !empty($end_date),function($q) use($start_date,$end_date){
                if(!empty($start_date) && !empty($end_date)){
                    $q->whereBetween(DB::raw("(STR_TO_DATE(ftr.request_date,'%Y-%m-%d'))"),[$start_date,$end_date]);
                }elseif(!empty($start_date) && empty($end_date)){
                    $q->where(DB::raw("(STR_TO_DATE(ftr.request_date,'%Y-%m-%d'))"),'>=',$start_date);
                }else{
                    $q->where(DB::raw("(STR_TO_DATE(ftr.request_date,'%Y-%m-%d'))"),'<=',$end_date);
                }
            })
            ->orderBy('ftr.id', 'ASC')
            ->get();
        return Datatables::of($history)
            ->addIndexColumn()
            ->addColumn('transation', function ($history) {
                $transation = '';
                if ($history->operation_type == 1) {
                    $transation = 'Add Funds';
                } elseif ($history->operation_type == 2) {
                    $transation = 'Payment';
                } elseif ($history->operation_type == 3) {
                    $transation = 'Commission';
                } elseif ($history->operation_type == 4) {
                    $transation = 'Send Funds';
                } elseif ($history->operation_type == 5) {
                    $transation = 'Received Funds';
                } elseif ($history->operation_type == 6) {
                    $transation = 'Withdraw Funds';
                } elseif ($history->operation_type == 7) {
                    $transation = 'Refund';
                } elseif ($history->operation_type == 8) {
                    $transation = 'Booking';
                }
                return $transation;
            })
            ->addColumn('amount', function ($history) {
                return '$' . number_format($history->amount, 2);
            })
            ->addColumn('credit', function ($data) {
                if (($data->operation_type % 2) !== 0) {
                    return "$ " . number_format($data->amount, 2);
                }
            })
            ->addColumn('debit', function ($data) {
                if (($data->operation_type % 2) == 0) {
                    return "$ " . number_format($data->amount, 2);
                }
            })
            ->addColumn('request_date', function ($history) {
                return $this->re_formatdate($history->request_date);
            })
            ->addColumn('status', function ($history) {
                $status = '';
                if ($history->status == 0) {
                    $status = '<strong class="text-warning"><span class="fa fa-check"></span> Pending</strong>';
                } elseif ($history->status == 2) {
                    $status = '<strong class="text-danger"><span class="fa fa-check"></span> Reject / ' . $this->re_formatdate($history->app_rej_date) . '</strong>';
                } elseif ($history->status == 3) {
                    $status = '<strong class="text-info"><span class="fa fa-spinner"></span> Processing</strong>';
                } else {
                    if ($history->operation_type == 7) {
                        $status = '<strong class="text-dank"><span class="fa fa-check"></span> Refund / ' . $this->re_formatdate($history->app_rej_date) . '</strong>';
                    } else {
                        $status = '<strong class="text-success"><span class="fa fa-check"></span> Done​ / ' . $this->re_formatdate($history->app_rej_date) . '</strong>';
                    }
                    if ($history->operation_type == 6) {
                        $status = '<strong class="text-success"><span class="fa fa-check"></span> Done​ / ' . $this->re_formatdate($history->done_date) . '</strong>';
                    } else {
                        $status = '<strong class="text-success"><span class="fa fa-check"></span> Done​ / ' . $this->re_formatdate($history->app_rej_date) . '</strong>';
                    }
                }
                return $status;
            })
            ->addColumn('account_funds', function ($history) {
                if (($history->operation_type % 2) !== 0) {
                    return $history->account_name . " (" . $history->account_number . ")";
                } elseif (($history->operation_type % 2) == 0) {
                    return $history->account_name . " (" . $history->account_number . ")";
                }
            })
            ->addColumn('app_rej_date', function ($history) {
                return ($history->app_rej_date == "") ? 'N/A' : $this->re_formatdate($history->app_rej_date);
            })
            ->addColumn('phone', function ($history) {
                return '<a href="tel:' . $history->phone . '">' . $history->phone . '</a>';
            })
            ->addColumn('bank_account_info', function ($transac) {
                return empty($transac->bank_name) ? "N/A" : $transac->bank_name . " (" . $transac->bank_account . ")";
            })
            ->rawColumns(['status' => 'status', 'transation' => 'transation', 'updated_at' => 'updated_at', 'phone' => 'phone'])
            ->make(true);
    }
    public function history_funds_print(Request $request)
    {
        $model_searching = new SearchModel();
        $search_date =  (empty($request->form_date)) ? '' : ' SUBSTRING(nso007_funds_transaction.request_date, 1, 10) BETWEEN "' . $request->form_date . '" AND "' . $request->to_date . '" ';

        $status = '';
        if ($request->action == 4) {
            $status = ' nso007_funds_transaction.status = 0 ';
        } else if ($request->action == 1 || $request->action == 2 || $request->action == 3) {
            $status = ' nso007_funds_transaction.status = ' . $request->action . ' ';
        } else if ($request->action == 0) {
            $status = '';
        }

        $agency = (empty($request->agencys)) ? '' : ' users.id = "' . $request->agencys . '"';

        $data_search = array(
            'requested_date' => $search_date,
            'status' => $status,
            'agency' => $agency,
        );
        $search = $model_searching->search($data_search);
        $search =  (empty($search)) ? ' ' : $search;
        $history = DB::select("SELECT 
                               nso007_funds_transaction.id,
                               nso007_funds_transaction.operation_type,
                               nso007_funds_transaction.balance,
                               nso007_funds_transaction.request_date,
                               nso007_funds_transaction.app_rej_date,
                               nso007_funds_transaction.account_number,
                               nso007_funds.account_name,
                               nso007_funds_transaction.amount,
                               nso007_funds_transaction.remark,
                               nso007_funds_transaction.status,
                               nso007_funds_transaction.done_date,
                               users.user_phone AS phone,
                               nso007_bank.name as bank_name,
                               nso007_funds_transaction.bank_account_name,
                               nso007_funds_transaction.bank_account_number
                               FROM nso007_funds_transaction 
                               INNER JOIN nso007_funds ON nso007_funds.account_number = nso007_funds_transaction.account_number
                               INNER JOIN users ON users.id = nso007_funds.user_id
                               LEFT JOIN nso007_bank ON nso007_bank.id = nso007_funds_transaction.bank_id
							   $search
							   ORDER BY id ASC
                               ");
        $total = 0;
        foreach ($history as $key => $value) {
            $total += $value->amount;
        }
        return view('administrator.funds-transaction.history-funds-print', compact('history', 'total'));
    }
    public function addFundManually(Request $request)
    {
        $this->validate($request, [
            'accountname'       => 'required',
            'accountnumber'     => 'required',
            'amount'            => 'required',
            'accountid'         => 'required'
        ]);
        $account = FundsRegisterModel::find($request->accountid);
        if ($account && $account->status == 1) {
            FundsTransactionModel::insert([
                'transaction_code'      =>  date('YmdHis'),
                'add_funds_bank'        =>  null,
                'bank_account_name'     =>  null,
                'bank_account_number'   =>  null,
                'operation_type'        =>  1,
                'account_number'        =>  $request->accountnumber,
                'amount'                =>  $request->amount,
                'balance'               =>  $account->balance,
                'remark'                =>  $request->remark,
                'user_log'              =>  Auth::user()->id,
                'status'                =>  0,
                // 'app_rej_date'          => date('Y-m-d H:i:s A'),
                'request_date'          => date('Y-m-d H:i:s A')
            ]);
            \LogActivity::addToLog('Funds Successfully Deposited by Admin Manually!');
            $response = ['success' => true, 'msg' => 'Account Successfully Added Funds'];
        } else {
            $response = ['success' => false, 'msg' => 'Account not found or not activated yet'];
        }
        return response()->json($response);
    }
    public function withdrawMannually(Request $request)
    {
        $this->validate($request, [
            'accountname'       => 'required',
            'accountnumber'     => 'required',
            'amount'            => 'required',
            'accountid'         => 'required',
            'bank_id'           => 'required',
        ]);
        $Account        =   FundsRegisterModel::find($request->accountid);
        $bankaccount    = BankAccountModel::where([['bank_id', $request->bank_id], ['agency_id', $Account->user_id]])->first();
        if ($Account && $Account->status == 1 && $bankaccount) {
            if ($Account->balance >= $request->amount) {
                try {
                    DB::beginTransaction();
                    FundsTransactionModel::insert([
                        'transaction_code'      => 'TS-' . date('YmdHis'),
                        'bank_id'               => $request->bank_id,
                        'bank_account_name'     => $bankaccount->account_name,
                        'bank_account_number'   => $bankaccount->account_number,
                        'operation_type'        => 6,
                        'account_number'        => $request->accountnumber,
                        'amount'                => $request->amount,
                        'balance'               => $Account->balance,
                        'remark'                => $request->remark,
                        'user_log'              => Auth::user()->id,
                        'request_date'          => date('d-m-Y H:i:s A'),
                        'status'                => 0,
                        'request_date'          => date('Y-m-d H:i:s A')
                    ]);
                    DB::commit();
                    \LogActivity::addToLog('Funds Successfully Requested To Withdraw by Admin Manually!');
                    $response = ['success' => true, 'msg' => 'Funds Successfully Requested To Withdraw'];
                } catch (\Exception $ex) {
                    DB::rollback();
                    $response = ['success' => false, 'msg' => $ex->getMessage()];
                }
            } else {
                $response = ['success' => false, 'msg' => 'Please Check Your Balance'];
            }
        } else {
            $response = ['success' => false, 'msg' => 'Account is not activated yet'];
        }
        return response()->json($response);
    }
    public function query_accountNumber(Request $request)
    {
        $search = $request->value;
        $accounts = FundsRegisterModel::when($request->value, function ($q) use ($search) {
            $q->orwhere('account_name', 'LIKE', "%$search%");
            $q->orwhere('account_number', 'LIKE', "%$search%");
        })->get();
        echo json_encode($accounts);
    }
    function sendfund(Request $request)
    {
        $this->validate($request, [
            'accountid'     => 'required',
            'accountname'   => 'required',
            'accountnumber' => 'required',
            'amount'        => 'required',
            'to_number'     => 'required',
            'to_name'       => 'required'
        ]);
        try {
            $sender         = FundsRegisterModel::find($request->accountid);
            $receiver       = FundsRegisterModel::where('account_number', $request->to_number)->first();
            if (($sender && $sender->status == 1) && ($receiver && $receiver->status == 1) && ($sender->balance >= $request->amount)) {
                FundsRegisterModel::where('id', $request->accountid)
                    ->update([
                        'balance'   => DB::raw("balance-$request->amount")
                    ]);
                FundsRegisterModel::where('user_id', $receiver->user_id)
                    ->update([
                        'balance'   => DB::raw("balance+$request->amount")
                    ]);

                FundsTransactionModel::insert([
                    'transaction_code'      => 'TS-' . date('YmdHis'),
                    'operation_type'        => 4,
                    'account_number'        => $sender->account_number,
                    'amount'                => $request->amount,
                    'balance'               => $sender->balance,
                    'remark'                => $request->remark,
                    'user_log'              => Auth::user()->id,
                    'request_date'          => date('d-m-Y H:i:s A'),
                    'status'                => 1,
                    'app_rej_date'          => date('Y-m-d H:i:s A'),
                    'request_date'          => date('Y-m-d H:i:s A')
                ]);
                FundsTransactionModel::insert([
                    'transaction_code'      => 'TS-' . date('YmdHis'),
                    'operation_type'        => 5,
                    'account_number'        => $receiver->account_number,
                    'amount'                => $request->amount,
                    'balance'               => $receiver->balance,
                    'remark'                => $request->remark,
                    'user_log'              => Auth::user()->id,
                    'request_date'          => date('d-m-Y H:i:s A'),
                    'status'                => 1,
                    'app_rej_date'          => date('Y-m-d H:i:s A'),
                    'request_date'          => date('Y-m-d H:i:s A')
                ]);
                $response = ['success' => true, 'msg' => 'Successfully Sent'];
            } else {
                $response = ['success' => false, 'msg' => 'Please Check Agency Account or Your Requested Amount'];
            }
        } catch (\Exception $ex) {
            DB::rollback();
            $response = ['success' => false, 'msg' => $ex->getMessage()];
        }
        return response()->json($response);
    }
    public function accountfundinfo($account_number)
    {
        return response()->json(['success' => true, 'data' => FundsRegisterModel::where('account_number', $account_number)->first()]);
    }
}
