<?php

namespace BitApps\PiPro\src\Integrations\Stripe;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

use BitApps\PiPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

class StripeHelper
{
    private const BASE_URL = 'https://api.stripe.com/v1';

    private $http;

    private $headers;

    public function __construct($headers)
    {
        $this->http = new HttpClient();
        $this->headers = $headers;
    }

    public function createCustomer($data, $metaData)
    {
        $url = self::BASE_URL . '/customers';
        $payload = $this->fetchCustomerInfo($data, $metaData);
        $response = $this->http->request($url, 'POST', http_build_query($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function cancelSubscription($data)
    {
        $url = self::BASE_URL . '/subscriptions/' . $data['subscription_id'];
        $response = $this->http->request($url, 'DELETE', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => $data,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrieveCustomer($data)
    {
        $url = add_query_arg('email', $data['email'], self::BASE_URL . '/customers');

        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => $data,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrieveCustomerById($customerId)
    {
        $url = self::BASE_URL . '/customers/' . $customerId;
        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrieveBalance($data)
    {
        $url = self::BASE_URL . '/balance';
        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => $data,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrievePrice($data)
    {
        $url = self::BASE_URL . '/prices';
        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => $data,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrieveSubscription($data)
    {
        $url = self::BASE_URL . '/subscriptions';
        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => $data,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrieveSubscriptionById($subscriptionId)
    {
        $url = self::BASE_URL . '/subscriptions/' . $subscriptionId;
        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function retrieveSubscriptionCustomerId($customerId)
    {
        $url = self::BASE_URL . '/subscriptions?customer=' . $customerId;
        $response = $this->http->request($url, 'GET', null, $this->headers);

        return [
            'response'    => $response,
            'payload'     => [],
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function createProduct($data, $metaData)
    {
        $payload = [
            'name'        => $data['name'],
            'description' => $data['description']
        ];
        if (!empty($data['type'])) {
            $payload['type'] = $data['type'];
        }

        $payload['metadata'] = $this->getMetaData($metaData);
        $url = self::BASE_URL . '/products';
        $response = $this->http->request($url, 'POST', http_build_query($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function createSubscription($data, $metaData)
    {
        $subscriptionData = [
            'customer' => $data['customer_id'],
            'items'    => [
                ['price' => $data['price_id']],
            ]
        ];
        $payload['metadata'] = $this->getMetaData($metaData);
        $url = self::BASE_URL . '/subscriptions';
        $response = $this->http->request($url, 'POST', http_build_query($subscriptionData), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $subscriptionData,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function createInvoice($payload, $metaData)
    {
        $payload['metadata'] = $this->getMetaData($metaData);
        $url = self::BASE_URL . '/invoices';
        $response = $this->http->request($url, 'POST', http_build_query($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    public function createPaymentIntent($payload, $metaData)
    {
        $payload['metadata'] = $this->getMetaData($metaData);
        $url = self::BASE_URL . '/payment_intents';
        $response = $this->http->request($url, 'POST', http_build_query($payload), $this->headers);

        return [
            'response'    => $response,
            'payload'     => $payload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    private function getMetaData($metaData)
    {
        $metadataInfo = [];
        foreach ($metaData as $item) {
            if (isset($item['key'], $item['value'])) {
                $metadataInfo[$item['key']] = $item['value'];
            }
        }

        return $metadataInfo;
    }

    private function fetchCustomerInfo($data, $metaData)
    {
        if (empty($data)) {
            return [];
        }

        return [
            'name'        => $data['name'] ?? '',
            'description' => $data['description'] ?? '',
            'email'       => $data['email'] ?? '',
            'phone'       => $data['phone'] ?? '',
            'address'     => [
                'line1'       => $data['address-line1'] ?? '',
                'line2'       => $data['address-line2'] ?? '',
                'city'        => $data['city'] ?? '',
                'state'       => $data['state'] ?? '',
                'postal_code' => $data['postal-code'] ?? '',
                'country'     => $data['country'] ?? ''
            ],
            'metadata' => $this->getMetaData($metaData)
        ];
    }
}
