<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Session;
use App\functions;
use App\User;
use DB;
use Image;
use PragmaRX\Google2FAQRCode\Google2FA;
use App\CardBank;
use App\Wallet;
use Morilog\Jalali;

class ProfileController extends Controller
{
    function index()
    {
        $ostan = \App\provinces::all();
        if (Auth::user()->id_province) {
            $province = \App\provinces::find(Auth::user()->id_province);
            $cities = $province->cities()->select('id', 'title')->get();
        }
        $data["ostan"] = $ostan;
        $data["city"] = isset($cities) ? $cities : array();
        return view('user.profile.profile',$data);
    }

    function send_otp_finotech(Request $request){
        $validator = \Validator::make($request->all(), [
            'code_meli' => 'required|numeric',
            'code_finotech' => 'nullable|numeric|digits:5',
        ]);
        if ($validator->fails() != 1 && (!isset(Auth::user()->code_meli) || Auth::user()->code_meli == '')):
            $functions = new functions;
            $mobile = Auth::user()->mobile;
            $authorization = "Authorization: Basic ".env('FinotechKey');

            if (!isset($request->code_finotech)){
                $url = 'https://apibeta.finnotech.ir/dev/v2/oauth2/authorize?client_id='.env('FinotechClientId').'&response_type=code&redirect_uri='.env('FinotechRedirectUri').'&scope=facility:sms-nid-verification:get&mobile='.$mobile.'&state='.time().'&auth_type=SMS';
                $responce = $functions->Curl($url,array(),$authorization,'GET');
                if ($responce->statusCodeHttp == 200 && $responce->status =='DONE') {
                    $result = (object)$responce->result;
                    Session::put("trackId", $result->trackId);
                    $result = array('status' => true,'message' => 'پیامک با موفقیت ارسال شد'.'<br>'.'<small>ممکن است کمی تاخیر داشته باشد و لطفا صبور باشید</small>');
                } else {
                    $result = array('status' => false,'message' => 'فعلا ارسال پیامک امکان پذیر نیست');
                }
            }else{

                $url = 'https://apibeta.finnotech.ir/dev/v2/oauth2/verify/sms';
                $param = array(
                    "mobile"=> $mobile,
                    "otp"=> $request->code_finotech,
                    "nid"=> $request->code_meli,
                    "trackId"=> Session::get('trackId')
                );
                $responce = $functions->Curl($url,$param,$authorization,'POST');
                if ($responce->statusCodeHttp == 200 && $responce->status =='DONE') {
                    $user = User::find(Auth::user()->id);
                    $user->code_meli = $request->code_meli;
                    $user->save();
                    $result = array('status' => true, 'message' => 'احراز مالکیت موبایل با موفقیت انجام شد');
                }else{
                    $result2 = (object)$responce->error;
                    if ($result2->message == "invalid otp or mobile")
                        $result = array('status' => false, 'message' => 'کد درج شده صحیح نمی باشد','refresh'=>false);
                    elseif ($result2->message == 'service provider failed' or $result2->message == 'nid and mobile is not match')
                        $result = array('status' => false, 'message' => 'کد ملی درج شده با کد ملی صاحب موبایل مطابقت ندارد و  لطفا مجدد کد ملی صحیح را درج نمایید','refresh'=>true);
                    elseif ($result2->message == "Expiration time is exceeded")
                        $result = array('status' => false, 'message' => 'کد ارسالی منقضی شده است و مجدد ثبت کنید','refresh'=>true);
                    else
                        $result = array('status' => false, 'message' => 'متاسفانه احراز هویت اکنون مقدور نیست'.'<br>'.$result2->message,'refresh'=>false);
                }
            }
        else:
            $result = array('status' => false, 'message' => 'داده های درج شده درست نیست','refresh'=>false);
        endif;
        return response()->json($result);
    }



    function resend_otp_finotech(Request $request){
        $validator = \Validator::make($request->all(), [
            'code_meli' => 'required|numeric',
        ]);
        if ($validator->fails() != 1 && (isset(Auth::user()->code_meli) || Auth::user()->code_meli == '')):
            $functions = new functions;
            $authorization = "Authorization: Basic ".env('FinotechKey');
            $mobile = Auth::user()->mobile;
            $url = 'https://apibeta.finnotech.ir/dev/v2/oauth2/authorize?client_id='.env('FinotechClientId').'&response_type=code&redirect_uri='.env('FinotechRedirectUri').'&scope=facility:sms-nid-verification:get&mobile='.$mobile.'&state='.time().'&auth_type=SMS';
            $responce = $functions->Curl($url,array(),$authorization,'GET');
            if ($responce->statusCodeHttp == 200 && $responce->status =='DONE') {
                $result = (object)$responce->result;
                Session::put("trackId", $result->trackId);
                $result = array('status' => true,'message' => 'پیامک با موفقیت ارسال شد');
            } else {
                $result = array('status' => false,'message' => 'فعلا ارسال پیامک امکان پذیر نیست');
            }
        else:
            $result = array('status' => false, 'message' => 'داده های درج شده درست نیست');
        endif;
        return response()->json($result);
    }


    function national_card(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'auth_img' => 'required|mimes:jpg,jpeg,png',
            'codemeli' => 'required|numeric',
            //'FatherName' => 'required|farsi',
            'DateBirth' => 'required',
        ]);
        if ($validator->fails() != 1):

            $user = User::find(Auth::user()->id);
            $user->code_meli = $request->codemeli;
            //$user->father_name = $request->FatherName;
            $user->date_birth = $request->DateBirth;


            $file = $request->file('auth_img');
            $extension = $file->getClientOriginalExtension();
            $just_name = str_replace(" ", "-", pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
            $just_name_hash = str_replace("/", "",bcrypt($just_name  .time().'meli'));
            $name = $just_name_hash.'.'.$extension;

            $Image = Image::make($file);
            if ($Image->width() > 1500) {
                $Image->resize(1500, null, function ($constraint) {
                    $constraint->aspectRatio();
                });
            }
            if ($Image->height() > 2000) {
                $Image->resize(null, 2000, function ($constraint) {
                    $constraint->aspectRatio();
                });
            }


            $directory = 'uploads/Users/'.$user->created_at->year.'/'.$user->created_at->month.'/'. $user->id;
            $file_path = $directory . '/'. $name;
            if (!file_exists(($file_path))) {
                \File::makeDirectory($directory, $mode = 0777, true, true);
                if ($Image->save(($directory . '/'. $name))) {
                    $user->auth_img = $directory . '/' .$name;
                }
            } else {
                if ($Image->save(($directory . '/' . $just_name_hash.time() . '.' . $extension))) {
                    $user->auth_img = $directory . '/' .$just_name_hash.time() . '.' . $extension;
                }
            }
            $user->auth_img_confirm = 2;
            $user->save();


            $result = array('status' => true, 'message' => 'تصویر با موفقیت ثبت شد و در انتظار بررسی قرار گرفت');

        else:
            $result = array('status' => false, 'message' =>  $validator->errors()->first());
        endif;
        return response()->json($result);
    }


    function edit_password(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'old_password' => 'required|min:6',
            'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
            'password_confirmation' => 'min:6'
        ]);

        if ($validator->fails() != 1):

            if (\Hash::check($request->input('old_password'), Auth::user()->password)) {
                if($request->password == $request->password_confirmation){
                    $user = User::find(Auth::user()->id);
                    $user->password = bcrypt($request->password);
                    $user->save();
                    auth('')->logout();
                    $result = array('status' => true, 'message' => 'رمز عبور با موفقیت ویرایش شد.');
                }else
                    $result = array('status' => false, 'message' => 'رمز جدید و تکرار با یکدیگر برابر نیستند.');
            }else
                $result = array('status' => false, 'message' => 'رمز فعلی اشتباه است.');

        else:
            $result = array('status' => false, 'message' => 'داده های ارسالی اشتباه است.');
        endif;
        return response()->json($result);

    }

    function twofa()
    {
        $data = array();
        if (Auth::user()->google2fa == null){

            $google2fa = new Google2FA(new \BaconQrCode\Renderer\Image\SvgImageBackEnd());
            if(session()->has("secret"))
                $secret = session()->get("secret");
            else{
                $secret = $google2fa->generateSecretKey();
                session()->put("secret", $secret);
            }
            $data['goole2fa']['secret'] = $secret;
            $inlineUrl = $google2fa->getQRCodeInline(
                env('APP_NAME'),
                'mobile:'.Auth::user()->mobile,
                $secret
            );
            $data['goole2fa']['inlineUrl'] = $inlineUrl;

        }
        return view('user.profile.profile-2fa',$data);
    }

    function twofa_sms(Request $request)
    {
        if($request->sms==1){
            $user = User::find(Auth::user()->id);
            $user->sms2fa = 1;
            $user->google2fa = null;
            $user->save();
            $result = array('status' => true, 'message' => 'ورود دو مرحله ای از طریق پیامک با موفقیت فعال شد!');
        }
        else{
            $user = User::find(Auth::user()->id);
            $user->sms2fa = 0;
            $user->save();
            $result = array('status' => true, 'message' => 'ورود دو مرحله ای غیر فعال شد!');
        }
        return response()->json($result);
    }

    function twofa_google(Request $request)
    {
        $google2fa = new Google2FA(new \BaconQrCode\Renderer\Image\SvgImageBackEnd());
        if(isset(Auth::user()->google2fa)){
            $valid = $google2fa->verifyKey(Auth::user()->google2fa, $request->code);
            if($valid==1){
                $user = User::find(Auth::user()->id);
                $user->google2fa = null;
                $user->save();
                $result = array('status' => true, 'message' => 'ورود دو مرحله ای غیر فعال شد!');
            }else{
                $result = array('status' => false, 'message' => 'کد اشتباه است!');
            }
        }
        else{
            $valid = $google2fa->verifyKey(Session::get("secret"), $request->code);
            if($valid==1){
                $user = User::find(Auth::user()->id);
                $user->google2fa = Session::get("secret");
                $user->sms2fa = 0;
                $user->save();
                $result = array('status' => true, 'message' => 'ورود دو مرحله ای از طریق گوگل با موفقیت فعال شد!');
            }else{
                $result = array('status' => false, 'message' => 'کد اشتباه است!');
            }
        }
        return response()->json($result);
    }


    function financialIndex()
    {
        $cards = CardBank::where('id_user',Auth::user()->id)->orderBy('id','desc')->get();
        foreach ($cards as $card){
            $card->card_number = self::formatCreditCard($card->card_number);
        }
        $data['card'] = $cards;

        return view('user.profile.financial',$data);
    }

    function financial(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'bank_name' => 'required',
            'card_number' => 'required|numeric',
            'account_number' => 'required|numeric',
            'iban' => 'required|numeric',
            //'card_image' => 'required|mimes:jpg,jpeg,png',
        ], [
            'bank_name.required' => 'نام بانک را وارد نمایید',
            'name_family.required' => 'نام صاحب حساب را وارد نمایید',
            'card_number.required' => 'شماره کارت را وارد نمایید',
            'account_number.required' => 'شماره حساب را وارد نمایید',
            'iban.required' => 'شناسه شبا را وارد نمایید',
            'card_image.required' => 'تصویر کارت را وارد نمایید'
        ]);

        if ($validator->fails()) {
            $result = array('status' => false, 'message' => $validator->errors()->first());
            return response()->json($result);
        }

        $bank = \App\CardBank::where('card_number',$request->card_number)->first();
        if(isset($bank)){
            $result = array('status' => false, 'message' => 'شماره کارت قبلا ثبت شده است!');
            return response()->json($result);
        }

        if($request->bank_name == 'سایر' && (!isset($request->iban) || !isset($request->account_number))){
            $result = array('status' => false, 'message' => 'شماره شبا و شماره حساب درج شود!');
            return response()->json($result);
        }




        DB::beginTransaction();
        try {
            $bank = new \App\CardBank;
            $bank->id_user = Auth::id();
            $bank->bank_name = $request->bank_name;
            $bank->card_number = $request->card_number;
            $bank->account_number = $request->account_number;
            $bank->shaba = $request->iban;
            $bank->save();

            DB::commit();

            /*
            $app = app('App\Http\Controllers\Admin\UsersController');
            if($bank->bank_name != 'سایر'){
                $request->merge([ 'id_card' => $bank->id ,  'model' => 'iban','id'=>$bank->id_user]);
                $res = $app->finnotech_card($request)->getData();
                $bank = \App\CardBank::find($bank->id);
                $similarText = similar_text($bank->account_owner,Auth::user()->name.' '.Auth::user()->family);
                if($res->status == 'true'){
                    $StrLen = (strlen($bank->account_owner)) - 7;
                    //dd($StrLen .'<'. $similarText);
                    if($StrLen < $similarText){
                        $bank->confirm = 1;
                        $bank->save();
                    }
                }
            }else{
                $request->merge([ 'id_card' => $bank->id ,  'model' => 'ibanOther','id'=>$bank->id_user]);
                $res = $app->finnotech_card($request)->getData();
                $bank = \App\CardBank::find($bank->id);
                $similarText = similar_text($bank->account_owner,Auth::user()->name.' '.Auth::user()->family);
                if($res->status == 'true'){
                    $StrLen = (strlen($bank->account_owner)) - 7;
                    if($StrLen < $similarText){
                        $request->merge([ 'id_card' => $bank->id ,  'model' => 'card','id'=>$bank->id_user]);
                        $res = $app->finnotech_card($request)->getData();
                        $bank = \App\CardBank::find($bank->id);
                        $similarText = similar_text($bank->account_owner,Auth::user()->name.' '.Auth::user()->family);
                        if($res->status == 'true'){
                            $StrLen = (strlen($bank->account_owner)) - 7;
                            if($StrLen < $similarText){
                                $bank->confirm = 1;
                                $bank->save();
                            }
                        }
                    }
                }
            }
            */

            DB::commit();
            $result = array('status' => true, 'message' => 'کارت بانکی شما با موفقیت ثبت شد و نیاز به بررسی توسط مدیریت سایت می باشد. پس از تایید به شما اطلاع داده خواهد شد.');

        } catch (\Exception $e) {
            DB::rollback();
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد' . $e);
        }
        return response()->json($result);
    }

    function walletIndex()
    {
        $wallets = Wallet::where('id_user',Auth::user()->id)->orderBy('id','desc')->get();

        $data['wallet'] = $wallets;

        return view('user.profile.wallet',$data);
    }
    function wallet(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'coin_name' => 'required',
            'wallet' => 'required',
        ], [
            'coin_name.required' => 'نام ارز مرتبط به کیف پول را وارد نمایید',
            'wallet.required' => 'آدرس کیف پول را وارد نمایید',
        ]);

        if ($validator->fails()) {
            $result = array('status' => false, 'message' => $validator->errors()->first());
            return response()->json($result);
        }

        $bank = \App\Wallet::where('wallet',$request->wallet)->first();
        if(isset($bank)){
            $result = array('status' => false, 'message' => 'این آدرس کیف پول قبلا ثبت شده است');
            return response()->json($result);
        }

        if($request->bank_name == 'سایر' && (!isset($request->iban) || !isset($request->account_number))){
            $result = array('status' => false, 'message' => 'شماره شبا و شماره حساب درج شود!');
            return response()->json($result);
        }




        DB::beginTransaction();
        try {
            $bank = new \App\Wallet;
            $bank->id_user = Auth::id();
            $bank->coin_name = $request->coin_name;
            $bank->wallet = $request->wallet;
            $bank->save();


            DB::commit();
            $result = array('status' => true, 'message' => 'آدرس کیف شما با موفقیت ثبت شد!');

        } catch (\Exception $e) {
            DB::rollback();
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد' . $e);
        }
        return response()->json($result);
    }

    function selfieImg(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'selfie_img' => 'required|mimes:jpg,jpeg,png',
        ]);
        if ($validator->fails() != 1):

            $user = User::find(Auth::user()->id);

            $file = $request->file('selfie_img');
            $extension = $file->getClientOriginalExtension();
            $just_name = str_replace(" ", "-", pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
            $just_name_hash = str_replace("/", "",bcrypt($just_name  .time().'selfie'));
            $name = $just_name_hash.'.'.$extension;

            $Image = Image::make($file);
            if ($Image->width() > 2000) {
                $Image->resize(2000, null, function ($constraint) {
                    $constraint->aspectRatio();
                });
            }
            if ($Image->height() > 2500) {
                $Image->resize(null, 2500, function ($constraint) {
                    $constraint->aspectRatio();
                });
            }


            $directory = 'uploads/Users/'.$user->created_at->year.'/'.$user->created_at->month.'/'. $user->id;
            $file_path = $directory . '/'. $name;
            if (!file_exists(($file_path))) {
                \File::makeDirectory($directory, $mode = 0777, true, true);
                if ($Image->save(($directory . '/'. $name))) {
                    $user->selfie_img = $directory . '/' .$name;
                }
            } else {
                if ($Image->save(($directory . '/' . $just_name_hash.time() . '.' . $extension))) {
                    $user->selfie_img = $directory . '/' .$just_name_hash.time() . '.' . $extension;
                }
            }
            $user->selfie_img_confirm = 2;
            $user->save();


            $result = array('status' => true, 'message' => 'تصویر با موفقیت ثبت شد و در انتظار بررسی قرار گرفت');

        else:
            $result = array('status' => false, 'message' =>  $validator->errors()->first());
        endif;
        return response()->json($result);
    }



    function FormatCreditCard($cc)
    {
        if(Auth::guard('admin')->check()){
            return $cc;
        }
        else {
            // Clean out extra data that might be in the cc
            $cc = str_replace(array('-', ' '), '', $cc);
            // Get the CC Length
            $cc_length = strlen($cc);
            // Initialize the new credit card to contian the last four digits
            $newCreditCard = substr($cc, -4);
            // Walk backwards through the credit card number and add a dash after every fourth digit
            for ($i = $cc_length - 5; $i >= 0; $i--) {
                // If on the fourth character add a dash
                if ((($i + 1) - $cc_length) % 4 == 0) {
                    $newCreditCard = '-' . $newCreditCard;
                }
                // Add the current character to the new credit card
                $newCreditCard = $cc[$i] . $newCreditCard;
            }
            // Return the formatted credit card number
            return $newCreditCard;
        }
    }



    function address_ownership(Request $request){
        $functions = new functions;
        $request->phone = $functions->toLatin($request->phone);
        $request->verify_phone = $functions->toLatin($request->verify_phone);

        $validator = \Validator::make($request->all(), [
            'phone' => 'required|numeric|phone|digits:11',
        ]);

        if ($validator->fails()) {
            $result = array('status' => false, 'message' => $validator->errors()->first());
            return response()->json($result);
        }

        if ($validator->fails() != 1 && !isset(Auth::user()->phone)):
            if (isset($request->phone) && $request->phone!='' && (!isset($request->verify_phone) || $request->verify_phone=='')){
                $randstring = rand(1000, 9999);
                $functions->SetSession("verify_phone", $randstring);
                $functions->SetSession("phone", $request->phone);
                try{
                    \Kavenegar::VerifyLookup($request->phone, $randstring, null, null, 'VerifyMobile');
                    $result = array('status'=> true , 'message'=> 'تماس با شما در حال برقرای است'.'<br><small>'.'ممکن است کمی تاخیر داشته باشد(حداکثر 2 دقیقه)'.'</small>');
                }
                catch (\Exception $ex){
                    $result = array('status'=> false , 'message'=>  $ex->getMessage() );
                }
            }else{
                if( (isset($request->phone) && $request->phone!='') &&
                    ($functions->GetSession("phone") != $request->phone || $request->verify_phone != $functions->GetSession("verify_phone"))){
                    $result = array('status' => false, 'message' => 'کد تایید تلفن صحیح نمیباشد');
                    return response()->json($result);
                }
                $user = User::find(Auth::user()->id);
                $user->phone = $request->phone;
                if($user->daily_buy >= 10000000){
                    $user->daily_buy = $user->daily_buy * 2;
                }else{
                    $user->daily_buy = 10000000;
                }
                $user->save();
                $result = array('status' => true, 'message' => 'تلفن با موفقیت ثبت شد و سقف خرید شما به '.number_format($user->daily_buy).' تومان تغییر یافت! ');

            }
        else:
            $result = array('status' => false, 'message' => $validator->errors()->first());
        endif;
        return response()->json($result);
    }


    function get_cities(Request $request)
    {
        $province = \App\provinces::find($request->id);
        $cities = $province->cities()->select('id','title as name')->get();
        return response()->json($cities);
    }

    public function logActivity()
    {
        $logs = \App\LogActivity::select('id','subject','url','method','ip','agent','user_id','created_at')
            ->where('user_id',Auth::user()->id)
            ->paginate(10);
        return view('user.profile.log',compact('logs'));
    }
}
