<?php

namespace apexl\Io\modules\product\services;

use apexl\Config\Singleton;
use apexl\Io\includes\Routes;
use apexl\Io\includes\System;
use apexl\Io\modules\payment\entities\invoiceEntity;
use apexl\Io\modules\payment\entities\paymentEntity;
use apexl\Io\modules\payment\entities\userCreditEntity;
use apexl\Io\modules\payment\providers\stripeProvider;
use apexl\Io\modules\payment\services\cardValidationService;
use apexl\Io\modules\payment\services\paymentService;
use apexl\Io\modules\product\entities\productEntity;
use apexl\Io\modules\product\entities\productRemoteReferenceIdsEntity;
use apexl\Io\modules\subscription\entities\subscriptionCreditEntity;
use apexl\Io\modules\subscription\entities\subscriptionEntity;
use apexl\Io\modules\user\entities\userEntity;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class productService {

    protected $config;

    public function __construct()
    {
        $this->config = Singleton::getInstance();
    }

    public function getProductsFromTokenData($data)
    {
        $productEntities = [];

        if (isset($data->products) && is_array($data->products)) { //i.e. if this is a woocommerce order
            $productRemoteReferenceIdsEntity = new productRemoteReferenceIdsEntity();

            foreach ($data->products as $product) {
                if (isset($product->product_id)) {
                    $productId = $productRemoteReferenceIdsEntity->getProductIdUsingRemoteReferenceId($product->product_id); // Get Dashboard product ID from Woo Product ID
                    $productEntity = new productEntity();
                    $productEntity->load($productId);
                    $productEntities[] = $productEntity;
                } elseif (isset($product->product_name)) { // If no ID provided, load by name
                    $productEntity->loadByName($product->product_name);
                    if (!isset($productEntity->id) || !$productEntity) { // Automatically create new product if it doesn't exist
                        $productEntity = new productEntity();
                        $productEntity->type = $product->type ?? "";
                        $productEntity->product_name = $product->product_name;
                        $productEntity->price = $product->price ?? 0;
                        $productEntity->code = $product->code ?? "";
                        $productEntity->created = time();
                        $productEntity->store();
                    }
                    $productEntities[] = $productEntity;
                } else if (isset($product->dashboardProductId)) {
                    $productId = $product->dashboardProductId;
                }
            }
        } elseif (isset($data->productId)) { // None-woocommerce order - may be extinct now? Not sure...
            $productId = $data->productId;
        }
    }

}