<?php
namespace PayCal\Admin;

defined('ABSPATH') || exit;

use PayCal\Licensing\Gate;
use PayCal\Licensing\LicenseClient;
use PayCal\Licensing\LicenseStore;
use PayCal\Permissions\Access;

class Page_License {
  public static function render(): void {
    Access::enforce('license');

    $msg = '';
    $err = '';

    $paycal_action = isset($_POST['paycal_action']) ? sanitize_key(wp_unslash($_POST['paycal_action'])) : '';
    if ($paycal_action === 'save_license') {
      check_admin_referer('paycal_save_license');

      $key = sanitize_text_field(wp_unslash($_POST['license_key'] ?? ''));

      if (!$key) {
        $err = 'Please enter a License Token for optional commercial modules, or leave this blank if you do not use licensed modules.';
      } else {
        $res = LicenseClient::validate_remote($key);
        if (!empty($res['ok'])) {
          LicenseStore::set($res['data']);
          $msg = 'License Token verified and saved.';
        } elseif (LicenseClient::looks_like_connector_credential($key)) {
          $err = 'זה נראה כמו נתון חיבור של PayCal, לא מפתח רישוי. יש להזין אותו בהגדרות Merchant / Terminal.';
        } elseif (($res['reason'] ?? '') === 'invalid') {
          LicenseStore::set([
            'license_key' => $key,
            'valid' => false,
            'plan' => '',
            'modules' => [],
            'expires_at' => '',
            'validated_at' => time(),
            'grace_until' => time() + (7 * DAY_IN_SECONDS),
          ]);
          $err = 'License Token verification failed: ' . sanitize_text_field((string) ($res['error'] ?? 'Unknown error'));
        } else {
          $err = 'License Token verification could not be completed: ' . sanitize_text_field((string) ($res['error'] ?? 'Unknown error')) . '. Existing connection status was preserved.';
        }
      }
    }

    $data = LicenseStore::get();
    $stored_key = (string) ($data['license_key'] ?? '');
    $stored_connector_credential = $stored_key !== '' && LicenseClient::looks_like_connector_credential($stored_key);
    if ($stored_connector_credential) {
      $data['license_key'] = '';
      $data['valid'] = false;
      $data['modules'] = [];
      $data['expires_at'] = '';
      $data['grace_until'] = 0;
      LicenseStore::set($data);
      $stored_key = '';
      if (!$err) {
        $err = 'זה נראה כמו נתון חיבור של PayCal, לא מפתח רישוי. יש להזין אותו בהגדרות Merchant / Terminal.';
      }
    }
    $raw_status = class_exists(Gate::class) ? Gate::status_label() : 'לא מחובר';
    $status_text = in_array($raw_status, ['Pending verification', 'Disabled'], true) ? 'לא מחובר' : $raw_status;
    $expires = (string) ($data['expires_at'] ?? '');

    echo '<div class="wrap paycal-wrap">';
    echo '<div class="paycal-header"><h1>רישוי</h1><p>מפתחות רישוי נדרשים רק להפעלת מודולים מסחריים אופציונליים. נתוני חיבור התשלום מנוהלים בנפרד.</p></div>';

    if ($msg) echo '<div class="notice notice-success"><p>' . esc_html($msg) . '</p></div>';
    if ($err) echo '<div class="notice notice-error"><p>' . esc_html($err) . '</p></div>';

    echo '<div class="paycal-card">';
    echo '<h2>רישוי</h2>';
    echo '<p><strong>' . esc_html($status_text) . '</strong></p>';
    if ($raw_status === 'Grace period') {
      echo '<p class="description">Optional commercial modules are not fully licensed. Core connector and admin access remain available.</p>';
    }
    if ($expires) echo '<p><strong>Expires:</strong> ' . esc_html($expires) . '</p>';
    echo '<p class="description">מפתחות רישוי נדרשים רק להפעלת מודולים מסחריים אופציונליים. נתוני חיבור התשלום מנוהלים בנפרד.</p>';

    echo '<form method="post">';
    wp_nonce_field('paycal_save_license');
    echo '<input type="hidden" name="paycal_action" value="save_license" />';
    echo '<div class="paycal-field" style="max-width:560px">';
    echo '<label for="license_key">License Token</label>';
    echo '<input id="license_key" name="license_key" type="text" value="' . esc_attr($stored_key) . '" placeholder="lic_... only, not mrc_/trm_/pk_" />';
    echo '<p class="description">License Tokens are only for optional commercial modules. Merchant ID, Terminal ID and Public Key belong in Merchant / Terminal settings.</p>';
    echo '</div>';
    echo '<p><a href="' . esc_url(admin_url('admin.php?page=paycal-connector')) . '">Open Merchant/Terminal settings</a></p>';
    echo '<p class="submit"><button class="button button-primary">Verify License Token</button></p>';
    echo '</form>';

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