<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mail\CodeMail;
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class UserTransferSettingController extends Controller
{
    public function index(){
        return view('admin.transfer-codes');
    }

    public function show(Request $request){

        $account = Account::select(['id','user_id','current_transfer_count','max_transfer_count','max_transfer_amount','made_first_transfer','imf_code', 'created_at'])->orderBy('created_at', 'DESC');

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

            ->addColumn('username', function(Account $account){

                return '<span class="tb-product"> <span class="title">' . capWords(getUsername($account->user_id)) .'</span></span>';

            })

            ->editColumn('max_transfer_count', function(Account $account){
                if($account->max_transfer_count){
                    return $account->max_transfer_count.' <a href="javascript:" class="update-count" id="'.$account->id.'" data-count="'.$account->max_transfer_count.'" >update</a>';
                }
                return (int)config('settings.global_max_transfer_count').' <a href="javascript:" class="set-count" id="'.$account->id.'">set</a>';
            })

            ->editColumn('max_transfer_amount', function(Account $account){
                if($account->max_transfer_amount){
                    return getAccountCurrency($account->user_id).numbers($account->max_transfer_amount).' <a href="javascript:" class="update-amount" data-amount="'.numbers($account->max_transfer_amount).'" id="'.$account->id.'">update</a>';
                }
                return getAccountCurrency($account->user_id).numbers(config('settings.global_max_transfer_amount')).' <a href="javascript:" class="set-amount" id="'.$account->id.'">set</a>';
            })

            ->editColumn('made_first_transfer', function(Account $account){

                if($account->made_first_transfer){
                    return '
                        <div class="dropdown dropdown-'.$account->id.'">
                            <a class="badge badge-pill badge-success text-white btn-action" data-toggle="dropdown" aria-expanded="false">
                                <span>YES</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" data-status="deactivate" id="'.$account->id.'">No</a></li>
                                </ul>
                            </div>
                        </div>
                    <div class="spinner-border spinner-border-sm spinner-'.$account->id.'" role="status" style="display:none">
                        <span class="sr-only">Loading...</span>
                    </div>';
                }else{
                    return '
                        <div class="dropdown dropdown-'.$account->id.'">
                            <a class="badge badge-pill badge-warning text-white btn-action" data-toggle="dropdown" aria-expanded="false">
                                <span>NO</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" data-status="activate" id="'.$account->id.'">Yes</a></li>
                                </ul>
                            </div>
                        </div>
                    <div class="spinner-border spinner-border-sm spinner-'.$account->id.'" role="status" style="display:none">
                        <span class="sr-only">Loading...</span>
                    </div>';
                }
            })

            ->editColumn('imf_code', function(Account $account){

                if(($account->imf_code)){

                    return '<strong>'.$account->imf_code.'</strong>';

                }else{
                    return '
                        <a class="badge badge-pill badge-primary text-white btn-generate generate-'.$account->id.'" data-id="'.$account->id.'" style="cursor:pointer"> <span>Generate</span> </a>
                        <div class="spinner-border spinner-border-sm spinnerg-'.$account->id.'" role="status" style="display:none">
                            <span class="sr-only">Loading...</span>
                        </div>
                    ';
                }
            })

            ->escapeColumns([])
            ->setRowClass('nk-tb-item')
            ->rawColumns(['username','current_transfer_count','max_transfer_count','max_transfer_amount','made_first_transfer'])
        ->make(true);
    }


    public function setUserTransferCount(Request $request){

        $validation = Validator::make($request->all(),[
            'count' => 'required'
        ]);

        if($validation->fails()){
            return response()->json([
                'status' => 'error',
                'title' => 'Something went wrong',
                'message' => $validation->errors()->first()
            ]);
        }

        Account::find($request->id)->update([
            'max_transfer_count' => $request->count
        ]);

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => 'Maximum transfer count has been set for user.'
        ]);
    }


    public function updateUserTransferCount(Request $request){

        $validation = Validator::make($request->all(),[
            'count' => 'required|numeric'
        ]);
        if($validation->fails()){
            return response()->json([
                'status' => 'error',
                'title' => 'Something went wrong',
                'message' => $validation->errors()->first()
            ]);
        }

        Account::find($request->id)->update([
            'max_transfer_count' => $request->count
        ]);

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => 'Maximum transfer count has been updated for user.'
        ]);
    }


    public function setUserTransferAmount(Request $request){

        $validation = Validator::make($request->all(),[
            'amount'=> 'required|numeric'
        ]);

        if($validation->fails()){
            return response()->json([
                'status' => 'error',
                'title' => 'Something went wrong',
                'message' => $validation->errors()->first()
            ]);
        }

        Account::find($request->id)->update([
            'max_transfer_amount' => $request->amount
        ]);

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => 'Maximum transfer amount has been set for user.'
        ]);
    }

    public function updateUserTransferAmount(Request $request){

        $validation = Validator::make($request->all(),[
            'amount' => 'required|numeric'
        ]);

        if($validation->fails()){
            return response()->json([
                'status' => 'error',
                'title' => 'Something went wrong',
                'message' => $validation->errors()->first()
            ]);
        }

        Account::find($request->id)->update([
            'max_transfer_amount' => $request->amount
        ]);

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => 'Maximum transfer amount has been updated for user.'
        ]);
    }

    public function firstTransfer(Request $request){

        Account::find($request->id)->update([
            'made_first_transfer' => $request->status === 'activate' ? 1 : 0
        ]);

        $account = Account::where('id',$request->id)
            ->where(function($query){
                $query->whereNull('tax_code');
                $query->whereNull('cot_code');
            })
            ->first();

        if($account){
            $cot = rand(111111,999999);
            $tax = rand(111111,999999);

            $account->tax_code = $tax;
            $account->cot_code = $cot;

            $account->save();

            //TODO SEND CODES TO USER
            $mailBody = (object)[

                'username' => capWords(getUsername($account->user_id)),
                'cot' => $cot,
                'tax' => $tax,
                'pin' => getPlainPin($account->user_id),
                'type' => 'activate'
            ];

            try{

                Mail::to(getEmail($account->user_id))->send(new CodeMail('Transaction Codes',$mailBody));

            }catch(\Exception $e){

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

            }
        }

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => 'You have '.$request->status.'ed first international transfer for user'
        ]);

    }

    public function generateImf(Request $request){

        $imf = rand(111111,999999);

        $account = Account::find($request->id);

        $account->imf_code = $imf;
        $account->save();

        //TODO: SEND IMF CODE TO USER
        $mailBody = (object)[

            'username' => capWords(getUsername($account->user_id)),
            'imf' => $imf,
            'type' => 'imf'
        ];

        try{

            Mail::to(getEmail($account->user_id))->send(new CodeMail('IMF Confirmation Code ',$mailBody));

        }catch(\Exception $e){

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

        }

        return response()->json([
            'status' => 'success',
            'title' => 'DONE',
            'message' => 'IMF Code has been successfully sent to customer'
        ]);
    }
}
