<?php

namespace App\Services;

use Stripe\Stripe;
use Stripe\Account;
use Stripe\AccountLink;
use Stripe\Transfer;

class StripeService
{
    // public function __construct()
    // {
    //     Stripe::setApiKey(env('STRIPE_SECRET'));
    // }

    public function createConnectAccount($firstName,$lastName,$phoneNumber,$email,$dob,$accountHolderName,$accountNumber,$routingNumber){
        
	 $stripe = new \Stripe\StripeClient(config('app.stripe.secret_key'));
	 
		try{
			$TokenInfo = $stripe->tokens->create(array(
				"bank_account" => array(
					"country" => env('COUNTRY'),
					"currency" => env('CURRENECY'),
					"account_holder_name" => $accountHolderName,
					"account_holder_type" => "individual",
					"routing_number" => $routingNumber,
					"account_number" => $accountNumber
				)
			));
		 $TokenId=$TokenInfo->id;
			
			if($TokenId){
				$array =  $this->arrayOfConnectAccount($firstName,$lastName,$phoneNumber,$email,$dob);
				
				$Account=$stripe->accounts->create($array);
			   
				$accountId=$Account->id;
				
				if($accountId){
					$external_account = $stripe->accounts->createExternalAccount($accountId,['external_account' => $TokenId]);
				//   $accountDetail  = $this->createFileVerificationId($accountId,$filename);
				}
			}
			$response = array("success"=>1,"accountID"=>$accountId);
		}
		catch (Exception $e) {
            $messages=$e->getError()->message;
            $response = array("success"=>0,"message"=>$messages);
        }
        return $response;
    }
    
     public function arrayOfConnectAccount($firstName,$lastName,$phoneNumber,$email,$dob){
        $dobD = explode("-",$dob);
     
        $array =  [
            'type' => env('CONNECTED_ACCOUNT_TYPE'),
            'country' => env('COUNTRY'),
            'email' => $email,
            'business_type' => 'individual',
            'capabilities' => [
                'card_payments' => ['requested' => true],
                'transfers' => ['requested' => true],
            ],
            "business_profile" => [
                "url"=> env('BUSINESS_URL'),
                "mcc"=> env('MCC')
            ],
            "individual" => [
                "first_name"  => $firstName,
                "last_name" => $lastName,
                "email" => $email,
                "phone" => $phoneNumber,
                // "ssn_last_4" => 5678,
                "address" => [
                    "city" => "Singapore",          
                    "country" => "SG",              
                    "line1" => "10 Anson Road",      
                    "line2" => "International Plaza", 
                    "postal_code" => "079903"       
                ],
                'dob' => [
                    'day' => $dobD[2],
                    'month' => $dobD[1],
                    'year' => $dobD[0],
                ],
            ],
            "tos_acceptance" =>[
                "date"=> time(),
                "ip"=> $_SERVER['REMOTE_ADDR'],
                "user_agent"=> null
            ],
        ];
        return $array;
    }
    
     public function createFileVerificationId($accountId,$filename){
	    
	    //$filename = explode('/',$filename);
	  $stripe = new \Stripe\StripeClient(config('app.stripe.secret_key'));
        $file = $stripe->files->create([
            'purpose' => 'identity_document',
            'file' => fopen('public/uploads/user_docs/'.$filename, 'r'),
            ], [
            'stripe_account' => $accountId,
        ]);
          $fileID = $file->id;
       
        if($fileID){
            $account = $stripe->accounts->update($accountId,[
				"individual" => [
					"verification"=> [
					"document"=> [
					"back"=> null,
					//"details"=> null,
					//"details_code"=> null,
					"front"=> $fileID
				],
				],
            ]
			]);
            return $account;
        }
    }
    
    
    public function createCustomer($email=null, $name=null, $customer_id=null)
	{
        try
        {
            $stripe = new \Stripe\StripeClient(config('app.stripe.secret_key'));
            
          
            if(!empty($customer_id)) {
                $customer_id = $customer_id;
            } else {
                 
                if(!empty($email) && !empty($name)) {
                    $customer = $stripe->customers->create([
                        'email' => $email, 
                        'name' => $name,
                    ]);
                    $customer_id = $customer->id;
                } else {
                    $customer = $stripe->customers->create();
                    $customer_id = $customer->id;
                }
            }
     
            $PaymentMethod=$stripe->paymentMethods->all([
              'customer' => $customer_id,
              'type' => 'card',
            ]);
            $pid = (!empty($PaymentMethod->data))?$PaymentMethod->data[0]->id:0;
  
           
            
            $data=$stripe->checkout->sessions->create([
                'payment_method_types' => ['card'],
                'mode' => 'setup',
                'customer' => $customer_id,
                'success_url' => URL::to('/').'/success?session_id={CHECKOUT_SESSION_ID}',
                'cancel_url' => URL::to('/').'/cancel',
            ]);
            
            $response = ["success"=>1, "SessionUrl"=>$data->url, 'customer_id'=>$customer_id,];
        }catch (\Exception $ex){
            $response = ["success"=>0, "message"=>[$ex->getMessage()]];
        }
        return $response;
    }
    
    public function CancelPaymentIntent($paymentIntentId)
    {   
        try {
            $stripe = new \Stripe\StripeClient(config('app.stripe.secret_key'));
            
            $cancelPayment =  $stripe->paymentIntents->cancel($paymentIntentId, []);
          
            
          
            $response = ["success"=>1, "canceledPayment"=>$cancelPayment];
        } catch(\Exception $e) {
            $response = ["success"=>0, "message"=>$e->getMessage()];
        }
        return $response;
    }
    
    public function CapturePaymentIntent($payload)
    {   
        try {
            $stripe = new \Stripe\StripeClient(config('app.stripe.secret_key'));
            
            // $cancelPayment =  $stripe->paymentIntents->cancel($paymentIntentId, []);
             $capturePayment =  $stripe->paymentIntents->capture($payload['paymentIntentId'], [
                 'amount_to_capture' => $payload['amount_to_capture']
                 ]);
             
            
          
            $response = ["success"=>1, "capturedPayment"=> $capturePayment];
        } catch(\Exception $e) {
            $response = ["success"=>0, "message"=>$e->getMessage()];
        }
        return $response;
    }


}
