<?php
if (is_file(realpath('../system/stripe-php/init.php'))) {
  require_once(realpath('../system/stripe-php/init.php'));
}

ini_set('session.cookie_domain', '.gps-secure.co');
session_start();  
$sessionId = session_id();

//live sino api key
$stripe = new \Stripe\StripeClient('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');
//test sino api key
//~~$stripe = new \Stripe\StripeClient('sk_test_51PLp3nS57Lf5UNnaUNmTokcQTUj84etoSTOYUZZUKvpFxq7BNCYkFvOSadVkD53yTbO2AUG6wK11S3ikm4KbgffO00kQ2IlvTH');

//live AUD M2M
//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

//test atga api key
//$stripe = new \Stripe\StripeClient('sk_test_BASyqpeCGChFOtP0CpXG2bc3');
//live atga api key
//$stripe = new \Stripe\StripeClient('sk_live_wz1r8mYdFPWPPAMLDrFMrj4P');

\Stripe\Stripe::setApiKey('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');
//~~\Stripe\Stripe::setApiKey('sk_test_51PLp3nS57Lf5UNnaUNmTokcQTUj84etoSTOYUZZUKvpFxq7BNCYkFvOSadVkD53yTbO2AUG6wK11S3ikm4KbgffO00kQ2IlvTH');

header('Content-Type: application/json');

try {
  // retrieve JSON from POST body
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str, true);
 

  $_SESSION['formData'] = [
     'email' => $json_obj['email'],
     'imei' => $json_obj['imei'],
     'firstName' => $json_obj['firstName'],
     'devices' => $json_obj['devices'],
    'address' => $json_obj['address'],
    'city'  => $json_obj['city'],
    'region' => $json_obj['region'], 
    'zipCode' => $json_obj['zipCode'],  
     'price' => $json_obj['price'],
    'account' => $json_obj['account'],
    'phone' => $json_obj['phone'],
     'deviceName' => $json_obj['deviceName'], 
     'operatorType' => $json_obj['operatorType'], 
     'extraPayment' => $json_obj['extraPayment'], 
     'extraPaymentType' => $json_obj['extraPaymentType'], 
     'extraPlanDays' => $json_obj['extraPlanDays'], 
     'extraPlanPrice' => $json_obj['extraPlanPrice'], 
     'extraWarranty' => $json_obj['extraWarranty'], 
     'extraWarrantyPrice' => $json_obj['extraWarrantyPrice'], 
     'stripeAccount' => $json_obj['stripeAccount'], 
     'operatorCode' => $json_obj['operatorCode'], 
     'dealerName' => $json_obj['dealerName'], 
   ];


   
  // Alternatively, set up a webhook to listen for the payment_intent.succeeded event
  // and attach the PaymentMethod to a new Customer
  $customers = $stripe->customers->all(['email'=>$json_obj['email'],
    'limit' => 15,
  ]);

  if(empty($customers->data)){
    $customerId = createNewStripUser([
      'email' => $json_obj['email'],
      'firstName' => $json_obj['firstName'],
      'lastName' => $json_obj['subName'],
    
    ]);
  }else{
    $customerId = $customers->data[0]->id;
  }

  try {
 
    $line_items = array_map(function ($item) {
        return [
            'price_data' => [
                'currency' => 'usd',
                'product_data' => [
                    'name' => $item['deviceName'],
                ],
                'unit_amount' => $item['price'] *  100,
            ],
            'quantity' => $item['quantity'],
        ];
    }, $json_obj['devices']);

    $session = \Stripe\Checkout\Session::create([
        'payment_method_types' => ['card'],
        'line_items' => $line_items,
        'mode' => 'payment',
        'success_url' => 'https://forms.sinopacific.co/quiktrak/registration/success/?sid=' . $sessionId,
        'cancel_url' => 'https://activation.quiktrak.co/',
        // 'automatic_tax' => [
        //   'enabled' => true,
        //   'liability' => [
        //       'type' => 'self',
        //       ],
        // ],
    ]);


    $stripe->checkout->sessions->retrieve(
      $session->id,
      []
    );
    echo json_encode(['id' => $session]);

} catch (\Stripe\Exception\ApiErrorException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
    exit;
} catch (\Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
    exit;
} catch (\Error $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getError()]);
    exit;
}



 
} catch (Error $e) {
  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
}



function getTotalOrderAmount(array $items) {
  global $stripe;
  $currency = 'usd';
  $amount = 0;
  foreach ($items as $key => $value){
    $stripeItemPrice = $stripe->prices->retrieve(
      $value->priceId,
      []
    );
    $currency = $stripeItemPrice->currency;
    $amount .= $stripeItemPrice->unit_amount;
  }
  return ['amount' => $amount, 'currency' => $currency];
}

function createNewStripUser($data){
  global $stripe;
  $response = $stripe->customers->create([
    'email' => $data['email'],
    'name' => $data['firstName'] . " " . $data['lastName'],
   ]);
  return $response->id;
}