<?php

namespace App\Http\Controllers\API;

use Carbon\Carbon;
use App\Models\Plan;
use GuzzleHttp\Client;
use App\Models\CardDetails;
use App\Models\Transection;
use Illuminate\Http\Request;
use App\Services\BamboraService;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use App\Models\SubscriptionPaymentHistory;
use Stripe\Token;
use Stripe\Stripe;
use Stripe\StripeClient;
use Stripe\Customer;

class BamboraController extends Controller
{
    private $bambora;
    private $stripe;

    public function __construct(BamboraService $bamboraService)
    {
		$this->bambora = $bamboraService;
        Stripe::setApiKey(env('STRIPE_SECRET_KEY'));
        $this->stripe = new StripeClient(env('STRIPE_SECRET_KEY'));
    }

    public function test_recuring() {
        // dd(Carbon::now()->toDateTimeString());
        // 2024-04-27 06:37:29
        $get_plan = Plan::with('user')
        ->with(['user' => function ($users) {
            $users->where('profile_id','!=',null)
            ->where('subscription_status','active')
            ->where('users.plan_id','=', 1)
            ->where('subscription_end_date', '<', "2024-04-27 06:24:00")
            ->where('payment_count','<',10);
        }])->where('id', 1)->get();

        // dd($get_plan);

        // $users = User::where('profile_id','!=',null)
        // ->where('subscription_status','active')
        // ->where('subscription_end_date','<',Carbon::now()->addDays(9))
        // ->where('payment_count','<',10)
        // ->with('plans')->get();
        // dd($users);

        foreach($get_plan as $user_value){
            if(count($user_value->user) > 0){
                foreach ($user_value->user as $user) {
                    // $payment = $this->bambora->make_payment($user,$user->card->card_id,$user->plan->recurring_price);

                    $charge_data = $this->stripe->charges->create([
                      'amount' => $user_value->recurring_price*100,
                      'currency' => 'usd',
                      'customer' => $user->profile_id,
                      'description' => $user_value->description,
                    ]);

                    // if($payment && $payment['message'] == 'Approved'){
                    if($charge_data->status == "succeeded"){
                        // $transaction = new SubscriptionPaymentHistory;
                        // $transaction->user_id = $user->id;
                        // $transaction->plan_id = $user->plan->id;
                        // $transaction->price = $user->plan->recurring_price;
                        // $transaction->save();

                        $user->plans()->attach($user_value);

                        $user->subscription_end_date = Carbon::now()->addDays(7);
                        $user->payment_count += 1;
                        $user->save();
                        info('User payment succesfull '.$user->id);
                    }else{
                        $user->subscription_status = 'inactive';
                        $user->save();

                        info('User payment unsuccesfull '.$user->id);
                    }
                }
            }
        }
        return 0;
    }

    public function generatePaymentToken(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'cardNumber' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }
        $firstSixDigits = substr(str_replace(' ', '', $request->cardNumber), 0, 6);
        $lastFourDigits = substr(str_replace(' ', '', $request->cardNumber), -4);
        CardDetails::create([
            'user_id' => Auth::user()->id,
            'user_email' => Auth::user()->email,
            'first_six' => $firstSixDigits,
            'last_four' => $lastFourDigits,
            'otp_code' => rand(10000, 99999),
        ]);
        $responseData = $response->json();
        return response()->json($responseData);
    }

    public function paymentProfile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'token' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }
        $response = Http::withHeaders([
            'Authorization' => "Passcode " . env('BAMBORA_API_PASSCODE'),
            'Content-Type' => 'application/json',
        ])->post('https://api.na.bambora.com/v1/profiles', [
            'token' => [
                'name' => 'John Doe',
                'code' => $request->token,
            ],
        ]);
        $responseData = $response->json();
        return response()->json($responseData);
    }

    public function processPayment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required',
            'code' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }

        // $response = Http::withHeaders([
        //     'Authorization' => "Passcode MzgzNjExODI2OkUyMkU1NEYwOUMxNjRENTI4MTVCRDhCMUM1ODQ4NEQz",
        //     'Content-Type' => 'application/json',
        // ])->post('https://api.na.bambora.com/v1/payments', [
        //     'amount' => $request->amount,
        //     'payment_method' => 'token',
        //     'token' => [
        //         'name' => '1',
        //         'code' => $request->code,
        //         'complete' => false,
        //     ],
        // ]);
        // $responseData = $response->json();
        // return response()->json($responseData);
        // // Handle the response
        // if ($response->successful()) {
        $trans = Transection::create([
            'user_id' => Auth::id(),
            'price' => $request->amount,
        ]);
        $user = User::find(Auth::id());
        $user->plan_buy_date = Carbon::now()->addDays(30);
        $user->save();
        //     $responseData = $response->json();
        //     // Handle the response data
        // } else {
        //     // Request failed
        //     $errorMessage = $response->body();
        //     // Handle the error message
        // }
        return [
            'data' => $trans,
            'status' => 200,
            'message' => 'success',
        ];
    }

    public function verifyCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'otp_code' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }
        $data = CardDetails::where('otp_code', $request->otp_code)->first();
        if ($data) {
            $user = User::find(Auth::id());
            $user->plan_buy_date = Carbon::now();
            $user->save();
            $data->delete();
            return [
                'status' => 200,
                'message' => 'success',
            ];
        } else {
            return [
                'status' => 404,
                'message' => 'Something went wrong',
            ];
        }
    }

    public function makePayment(Request $request)
    {
        $client = new Client();

        $response = $client->post('https://api.na.bambora.com/v1/payments', [
            'headers' => [
                'Authorization' => 'Passcode ' . "f365d85A1948415fB92cBb2d5d5f8CD2",
            ],
            'json' => [
                'merchant_id' => "383611826",
                'payment_method' => [
                    'payment_method' => 'card',
                    'card' => [
                        'name' => "Faizan Khan",
                        'number' => "4030000010001234",
                        'expiry_month' => "02",
                        'expiry_year' => "24",
                        'cvd' => "20",
                    ],
                ],
                'amount' => "100",
                'order_number' => "1",
            ],
        ]);

        $responseData = json_decode($response->getBody(), true);

        // Process the response and handle success or failure scenarios here

        // Redirect the user back to a thank-you page or error page
    }

    public function buy_subscription(Request $request){

        // dd($request->all());
        $validator = Validator::make($request->all(), [
            'plan_id' => 'required|exists:plans,id',
            'cardLast4' => 'required',
            'name' => 'required',
            'cardtokenID' => 'required',
            'cardID' => 'required',
            'cardBrand' => 'required',
            'cardExp_month' => 'required',
            'cardExp_year' => 'required',
            'address_line' => 'required',
            'city'=>'required',
            'postal_code' => 'required',
            // 'state' => 'required',
            'country' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }
        try {

            // $token = $this->bambora->create_token($request);

            // return response()->json([
            //     'errors' => $token,
            //     'status' => 401,
            // ]);
            $user = Auth::user();

            if($user->subscription_status == 'active'){
                return response()->json([
                    'errors' => "You already has an active subscription",
                    'status' => 400,
                ]);
            }

            if(!$user->profile_id){

                // create stripe
                $customer = $this->customer = Customer::create([
                    'name' => 'Faizan Khan',
                    'email' => $user->email,
                    'source' => $request->cardtokenID, //token_id
                ]);


                if ($customer) {
                    $user->profile_id = $customer->id;
                    $user->street = $request->addres_line;
                    $user->city = $request->city;
                    $user->zip = $request->postal_code;
                    $user->country = $request->country;
                    $user->save();
                } else {
                    return response()->json([
                        'errors' => $response,
                        'status' => 400,
                    ]);
                }

                // Bambora Profile Start
                // $response = $this->bambora->create_profile($request);

                // if($response && $response['code'] == 1 && isset($response['customer_code'])){
                //     $user->profile_id = $response['customer_code'];
                //     $user->street = $request->addres_line;
                //     $user->city = $request->city;
                //     $user->zip = $request->postal_code;
                //     $user->country = $request->country;
                //     $user->save();
                // }else{
                //     return response()->json([
                //         'errors' => $response,
                //         'status' => 400,
                //     ]);
                // }
                // Bambora Profile End

                $card_detail = new CardDetails;
                $card_detail->user_id = $user->id;
                $card_detail->user_email = $user->email;
                $card_detail->first_six = "nill";
                $card_detail->last_four = $request->cardLast4;
                $card_detail->card_id = $request->cardID;
                $card_detail->save();

            }else{
                //*** Bmbora Paymnet ***//

                // $card_detail = CardDetails::where('user_id',$user->id)->where('card_id','!=',null)->first();

                // if(!$card_detail){
    
                //     $card = $this->bambora->get_card_from_profile($user->profile_id);
    
                //     if($card && $card['code'] == 1 && $card['card']){
                //         $card_info  = $card['card'][0];
                //         $first_six = substr($card_info['number'], 0, 6);
                //         $last_four = substr($card_info['number'], -4);
        
                //         $card_detail = new CardDetails;
                //         $card_detail->user_id = Auth::user()->id;
                //         $card_detail->user_email = Auth::user()->email;
        
                //         $card_detail->first_six = $first_six;
                //         $card_detail->last_four = $last_four;
                //         $card_detail->card_id = $card_info['card_id'];
                //         $card_detail->save();
                //     }else{
                //         return response()->json([
                //             'errors' => $card,
                //             'status' => 400,
                //         ]);
                //     }
                // }
            }


            $plan = Plan::find($request->plan_id);

            $charge_data = $this->stripe->charges->create([
              'amount' => $plan->price*100,
              'currency' => 'usd',
              'customer' => $user->profile_id,
              'description' => $plan->description,
            ]);

            if($charge_data){
                // $transaction = new SubscriptionPaymentHistory;
                // $transaction->user_id = Auth::id();
                // $transaction->plan_id = $plan->id;
                // $transaction->price = $plan->price;
                // $transaction->save();

                $user->plans()->attach($plan);

                $user->plan_id = $plan->id;
                if($plan->type == 'lifetime'){
                    $user->subscription_end_date = Carbon::now()->addYears()->toDateTimeString();
                }else{
                    $user->subscription_end_date = Carbon::now()->addDays()->toDateTimeString();
                }
                $user->subscription_status = 'active';
                $user->payment_count += 1;
                $user->save();

                return response()->json([
                    'success' => 'Payment successfull',
                    'data' => $user,
                    'status' => 200,
                ]);
            }else{
                return response()->json([
                    'errors' => $payment,
                    'status' => 400,
                ]); 
            }


            //*** Bmbora Paymnet ***//
 
            // $plan = Plan::find($request->plan_id);

            // $payment = $this->bambora->make_payment($user,$card_detail->card_id,$plan->price);

            // if($payment && $payment['message'] == 'Approved'){
            //     $transaction = new SubscriptionPaymentHistory;
            //     $transaction->user_id = Auth::id();
            //     $transaction->plan_id = $plan->id;
            //     $transaction->price = $plan->price;
            //     $transaction->save();

            //     $user->plan_id = $plan->id;
            //     if($plan->type == 'lifetime'){
            //         $user->subscription_end_date = Carbon::now()->addYears(20)->toDateTimeString();
            //     }else{
            //         $user->subscription_end_date = Carbon::now()->addDays(2)->toDateTimeString();
            //     }
            //     $user->subscription_status = 'active';
            //     $user->payment_count += 1;
            //     $user->save();

            //     return response()->json([
            //         'success' => 'Payment successfull',
            //         'data' => $user,
            //         'status' => 200,
            //     ]);
            // }
            
        } catch (\Exception $e) {
            return response()->json([
                'errors' => $e->getMessage(),
                'status' => 400,
            ]);
        }
    }

    public function retry_payment(Request $request)
    {
        try {
            $user = Auth::user();

            if($user->subscription_status == 'active'){
                return response()->json([
                    'errors' => 'Subscription Active',
                    'status' => 400,
                ]);
            }

            if(!$user->profile_id){
                return response()->json([
                    'errors' => 'Invalid Profile. Please Buy Subscription First',
                    'status' => 400,
                ]);
            }

            $card_detail = CardDetails::where('user_id',Auth::user()->id)->where('card_id','!=',null)->first();

            if(!$card_detail){

                $card = $this->bambora->get_card_from_profile($user->profile_id);

                if($card && $card['code'] == 1 && $card['card']){
                    $card_info  = $card['card'][0];
                    $first_six = substr($card_info['number'], 0, 6);
                    $last_four = substr($card_info['number'], -4);
    
                    $card_detail = new CardDetails;
                    $card_detail->user_id = Auth::user()->id;
                    $card_detail->user_email = Auth::user()->email;
    
                    $card_detail->first_six = $first_six;
                    $card_detail->last_four = $last_four;
                    $card_detail->card_id = $card_info['card_id'];
                    $card_detail->save();
                }else{
                    return response()->json([
                        'errors' => $card['message'],
                        'status' => 400,
                    ]);
                }
            }

            $plan = Plan::find($user->plan_id);

            $payment = $this->bambora->make_payment($user,$card_detail->card_id,$plan->price);

            if($payment && $payment['message'] == 'Approved'){
                $transaction = new SubscriptionPaymentHistory;
                $transaction->user_id = Auth::id();
                $transaction->plan_id = $plan->id;
                $transaction->price = $plan->price;
                $transaction->save();

                $user->plan_id = $plan->id;
                if($plan->type == 'lifetime'){
                    $user->subscription_end_date = Carbon::now()->addYears(20)->toDateTimeString();
                }else{
                    $user->subscription_end_date = Carbon::now()->addDays(7)->toDateTimeString();
                }
                $user->subscription_status = 'active';
                $user->payment_count += 1;
                $user->save();

                return response()->json([
                    'success' => 'Payment successfull',
                    'data' => $user,
                    'status' => 200,
                ]);

            }

            return response()->json([
                'errors' => isset($payment['message']) ? $payment['message'] : 'Unable to process payment',
                'status' => 400,
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'errors' => $e->getMessage(),
                'status' => 400,
            ]);
        }
    }

    public function add_new_card(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'card_number' => 'required',
            'expiry_month' => 'required',
            'expiry_year' => 'required',
            'cvv' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }
        // dd($request->all());
        try {

            $user = Auth::user();

            if($user->subscription_status == 'active'){
                return response()->json([
                    'errors' => 'You already have an active subscrition',
                    'status' => 400,
                ]);
            }

            if(!$user->profile_id){
                return response()->json([
                    'errors' => 'Invalid Profile. Please Buy Subscription First',
                    'status' => 400,
                ]);
            }

            $card = $this->bambora->create_card_from_profile($request,$user->profile_id);
            
            $card_detail = CardDetails::where('user_id',Auth::user()->id)->where('card_id','!=',null)->first();
            
            if($card && is_array($card) && $card['code'] == 1){

                $first_six = substr($request->card_number, 0, 6);
                $last_four = substr($request->card_number, -4);

                if(!$card_detail){
    
                    $card_detail = new CardDetails;
                    $card_detail->user_id = Auth::user()->id;
                    $card_detail->user_email = Auth::user()->email;
    
                    $card_detail->first_six = $first_six;
                    $card_detail->last_four = $last_four;
                    $card_detail->card_id = $card_info['card_id'];
                    $card_detail->save();
                }else{
                    $card_detail->first_six = $first_six;
                    $card_detail->last_four = $last_four;
                    $card_detail->card_id = $card_detail->card_id + 1;
                    $card_detail->save();
                }
            }else{
                return response()->json([
                    'errors' => isset($card['message']) ? $card['message'] : 'Invalid Card Details',
                    'status' => 400,
                ]);
            }
            $plan = Plan::find($user->plan_id);

            $payment = $this->bambora->make_payment($user,$card_detail->card_id,$plan->price);

            if($payment && $payment['message'] == 'Approved'){
                $transaction = new SubscriptionPaymentHistory;
                $transaction->user_id = Auth::id();
                $transaction->plan_id = $plan->id;
                $transaction->price = $plan->price;
                $transaction->save();

                $user->plan_id = $plan->id;
                
                $user->subscription_end_date = Carbon::now()->addDays(7)->toDateTimeString();
                $user->subscription_status = 'active';
                $user->payment_count += 1;
                $user->save();

                return response()->json([
                    'success' => 'Payment successfull',
                    'data' => $user,
                    'status' => 200,
                ]);

            }

            return response()->json([
                'errors' => isset($payment['message']) ? $payment['message'] : 'Unable to process payment',
                'data' => $user,
                'status' => 400,
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'errors' => $e->getMessage(),
                'status' => 400,
            ]);
        }
    }

    public function unsubscribe(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'firstSixDigits' => 'required',
            'lastFourDigits' => 'required',
            'email' => 'required|exists:users,email',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
                'status' => 401,
            ]);
        }

        try {

            $user = Auth::user();

            if($user->subscription_status == 'cancel'){
                return response()->json([
                    'errors' => 'You already have a cancel subscription',
                    'status' => 400,
                ]);
            }

            $card = CardDetails::where('user_email',$request->email)
            ->where('first_six',$request->firstSixDigits)
            ->where('last_four',$request->lastFourDigits)
            ->first();

            if(!$card){
                return response()->json([
                    'errors' => 'Invalid Card Details',
                    'status' => 400,
                ]);
            }

            $user->subscription_status = 'cancel';
            $user->save();

            auth()->user()->tokens()->delete();

            return response()->json([
                'errors' => 'Subscription cancelled successfully',
                'data' => $user,
                'status' => 200,
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'errors' => $e->getMessage(),
                'status' => 400,
            ]);
        }
    }
}
