<?php

namespace HelpGent\App\Licensing;

defined( 'ABSPATH' ) || exit;

use Exception;
use HelpGent\App\Repositories\SettingsRepository;

class License {
    public SettingsRepository $settings_repository;

    public array $config;

    public function __construct( SettingsRepository $settings_repository ) {
        $this->settings_repository = $settings_repository;

        $this->config = helpgent_config( 'license' );
    }

    public function get_access_token(): string {
        $license = $this->settings_repository->get_by_key( 'license' );

        if ( empty( $license ) ) {
            return '';
        }

        try {
            if ( $this->is_expired( $license['access_token'] ) ) {
                return $this->refresh_token( $license['refresh_token'] );
            }
        } catch ( Exception $e ) {
            return '';
        }

        return $license['access_token'];
    }

    /**
     * @throws Exception
     */
    public function is_expired( string $access_token ): bool {
        $url = $this->config['api_base_url'] . "/auth/token-info?access_token={$access_token}";

        $response = wp_remote_get(
            $url, [
                'headers' => [
                    'hg-website' => get_home_url(),
                ],
            ] 
        );
        
        if ( is_wp_error( $response ) ) {
            throw new Exception( $response->get_error_message() );
        }

        $status_code = wp_remote_retrieve_response_code( $response );

        if ( 404 === absint( $status_code ) ) {
            return true;
        }

        if ( 200 !== $status_code ) {
            throw new Exception( __( 'Something went wrong! please try again', 'helpgent' ) );
        }

        $data = json_decode( wp_remote_retrieve_body( $response ), true );

        return ( bool ) $data['is_expired'];
    }
    
    public function refresh_token( string $refresh_token ): string {
        $url = $this->config['api_base_url'] . "/auth/refresh-access-token";

        $response = wp_remote_post(
            $url, [
                'body'    => json_encode(
                    [
                        'refresh_token' => $refresh_token,
                    ] 
                ),
                'headers' => [
                    'Content-Type' => 'application/json',
                    'hg-website'   => get_home_url(),
                ],
            ] 
        );
        
        if ( is_wp_error( $response ) ) {
            throw new Exception( $response->get_error_message() );
        }

        $status_code = wp_remote_retrieve_response_code( $response );

        if ( 200 !== absint( $status_code ) ) {
            throw new Exception( __( 'Something went wrong! please try again', 'helpgent' ) );
        }

        $data = json_decode( wp_remote_retrieve_body( $response ), true );

        $this->settings_repository->update_setting(
            'license', [
                'access_token'  => $data['access_token'],
                'refresh_token' => $refresh_token,
            ] 
        );

        return $data['access_token'];
    }

    public function get_config(): array {
        return array_merge(
            $this->config,
            [ 'access_token' => $this->get_access_token() ] 
        );
    }
}