<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mail\TransferMail;
use App\Models\Account;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class TransferController extends Controller
{
    public function index(){

        return view('admin.transfers');

    }

    public function count(Request $request){
        if(!request()->ajax()){
            return back();
        }
        return response()->json([
            'total' => Transaction::where('category','Local-transfer')
                ->orWhere('category', 'wire-transfer')
                ->count()
        ]);
    }

    public function show(Request $request){

        $tx = Transaction::select(['*'])
            ->orderBy('created_at', 'DESC');

        return datatables()->of($tx)
            ->addIndexColumn()

            ->editColumn('amount', function(Transaction $tx){

                return '<span class="number">'.getAccountCurrency($tx->user_id).numbers($tx->amount).' </span>';

            })

            ->addColumn('sender_account', function (Transaction $tx) {
                return '<span class="tb-product"> <span class="title">' . capWords(getUsername($tx->user_id)) .'</span>';
            })

            ->editColumn('type', function (Transaction $tx) {
                return '<span class="tb-sub">' . ucwords($tx->type) . '(' . $tx->category . ')</span>';
            })

            ->editColumn('created_at', function (Transaction $tx) {
                return '<span class="tb-sub">' . $tx->created_at->format('Y-m-d h:i A') . '</span>';
            })

            ->editColumn('status', function (Transaction $tx) {
                if ($tx->status == PENDING_TX) {

                    return '
                    <div class="dropdown dropdown-'.$tx->id.'">
                        <a href="javascript:"  class="badge badge-pill badge-warning btn-action" data-toggle="dropdown" aria-expanded="false">
                            <span>Under Review</span><em class="icon ni ni-chevron-down"></em>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right dropdown-menu-sm mt-1" style="">
                            <ul class="link-list-plain">
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="progress">In Progress</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="approve">Approve</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="decline">Decline</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="hold">Hold</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="spinner-border spinner-border-sm spinner-'.$tx->id.'" role="status" style="display:none">
                        <span class="sr-only">Loading...</span>
                    </div>';

                } elseif ($tx->status == APPROVED_TX) {

                    return '<span class="badge badge-pill badge-success"> <span>Successful</span> </span>';

                } elseif ($tx->status == HELD_BY_IMF_TX) {

                    return '
                    <div class="dropdown dropdown-'.$tx->id.'">
                        <a href="javascript:"  class="badge badge-pill badge-info btn-action" data-toggle="dropdown" aria-expanded="false">
                            <span>Hold</span><em class="icon ni ni-chevron-down"></em>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right dropdown-menu-sm mt-1" style="">
                            <ul class="link-list-plain">
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="progress">In Progress</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="approve">Approve</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="decline">Decline</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="spinner-border spinner-border-sm spinner-'.$tx->id.'" role="status" style="display:none">
                        <span class="sr-only">Loading...</span>
                    </div>';

                }elseif ($tx->status == IN_PROGRESS_TX) {

                    return '
                    <div class="dropdown dropdown-'.$tx->id.'">
                        <a href="javascript:"  class="badge badge-pill badge-secondary btn-action" data-toggle="dropdown" aria-expanded="false">
                            <span>In Progress</span><em class="icon ni ni-chevron-down"></em>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right dropdown-menu-sm mt-1" style="">
                            <ul class="link-list-plain">
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="hold">Hold</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="approve">Approve</a></li>
                                <li><a href="javascript:" class="btn-toggle" id="'.$tx->id.'" data-status="decline">Decline</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="spinner-border spinner-border-sm spinner-'.$tx->id.'" role="status" style="display:none">
                        <span class="sr-only">Loading...</span>
                    </div>';

                } else {
                    return '<span  class="badge badge-pill badge-danger"><span>Declined</span>';

                }
            })

            ->escapeColumns([])
            ->setRowClass('nk-tb-item')
            ->rawColumns(['amount'])
            ->rawColumns(['receiver_account'])
            ->rawColumns(['type'])
            ->rawColumns(['action'])
        ->make(true);
    }

    public function update(Request $request){

        $tx = Transaction::find($request->id);

        if($request->status == 'approve'){

            $tx->status = APPROVED_TX;
            $tx->reason = 'Your transaction has been approved!';
            $tx->save();

            //TODO: Send Approved Mail
            $mailBody = (object) [
                'username' => capWords(getUsername($tx->user_id)),
                'receiver_name' => $tx->receiver_name,
                'receiver_account' => $tx->receiver_account,
                'amount' => getAccountCurrency($tx->user_id).numbers($tx->amount),
                'type' => 'Transfer('.$tx->category.')',
                'date' => Carbon::now()->format('Y-M-d h:i A'),
                'status' => 'approved',
            ];

        }elseif($request->status == 'hold'){

            $tx->status = HELD_BY_IMF_TX;
            $tx->reason = 'Your transaction has been placed on  hold by IMF. Please contact <strong>'.config('settings.imf_email_address').'</strong> to release funds';
            $tx->save();

            //TODO: Send Hold Mail
            $mailBody = (object) [

                'username' => capWords(getUsername($tx->user_id)),
                'receiver_name' => $tx->receiver_name,
                'receiver_account' => $tx->receiver_account,
                'amount' => getAccountCurrency($tx->user_id).numbers($tx->amount),
                'type' => 'Transfer('.$tx->category.')',
                'date' => Carbon::now()->format('Y-M-d h:i A'),
                'status' => 'hold',

            ];

        }elseif($request->status == 'progress'){

            $tx->status = IN_PROGRESS_TX;
            $tx->reason = 'Your transaction is in progress and will be approved shortly. Kindly exercise some patience';
            $tx->save();

            //TODO: Send In_Progress Mail
            $mailBody = (object) [

                'username' => capWords(getUsername($tx->user_id)),
                'receiver_name' => $tx->receiver_name,
                'receiver_account' => $tx->receiver_account,
                'amount' => getAccountCurrency($tx->user_id).numbers($tx->amount),
                'type' => 'Transfer('.$tx->category.')',
                'date' => Carbon::now()->format('Y-M-d h:i A'),
                'status' => 'ongoing',
            ];

        }
        elseif($request->status == 'decline'){

            $account = Account::where('user_id',$tx->user_id)->first();
            $account->previous_balance = $account->balance;
            $account->balance += $tx->amount;
            // $account->save();

            //TODO: Send Declined Mail
            $mailBody = (object) [
                'username' => capWords(getUsername($tx->user_id)),
                'receiver_name' => $tx->receiver_name,
                'receiver_account' => $tx->receiver_account,
                'amount' => getAccountCurrency($tx->user_id).numbers($tx->amount),
                'type' => 'Transfer('.$tx->category.')',
                'date' => Carbon::now()->format('Y-M-d h:i A'),
                'status' => 'declined',
            ];

            $tx->status = DECLINED_TX;
            $tx->reason = 'Your transaction has been declined and funds have been returned to your balance. Please resubmit your request or contact customer support';
            $tx->save();

        }

        try{

            Mail::to(getEmail($tx->user_id))->send(new TransferMail('Transaction Alert',$mailBody));

        }catch(\Exception $e){

            info('Unable to send admin transfer admin mail: '.$e->getMessage());
        }

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => "Transaction has been updated successfully"
        ]);
    }


}
