<?php

namespace GriffinForms\Admin\Html\Pages\Settings;

class License extends \GriffinForms\Admin\Html\Pages\Settings\Format
{
    protected $package_state_resolver;

    protected function setPackagestateresolver()
    {
        $this->package_state_resolver = \GriffinForms\Includes\Packages\PackageStateResolver::getInstance();
    }

    protected function getPackageStateResolver(): \GriffinForms\Includes\Packages\PackageStateResolver
    {
        if (!is_object($this->package_state_resolver)) {
            $this->setPackagestateresolver();
        }

        return $this->package_state_resolver;
    }

    protected function setJsData()
    {
        parent::setJsData();
        $this->js_data['surface'] = $this->getSurfaceModel();
    }

    public function html()
    {
        $surface = $this->getSurfaceModel();
        $alert = $this->buildAlertModel($surface);
        $freemius = is_array($surface['freemius'] ?? null) ? $surface['freemius'] : [];
        $pro_state = is_array($surface['pro_state'] ?? null) ? $surface['pro_state'] : [];

        $this->settingsTabBar();
        $this->pageNoticeError();
        $this->pageNoticeSuccess();

        echo '<div class="card" style="max-width:1040px;">';
        echo '<div class="card-body">';
        echo '<p class="description" style="max-width:860px;margin-bottom:18px;">' . esc_html__('Manage your GriffinForms Pro license, review its current status, and keep this site connected for updates and premium access.', 'griffinforms-form-builder') . '</p>';

        echo '<div class="notice notice-' . esc_attr($alert['type']) . ' inline" style="margin:0 0 18px 0;">';
        echo '<p><strong>' . esc_html($alert['title']) . '</strong> ' . esc_html($alert['message']) . '</p>';
        echo '</div>';

        echo '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:18px;margin-bottom:18px;">';
        echo '<div style="padding:18px;border:1px solid #dcdcde;border-radius:8px;background:#fff;">';
        echo '<h2 style="margin:0 0 12px 0;font-size:16px;">' . esc_html($this->lang->getText('license_status_heading')) . '</h2>';
        echo '<table class="widefat striped" style="margin:0;">';
        echo '<tbody>';
        $this->tableRowHtml($this->lang->getText('license_state_label'), $this->formatValue((string) ($freemius['license_state_label'] ?? '')));
        $this->tableRowHtml($this->lang->getText('entitlement_state_label'), $this->formatStateLabel((string) ($pro_state['entitlement_state'] ?? 'unknown')));
        $this->tableRowHtml($this->lang->getText('runtime_access_label'), $this->formatRuntimeAccessLabel((string) ($pro_state['runtime_access_state'] ?? '')));
        if (!empty($freemius['is_trial'])) {
            $this->tableRowHtml($this->lang->getText('trial_ends_label'), $this->formatDateTimeValue((string) ($freemius['license_expires_at'] ?? '')));
        } else {
            $this->tableRowHtml($this->lang->getText('license_expiry_label'), $this->formatDateTimeValue((string) ($freemius['license_expires_at'] ?? ($pro_state['license_expires_at'] ?? ''))));
        }
        echo '</tbody>';
        echo '</table>';
        echo '</div>';

        echo '<div style="padding:18px;border:1px solid #dcdcde;border-radius:8px;background:#fff;">';
        echo '<h2 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('Activation and account', 'griffinforms-form-builder') . '</h2>';
        echo '<table class="widefat striped" style="margin:0;">';
        echo '<tbody>';
        $this->tableRowHtml(__('Pro installed', 'griffinforms-form-builder'), !empty($pro_state['is_present']) ? __('Yes', 'griffinforms-form-builder') : __('No', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Pro active', 'griffinforms-form-builder'), !empty($pro_state['is_active']) ? __('Yes', 'griffinforms-form-builder') : __('No', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Compatibility', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['compatibility_state'] ?? 'unknown')));
        $this->tableRowHtml(__('Licensing provider', 'griffinforms-form-builder'), !empty($freemius['ready']) ? __('Freemius connected', 'griffinforms-form-builder') : __('Freemius unavailable', 'griffinforms-form-builder'));
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        echo '</div>';

        echo '<div style="padding:18px;border:1px solid #dcdcde;border-radius:8px;background:#fff;">';
        echo '<h2 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('License key management', 'griffinforms-form-builder') . '</h2>';
        echo '<p class="description" style="margin-bottom:16px;">' . esc_html($this->lang->getText('license_key_description')) . '</p>';

        echo '<table class="form-table griffinforms-settings-form-table" role="presentation" style="margin:0;">';
        echo '<tbody>';
        echo '<tr>';
        echo '<th scope="row"><label for="griffinforms-settings-license-licensekey">' . esc_html($this->lang->getText('license_key', 'label')) . '</label></th>';
        echo '<td>';
        echo '<div style="display:flex;flex-wrap:wrap;gap:10px;align-items:center;">';
        echo '<input type="text" id="griffinforms-settings-license-licensekey" class="regular-text" value="' . esc_attr((string) ($surface['locked_value'] ?? '')) . '" placeholder="' . esc_attr__('Enter license key', 'griffinforms-form-builder') . '" ' . (!empty($surface['input_locked']) ? 'readonly' : '') . ' ' . (empty($surface['can_activate']) ? 'disabled' : '') . ' />';
        if (!empty($surface['input_locked'])) {
            echo '<button type="button" class="button" id="griffinforms-settings-license-edit-btn">' . esc_html($this->lang->getText('edit_license_key')) . '</button>';
        }
        echo '</div>';
        echo '<p class="description" style="margin-top:8px;">' . esc_html($this->lang->getText('license_key_description')) . '</p>';
        echo '</td>';
        echo '</tr>';
        echo '</tbody>';
        echo '</table>';

        echo '<div class="gf-license-settings-actions" style="display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-top:18px;">';
        $primary_label = !empty($surface['input_locked']) ? $this->lang->getText('update_license') : $this->lang->getText('activate_license');
        echo '<button type="button" id="griffinforms-settings-license-update-btn" class="button button-primary"' . (empty($surface['can_activate']) || !empty($surface['input_locked']) ? ' disabled' : '') . '>' . esc_html($primary_label) . '</button>';
        echo '<span class="spinner" style="float:none;"></span>';

        if (!empty($freemius['account_url'])) {
            echo '<a class="button button-secondary" href="' . esc_url((string) $freemius['account_url']) . '">' . esc_html($this->lang->getText('manage_license_account')) . '</a>';
        }

        if (!empty($freemius['upgrade_url'])) {
            echo '<a class="button button-secondary" href="' . esc_url((string) $freemius['upgrade_url']) . '">' . esc_html($this->lang->getText('view_upgrade_options')) . '</a>';
        }
        echo '</div>';

        if (empty($surface['can_activate'])) {
            echo '<p class="description" style="margin-top:12px;">' . esc_html($this->lang->getText('activation_unavailable')) . '</p>';
        }

        echo '</div>';
        echo '</div>';
    }

    protected function getSurfaceModel(): array
    {
        $state = $this->getPackageStateResolver()->getState();
        $pro_state = is_array($state['packages']['pro'] ?? null) ? $state['packages']['pro'] : [];
        $freemius = $this->getFreemiusSurfaceData();
        $input_locked = !empty($freemius['license_key_masked']) && in_array((string) ($freemius['license_state'] ?? ''), ['trial', 'active', 'nearing_expiry', 'expired'], true);
        $can_activate = !empty($pro_state['is_present'])
            && !empty($pro_state['is_active'])
            && (($pro_state['compatibility_state'] ?? '') === 'compatible')
            && !empty($freemius['ready'])
            && !empty($freemius['activation_ajax_action'])
            && !empty($freemius['activation_ajax_nonce']);

        return [
            'pro_state' => $pro_state,
            'freemius' => $freemius,
            'input_locked' => $input_locked,
            'locked_value' => $input_locked ? (string) ($freemius['license_key_masked'] ?? '') : '',
            'can_activate' => $can_activate,
        ];
    }

    protected function getFreemiusSurfaceData(): array
    {
        if (!class_exists('\\GriffinFormsPro\\Includes\\Licensing\\Freemius')) {
            return [];
        }

        try {
            return \GriffinFormsPro\Includes\Licensing\Freemius::getInstance()->getSettingsSurfaceData();
        } catch (\Throwable $throwable) {
            return [];
        }
    }

    protected function buildAlertModel(array $surface): array
    {
        $freemius = is_array($surface['freemius'] ?? null) ? $surface['freemius'] : [];
        $pro_state = is_array($surface['pro_state'] ?? null) ? $surface['pro_state'] : [];

        if (!empty($freemius['alert_message'])) {
            return [
                'type' => $this->mapAlertType((string) ($freemius['alert_type'] ?? 'warning')),
                'title' => (string) ($freemius['license_state_label'] ?? __('License status', 'griffinforms-form-builder')),
                'message' => (string) $freemius['alert_message'],
            ];
        }

        if (empty($pro_state['is_present'])) {
            return [
                'type' => 'info',
                'title' => __('GriffinForms Pro is not installed', 'griffinforms-form-builder'),
                'message' => __('Install GriffinForms Pro to enable license activation and entitlement controls here.', 'griffinforms-form-builder'),
            ];
        }

        if (empty($pro_state['is_active'])) {
            return [
                'type' => 'warning',
                'title' => __('GriffinForms Pro is inactive', 'griffinforms-form-builder'),
                'message' => __('Activate GriffinForms Pro before entering or updating a license key.', 'griffinforms-form-builder'),
            ];
        }

        if (($pro_state['compatibility_state'] ?? '') !== 'compatible') {
            return [
                'type' => 'warning',
                'title' => __('Compatibility needs attention', 'griffinforms-form-builder'),
                'message' => __('Resolve the current Core and Pro compatibility issue before managing the license here.', 'griffinforms-form-builder'),
            ];
        }

        return [
            'type' => 'info',
            'title' => __('License status pending', 'griffinforms-form-builder'),
            'message' => __('Freemius has not returned a detailed license state yet.', 'griffinforms-form-builder'),
        ];
    }

    protected function tableRowHtml(string $label, string $value): void
    {
        echo '<tr>';
        echo '<th scope="row" style="width:220px;">' . esc_html($label) . '</th>';
        echo '<td>' . esc_html($value) . '</td>';
        echo '</tr>';
    }

    protected function formatValue(string $value): string
    {
        $value = trim($value);
        return $value !== '' ? $value : __('Not recorded', 'griffinforms-form-builder');
    }

    protected function formatStateLabel(string $value): string
    {
        $value = trim($value);
        if ($value === '') {
            return __('Not recorded', 'griffinforms-form-builder');
        }

        return ucwords(str_replace(['_', '-'], ' ', $value));
    }

    protected function formatRuntimeAccessLabel(string $value): string
    {
        if ($value === '') {
            return __('Not recorded', 'griffinforms-form-builder');
        }

        if ($value === 'premium_enabled') {
            return __('Premium runtime enabled', 'griffinforms-form-builder');
        }

        if ($value === 'premium_blocked') {
            return __('Premium runtime blocked', 'griffinforms-form-builder');
        }

        return $this->formatStateLabel($value);
    }

    protected function formatDateTimeValue(string $value): string
    {
        $value = trim($value);
        if ($value === '') {
            return __('Not recorded', 'griffinforms-form-builder');
        }

        $timestamp = strtotime($value);
        if ($timestamp === false) {
            return $value;
        }

        return wp_date(trim(get_option('date_format') . ' ' . get_option('time_format')), $timestamp);
    }

    protected function mapAlertType(string $value): string
    {
        $value = sanitize_key($value);
        if (in_array($value, ['success', 'info', 'warning', 'error'], true)) {
            return $value;
        }

        return 'warning';
    }
}
