<?php

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

$stripe = new \Stripe\StripeClient('sk_live_wz1r8mYdFPWPPAMLDrFMrj4P');

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

try {
  // retrieve JSON from POST body
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str);
  // 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' => 1,//15
  ]);

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

  $stripe->customers->update($customerId, [
    'address' => [
      'line1' => $json_obj->line1,
      'city' =>  $json_obj->city,
      'postal_code' => $json_obj->postal_code,
      'state' => $json_obj->state,
      'country' => $json_obj->country,
    ]
  ]);

  function createSubscription($stripe, $customerId, $json_obj, $client_secret = null)
  {
    try {
      $subscription = $stripe->subscriptions->create([
        'customer' => $customerId,
        'items' => [
          [
            'price' => $json_obj->priceId,
            'metadata' => ['imei' => $json_obj->imei],
          ],
        ],
        'expand' => ['latest_invoice.payment_intent'],
        'metadata' => ['imei' => $json_obj->imei]
      ]);

      $response = [
        'data' => $subscription,
      ];

      if ($subscription->latest_invoice->payment_intent->status === 'requires_confirmation') {
        $response['client_secret'] = $subscription->latest_invoice->payment_intent->client_secret;
      }



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

  if (empty($json_obj->paymentMethodId)) {
    $customer = $stripe->customers->retrieve($customerId);
    if (empty($customer->invoice_settings->default_payment_method)) {
      echo json_encode(['error' => 'No default payment method', 'customerId' => $customerId, 'replyCode' => '200']);
      return;
    }

    $subscriptions = $stripe->subscriptions->all(['customer' => $customerId]);
    foreach ($subscriptions->data as $subscription) {
      if (isset($subscription->metadata->imei) && $subscription->metadata->imei == $json_obj->imei) {
        if ($subscription->status == 'incomplete' && $subscription->items->data[0]->price->id == $json_obj->priceId) {
          try {
            $invoice = $stripe->invoices->retrieve($subscription->latest_invoice);
            $paymentIntent = $stripe->paymentIntents->retrieve($invoice->payment_intent);
            $paymentMethod = $stripe->paymentMethods->retrieve($paymentIntent->payment_method);

            if ($paymentMethod->type == 'au_becs_debit') {
              $confirmedPaymentIntent = $stripe->paymentIntents->confirm($paymentIntent->id, [
                'payment_method' => $paymentIntent->payment_method,
                'mandate_data' => [
                  'customer_acceptance' => [
                    'type' => 'online',
                    'online' => [
                      'ip_address' => $_SERVER['REMOTE_ADDR'],
                      'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                    ],
                  ],
                ],
              ]);
            } else {
              $confirmedPaymentIntent = $stripe->paymentIntents->confirm($paymentIntent->id);
            }

            if ($confirmedPaymentIntent->status == 'succeeded') {
              $updatedSubscription = $stripe->subscriptions->retrieve($subscription->id);
              echo json_encode(['message' => "Subscription with IMEI {$json_obj->imei} activated.", 'subscription' => $updatedSubscription]);
              return;
            } else {
              echo json_encode(['error' => "Failed to complete payment for the subscription with IMEI {$json_obj->imei}."]);
              return;
            }
          } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
            return;
          }
        } elseif ($subscription->status == 'active' && $subscription->items->data[0]->price->id == $json_obj->priceId) {
          echo json_encode(["error" => "Subscription with IMEI {$json_obj->imei} already exists", 'replyCode' => '500']);
          return;
        }
      }
    }

    createSubscription($stripe, $customerId, $json_obj);

    
  } else {
    try {
      $payment_method = $stripe->paymentMethods->retrieve($json_obj->paymentMethodId);
      $payment_method->attach(['customer' => $customerId]);

      $stripe->customers->update($customerId, [
        'invoice_settings' => [
          'default_payment_method' => $json_obj->paymentMethodId,
          'custom_fields' => [
            [
              'name' => 'IMEI',
              'value' => $json_obj->imei
            ]
          ]
        ]
      ]);

      if ($payment_method->type === 'au_becs_debit') {
        $setup_intent = $stripe->setupIntents->update($json_obj->setupIntentId, ['expand' => ['mandate']]);
        $client_secret = $setup_intent->client_secret;
        createSubscription($stripe, $customerId, $json_obj, $client_secret);
      } else {
        createSubscription($stripe, $customerId, $json_obj);
      }
    } catch (\Stripe\Exception\CardException $e) {
      echo json_encode(['error' => $e->getError()->message]);
      exit;
    } catch (Error $e) {
      http_response_code(500);
      echo json_encode(['error' => $e->getMessage()]);
    }
  }
} catch (Error $e) {
  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
}

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