<?php
namespace PayCal\Admin;

defined('ABSPATH') || exit;

use PayCal\Connector\ConnectorStore;
use PayCal\Connector\EventClient;
use PayCal\Licensing\Gate;
use PayCal\Licensing\LicenseClient;
use PayCal\Licensing\LicenseStore;
use PayCal\Permissions\Access;

class Page_Wizard {
  public static function render(): void {
    Access::enforce('setup');

    $step = isset($_GET['step']) ? sanitize_key(wp_unslash($_GET['step'])) : 'welcome';
    $msg = '';
    $err = '';

    if (isset($_POST['paycal_wizard_action'])) {
      check_admin_referer('paycal_wizard');
      $action = sanitize_key(wp_unslash($_POST['paycal_wizard_action']));

      if ($action === 'save_connector') {
        ConnectorStore::save([
          'merchant_id' => sanitize_text_field(wp_unslash($_POST['merchant_id'] ?? '')),
          'terminal_id' => sanitize_text_field(wp_unslash($_POST['terminal_id'] ?? '')),
          'public_key' => sanitize_text_field(wp_unslash($_POST['public_key'] ?? '')),
        ]);
        if (class_exists(EventClient::class)) {
          EventClient::send('plugin.settings_saved', [
            'last_connection_result' => 'wizard settings saved',
            'last_sync' => current_time('mysql'),
          ]);
        }
        wp_safe_redirect(admin_url('admin.php?page=paycal-setup&step=license'));
        exit;
      }

      if ($action === 'save_license') {
        $key = sanitize_text_field(wp_unslash($_POST['license_key'] ?? ''));
        if ($key === '') {
          wp_safe_redirect(admin_url('admin.php?page=paycal-setup&step=modules'));
          exit;
        }

        $res = LicenseClient::validate_remote($key);
        if (!empty($res['ok'])) {
          LicenseStore::set($res['data']);
          wp_safe_redirect(admin_url('admin.php?page=paycal-setup&step=modules'));
          exit;
        }

        if (LicenseClient::looks_like_connector_credential($key)) {
          $err = 'זה נראה כמו נתון חיבור של PayCal, לא מפתח רישוי. יש להזין אותו בהגדרות Merchant / Terminal.';
        } else {
          $err = 'License verification failed: ' . sanitize_text_field((string) ($res['error'] ?? 'Unknown error'));
        }
      }

      if ($action === 'skip_license') {
        wp_safe_redirect(admin_url('admin.php?page=paycal-setup&step=modules'));
        exit;
      }

      if ($action === 'save_bit') {
        $phone = preg_replace('/\D+/', '', sanitize_text_field(wp_unslash($_POST['bit_phone'] ?? '')));
        $display = sanitize_text_field(wp_unslash($_POST['bit_display_name'] ?? ''));
        $note = sanitize_textarea_field(wp_unslash($_POST['bit_note'] ?? ''));

        if (strlen($phone) < 9) {
          $err = 'The Bit phone number looks too short. Check that you entered a valid phone number.';
        } else {
          \PayCal\Modules\Bit\BitSettings::set([
            'phone' => $phone,
            'display_name' => $display,
            'note' => $note,
          ]);
          wp_safe_redirect(admin_url('admin.php?page=paycal-setup&step=finish'));
          exit;
        }
      }

      if ($action === 'finish') {
        $msg = 'Setup is complete.';
      }
    }

    echo '<div class="wrap paycal-wrap paycal-wizard">';
    echo '<div class="paycal-header"><h1>PayCal Setup Wizard</h1><p>Connect payment credentials, optionally activate commercial modules, then finish setup.</p></div>';

    self::steps_nav($step);

    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">';

    if ($step === 'welcome') {
      echo '<h2>Welcome</h2>';
      echo '<p class="paycal-muted">This wizard connects the store to PayCal branded checkout and separates payment connector credentials from optional commercial license tokens.</p>';
      echo '<a class="paycal-btn-primary" href="' . esc_url(admin_url('admin.php?page=paycal-setup&step=merchant')) . '">Start setup</a>';
    }

    if ($step === 'merchant') {
      $settings = ConnectorStore::get();
      echo '<h2>Merchant / Terminal</h2>';
      echo '<p class="paycal-muted">These are payment connector credentials. They are not license keys.</p>';
      echo '<form method="post">';
      wp_nonce_field('paycal_wizard');
      echo '<input type="hidden" name="paycal_wizard_action" value="save_connector" />';
      echo '<div class="paycal-field" style="max-width:560px"><label>Merchant ID</label><input name="merchant_id" type="text" value="' . esc_attr($settings['merchant_id']) . '" placeholder="mrc_..." /></div>';
      echo '<div class="paycal-field" style="max-width:560px"><label>Terminal ID</label><input name="terminal_id" type="text" value="' . esc_attr($settings['terminal_id']) . '" placeholder="trm_..." /></div>';
      echo '<div class="paycal-field" style="max-width:560px"><label>Public Key</label><input name="public_key" type="text" value="' . esc_attr($settings['public_key']) . '" placeholder="pk_..." /></div>';
      echo '<p class="submit"><button class="button button-primary">Save and continue</button></p>';
      echo '</form>';
    }

    if ($step === 'license') {
      $data = LicenseStore::get();
      $stored_key = (string) ($data['license_key'] ?? '');
      $looks_like_connector = $stored_key !== '' && LicenseClient::looks_like_connector_credential($stored_key);
      $key_val = $looks_like_connector ? '' : $stored_key;

      if ($looks_like_connector) {
        echo '<div class="notice notice-warning"><p>' . esc_html__('זה נראה כמו נתון חיבור של PayCal, לא מפתח רישוי. יש להזין אותו בהגדרות Merchant / Terminal.', 'klamra-paycal-for-aspaclaria') . '</p></div>';
      }

      echo '<h2>License Token - optional</h2>';
      echo '<p class="paycal-muted">מפתחות רישוי נדרשים רק להפעלת מודולים מסחריים אופציונליים. נתוני חיבור התשלום מנוהלים בנפרד.</p>';
      echo '<form method="post">';
      wp_nonce_field('paycal_wizard');
      echo '<input type="hidden" name="paycal_wizard_action" value="save_license" />';
      echo '<div class="paycal-field" style="max-width:560px">';
      echo '<label>License Token</label>';
      echo '<input name="license_key" type="text" value="' . esc_attr($key_val) . '" placeholder="lic_... only, not mrc_/trm_/pk_" />';
      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 and continue</button></p>';
      echo '</form>';
      echo '<form method="post">';
      wp_nonce_field('paycal_wizard');
      echo '<input type="hidden" name="paycal_wizard_action" value="skip_license" />';
      echo '<p class="submit"><button class="button">Continue without license</button></p>';
      echo '</form>';
    }

    if ($step === 'modules') {
      $mods = LicenseStore::entitlements();
      echo '<h2>Modules</h2>';
      if (empty($mods)) {
        echo '<p class="paycal-muted">No optional commercial modules are currently licensed. Core connector and invoice admin access remain available.</p>';
      } else {
        echo '<p>Licensed optional modules:</p><ul class="paycal-bullets">';
        foreach ($mods as $m) echo '<li>' . esc_html($m) . '</li>';
        echo '</ul>';
      }
      echo '<p><a class="button button-primary" href="' . esc_url(admin_url('admin.php?page=paycal-setup&step=bit')) . '">Continue to Bit Setup</a> ';
      echo '<a class="button" href="' . esc_url(admin_url('admin.php?page=paycal-setup&step=finish')) . '">Skip Bit Setup</a></p>';
    }

    if ($step === 'bit') {
      if (!Gate::has('bit')) {
        echo '<h2>Bit Setup</h2>';
        echo '<p class="paycal-muted">Bit is an optional commercial module and is not currently licensed.</p>';
        echo '<p><a class="button button-primary" href="' . esc_url(admin_url('admin.php?page=paycal-setup&step=finish')) . '">Continue to finish</a> ';
        echo '<a class="button" href="'.esc_url(admin_url('admin.php?page=paycal-bundles')).'">Marketplace</a></p>';
      } else {
        $s = \PayCal\Modules\Bit\BitSettings::get();
        $phone = (string) ($s['phone'] ?? '');
        $display = (string) ($s['display_name'] ?? '');
        $note = (string) ($s['note'] ?? 'Transfer with Bit according to the order total. After payment, the order will be reviewed.');

        echo '<h2>Bit Setup</h2>';
        echo '<div class="paycal-two-col">';
        echo '<div class="paycal-card">';
        echo '<h2>Payment receiving details</h2>';
        echo '<form method="post">';
        wp_nonce_field('paycal_wizard');
        echo '<input type="hidden" name="paycal_wizard_action" value="save_bit" />';
        echo '<div class="paycal-field" style="margin-bottom:12px"><label>Bit phone</label><input name="bit_phone" id="paycal_bit_phone" type="text" value="'.esc_attr($phone).'" placeholder="05XXXXXXXX" /></div>';
        echo '<div class="paycal-field" style="margin-bottom:12px"><label>Display name</label><input name="bit_display_name" id="paycal_bit_display" type="text" value="'.esc_attr($display).'" /></div>';
        echo '<div class="paycal-field" style="margin-bottom:12px"><label>Customer instructions</label><textarea name="bit_note" rows="4" id="paycal_bit_note">'.esc_textarea($note).'</textarea></div>';
        echo '<p class="submit" style="margin-top:14px"><button class="button button-primary">Save and continue</button></p>';
        echo '</form>';
        echo '</div>';
        echo '<div class="paycal-card"><h2>Preview</h2><div class="paycal-qr"><div id="paycal_qr_box" data-phone="'.esc_attr($phone).'"></div></div></div>';
        echo '</div>';
      }
    }

    if ($step === 'finish') {
      echo '<h2>Finish</h2>';
      echo '<p class="paycal-muted">Setup is ready. You can return to the dashboard or adjust settings at any time.</p>';
      echo '<form method="post">';
      wp_nonce_field('paycal_wizard');
      echo '<input type="hidden" name="paycal_wizard_action" value="finish" />';
      echo '<p class="submit"><button class="button button-primary">Finish</button></p>';
      echo '</form>';
      echo '<p><a class="button" href="'.esc_url(admin_url('admin.php?page=paycal-dashboard')).'">Back to dashboard</a></p>';
    }

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

  private static function steps_nav(string $current): void {
    $steps = [
      'welcome' => 'Welcome',
      'merchant' => 'Merchant / Terminal',
      'license' => 'License - optional',
      'modules' => 'Modules',
      'bit' => 'Bit Setup',
      'finish' => 'Finish',
    ];

    echo '<div class="paycal-steps">';
    foreach ($steps as $slug => $label) {
      $class = ($slug === $current) ? 'paycal-step is-active' : 'paycal-step';
      $url = admin_url('admin.php?page=paycal-setup&step=' . $slug);
      echo '<a class="'.esc_attr($class).'" href="'.esc_url($url).'">'.esc_html($label).'</a>';
    }
    echo '</div>';
  }
}
