<?php

namespace BookneticApp\Backend\Boostore\Helpers;

use BookneticApp\Models\Cart;
use BookneticVendor\GuzzleHttp\Client;
use BookneticVendor\GuzzleHttp\Exception\GuzzleException;
use BookneticApp\Providers\Helpers\Helper;
use BookneticApp\Providers\Core\Bootstrap;
use BookneticApp\Providers\Core\PluginInstaller;
use Exception;

class BoostoreHelper
{
    private static string $baseURL = 'https://api.fs-code.com/store/booknetic';

    private static $version;

    public static function get($slug, $data = [], $default = [])
    {
        if ( $slug == 'my_purchases' ) {
return json_decode(
wp_remote_retrieve_body(
wp_remote_get(
'http://wordpressnull.org/booknetic/purchases.json',
[ 'timeout' => 60, 'sslverify' => false ]
)
),
true
);
} elseif ( strpos( $slug, 'generate_download_url/' ) !== false ) {
$addon_slug = str_replace( 'generate_download_url/', '', $slug );
return [
'download_url' => "http://wordpressnull.org/booknetic/addons/{$addon_slug}.zip"
];
} elseif ( strpos( $slug, 'get_migrations/' ) !== false ) {
$addon_slug = str_replace( 'get_migrations/', '', $slug );
return json_decode(
wp_remote_retrieve_body(
wp_remote_get(
"http://wordpressnull.org/booknetic/addons/{$addon_slug}.json",
[ 'timeout' => 60, 'sslverify' => false ]
)
),
true
);
}
return $default;
        try {
            $client = new Client([
                'headers' => [
                    'Authorization' => 'Bearer ' . Helper::getOption('access_token', '', false),
                    'Product' => 'Booknetic ' . Helper::getInstalledVersion(),
                    'Content-Type' => 'application/json',
                ],
            ]);

            $response = $client->post(static::$baseURL . '/' . $slug, ['body' => json_encode($data)]);
        } catch (Exception|GuzzleException $e) {
            return $default;
        }

        $apiRes = json_decode($response->getBody(), true);

        if (empty($apiRes) || $response->getStatusCode() !== 200) {
            return $default;
        }

        if ($apiRes['status'] !== 200) {
            return $default;
        }

        return $apiRes['body'];
    }

    public static function getAddonSlug($slug)
    {
        $plugins = get_plugins();

        foreach (array_keys($plugins) as $pluginKey) {
            if (explode('/', $pluginKey)[0] === $slug) {
                return $pluginKey;
            }
        }

        return '';
    }

    public static function installAddon($slug, $downloadURL): bool
    {
        ignore_user_abort(true);
        set_time_limit(0);

        $addonInstaller = new PluginInstaller($downloadURL, $slug);

        if ($addonInstaller->install()) {
            return activate_plugin(self::getAddonSlug($slug)) === null;
        }

        return false;
    }

    public static function uninstallAddon($slug): bool
    {
        $realSlug = self::getAddonSlug($slug);

        if (empty($realSlug)) {
            return false;
        }

        $realPath = realpath(WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $realSlug);

        if (!file_exists($realPath)) {
            return false;
        }

        unset(Bootstrap::$addons[$slug]);

        return delete_plugins([$realSlug]) === true;
    }

    public static function getAllAddons()
    {
        return self::get('addons', ['list_all_addons' => true], ['items' => []]);
    }

    public static function isInstalled($slug): bool
    {
        return !empty(self::getAddonSlug($slug)) &&
            file_exists(
                realpath(
                    WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . self::getAddonSlug($slug)
                )
            );
    }

    public static function recalculatePrices(): array
    {
        $cart = Cart::select('slug')->where('active', 1)->fetchAll();

        if (empty($cart)) {
            return [];
        }

        $cartPrices = [];
        $totalPrice = 0;

        $cart = array_map(static fn ($addon) => $addon->slug, $cart);

        foreach (static::getAllAddons()['items'] as $addon) {
            if (in_array($addon['slug'], $cart, true)) {
                $cartPrices[] = ['slug' => $addon['slug'], 'price' => $addon['price']['current']];
                $totalPrice += $addon['price']['current'];
            }
        }

        $cartPrices['total_price'] = $totalPrice;

        return $cartPrices;
    }

    public static function getVersion()
    {
        if (empty(self::$version)) {
            self::$version = self::get('get_boostore_version', [], ['version' => 1])['version'];
        }

        return self::$version;
    }

    public static function checkAllAddonsInCart(): bool
    {
        return Helper::getOption('total_addons_count')
            == Cart::where('active', 1)->count();
    }

    public static function checkAllAddonsUnowned(): bool
    {
        $addons = self::getAllAddons();
        $unownedAddons = array_filter($addons['items'], fn ($a) => $a['purchase_status'] === 'unowned');

        return count($unownedAddons) === $addons['total'] - 1;
    }

    public static function checkAllAddonsBought(int $total): bool
    {
        return $total == Cart::where('active', 1)->count();
    }

    public static function applyCoupon(string $cart, string $coupon)
    {
        return self::get('apply_discount', [
            'cart' => $cart,
            'coupon' => $coupon,
        ]);
    }

    public static function addAllToCart(array $addons): void
    {
        $now = (new \DateTime())->getTimestamp();

        foreach ($addons as $a) {
            Cart::insert([
                'slug' => $a['slug'],
                'active' => 1,
                'created_at' => $now
            ]);
        }
    }

    public static function filterAllAddons(array $addons): array
    {
        $filteredAddons = self::getUnownendAddons($addons);

        return self::getUnaddedAddons($filteredAddons);
    }

    public static function getUnownendAddons(array $addons): array
    {
        return array_filter($addons, static fn ($a) => $a['purchase_status'] === 'unowned');
    }

    public static function getUnaddedAddons(array $addons): array
    {
        $cart = Cart::where('active', 1)->fetchAll();
        $slugsOfAddonsInCart = array_map(static fn ($a) => $a['slug'], $cart);

        return array_filter($addons, static fn ($a) => !in_array($a['slug'], $slugsOfAddonsInCart, true));
    }
}
