<?php
namespace PayCal\Admin;

defined('ABSPATH') || exit;

use PayCal\Connector\ConnectorStore;
use PayCal\Connector\EventClient;
use PayCal\Connector\SyncClient;

class Page_Connector {
  public static function render(): void {
    if (!current_user_can('manage_options')) {
      wp_die(esc_html__('אין לך הרשאה לצפות בעמוד זה.', 'klamra-paycal-for-aspaclaria'));
    }

    if (isset($_POST['paycal_connector_sync_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['paycal_connector_sync_nonce'])), 'paycal_connector_sync')) {
      $sync = SyncClient::sync();
      $body = is_array($sync['body'] ?? null) ? $sync['body'] : [];
      $merchant = is_array($body['merchant'] ?? null) ? $body['merchant'] : [];
      $event_details = [
        'merchant_status' => (string) ($merchant['status'] ?? ''),
        'last_connection_result' => !empty($sync['ok']) ? 'success' : 'failed',
        'last_sync' => (string) ($sync['synced_at'] ?? current_time('mysql')),
        'error_code' => (string) ($sync['code'] ?? ''),
        'message' => !empty($sync['ok']) ? 'Connection test succeeded' : (string) ($sync['message'] ?? 'Connection test failed'),
      ];
      if (class_exists(EventClient::class)) {
        EventClient::send('plugin.test_connection', $event_details);
        EventClient::send(!empty($sync['ok']) ? 'merchant.connected' : 'merchant.connection_failed', $event_details);
      }
      echo '<div class="notice notice-' . ($sync['ok'] ? 'success' : 'error') . '"><p>' . esc_html($sync['ok'] ? 'הסנכרון הצליח.' : ('הסנכרון נכשל: ' . ($sync['message'] ?? 'Unknown error'))) . '</p></div>';
    }

    if (isset($_POST['paycal_connector_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['paycal_connector_nonce'])), 'paycal_connector_save')) {
      ConnectorStore::save([
        'platform_url' => sanitize_text_field(wp_unslash($_POST['platform_url'] ?? '')),
        'checkout_base_url' => esc_url_raw(wp_unslash($_POST['checkout_base_url'] ?? '')),
        'use_checkout_sessions' => isset($_POST['use_checkout_sessions']) ? 'yes' : 'no',
        'merchant_id' => sanitize_text_field(wp_unslash($_POST['merchant_id'] ?? '')),
        'public_key' => sanitize_text_field(wp_unslash($_POST['public_key'] ?? '')),
        'terminal_id' => sanitize_text_field(wp_unslash($_POST['terminal_id'] ?? '')),
        'mode' => sanitize_text_field(wp_unslash($_POST['mode'] ?? 'production')),
        'access_token' => sanitize_text_field(wp_unslash($_POST['access_token'] ?? '')),
        'last_sync' => current_time('mysql'),
      ]);
      if (class_exists(EventClient::class)) {
        EventClient::send('plugin.settings_saved', [
          'last_connection_result' => 'settings saved',
          'last_sync' => current_time('mysql'),
        ]);
      }
      echo '<div class="notice notice-success"><p>הגדרות החיבור נשמרו.</p></div>';
    }

    $settings = ConnectorStore::get();
    $last_sync = SyncClient::last_sync();
    $woocommerce_ok = class_exists('\\WooCommerce') && class_exists('\\WC_Payment_Gateway');
    $http_api_ok = function_exists('wp_remote_post');
    $connector_ready = !empty($settings['platform_url']) && !empty($settings['public_key']) && !empty($settings['merchant_id']);
    $verify_ready = $connector_ready && !empty($settings['access_token']);
    $last_sync_ok = !empty($last_sync) ? !empty($last_sync['ok']) : null;
    $platform_version = is_array($last_sync['body']['platform'] ?? null) ? sanitize_text_field((string) ($last_sync['body']['platform']['version'] ?? '')) : '';
    $platform_compatible = $platform_version === '' || version_compare($platform_version, '1.2.7', '>=');
    $migration_diagnostics = method_exists(ConnectorStore::class, 'last_diagnostics') ? ConnectorStore::last_diagnostics() : [];
    $latest_migration = is_array($migration_diagnostics[0] ?? null) ? $migration_diagnostics[0] : [];
    $no_migrated_settings_found = !$connector_ready && (($latest_migration['result'] ?? '') === 'created_defaults');
    $uninstall_diagnostics = get_option('paycal_connector_uninstall_diagnostics', []);
    ?>
    <div class="wrap paycal-wrap" dir="rtl">
      <div class="notice notice-info"><p><?php echo esc_html__('PayCal connects this WooCommerce store to branded checkout, payment-management tools and approved payment-provider configurations. PayCal does not replace the merchant payment provider and does not act as a bank or seller of record.', 'klamra-paycal-for-aspaclaria'); ?></p></div>
      <?php if (!$platform_compatible) : ?>
        <div class="notice notice-warning"><p><?php echo esc_html__('PayCal Connector 1.3.1 is designed for PayCal Platform 1.2.7 or newer. Please update the Platform plugin when possible. Checkout will continue to use server verification and will fail safely if an incompatible response is returned.', 'klamra-paycal-for-aspaclaria'); ?></p></div>
      <?php endif; ?>
      <?php if ($no_migrated_settings_found) : ?>
        <div class="notice notice-warning"><p><?php echo esc_html__('PayCal could not find existing connector settings to migrate. Enter the merchant connection details once, then future updates will preserve them.', 'klamra-paycal-for-aspaclaria'); ?></p></div>
      <?php endif; ?>
      <h1>חיבור PayCal</h1>
      <p>זהו תוסף לקוח. ניהול Merchants, מסופים, Apple Pay provisioning ו־Audit Log מתבצע בפלטפורמה המרכזית בלבד.</p>

      <div style="max-width:760px;background:#fff;border:1px solid #dbe7f6;border-radius:16px;padding:18px;margin:16px 0;">
        <h2>System Health</h2>
        <table class="widefat striped">
          <tbody>
            <tr><th>Plugin version</th><td><?php echo esc_html(defined('PAYCAL_VERSION') ? PAYCAL_VERSION : 'unknown'); ?></td></tr>
            <tr><th>Platform version</th><td><?php echo esc_html($platform_version !== '' ? $platform_version : 'unknown until sync'); ?></td></tr>
            <tr><th>WordPress compatibility</th><td><?php echo esc_html('Tested up to 7.1'); ?></td></tr>
            <tr><th>PHP runtime</th><td><?php echo esc_html(PHP_VERSION . ' (target: 8.3.31)'); ?></td></tr>
            <tr><th>WooCommerce gateway classes</th><td><?php echo esc_html($woocommerce_ok ? 'available' : 'unavailable'); ?></td></tr>
            <tr><th>WordPress HTTP API</th><td><?php echo esc_html($http_api_ok ? 'available' : 'unavailable'); ?></td></tr>
            <tr><th>Connector credentials</th><td><?php echo esc_html($connector_ready ? 'configured' : 'incomplete'); ?></td></tr>
            <tr><th>Payment verification</th><td><?php echo esc_html($verify_ready ? 'configured' : 'missing access token or connector settings'); ?></td></tr>
            <tr><th>Last sync</th><td><?php echo esc_html($last_sync_ok === null ? 'not run yet' : ($last_sync_ok ? 'success' : 'failed')); ?></td></tr>
          </tbody>
        </table>
      </div>

      <div style="max-width:760px;background:#fff;border:1px solid #dbe7f6;border-radius:16px;padding:18px;margin:16px 0;">
        <h2>PayCal Security Status</h2>
        <table class="widefat striped">
          <tbody>
            <tr><th>Hosted checkout</th><td><?php echo esc_html($connector_ready ? 'enabled' : 'disabled'); ?></td></tr>
            <tr><th>Server-side verify</th><td><?php echo esc_html($verify_ready ? 'enabled' : 'disabled'); ?></td></tr>
            <tr><th>Session expiry</th><td><?php echo esc_html('enabled'); ?></td></tr>
            <tr><th>One-time session use</th><td><?php echo esc_html('enabled'); ?></td></tr>
            <tr><th>Merchant isolation</th><td><?php echo esc_html($connector_ready ? 'enabled' : 'disabled'); ?></td></tr>
            <tr><th>Debug visibility</th><td><?php echo esc_html('admin-only'); ?></td></tr>
            <tr><th>Webhook idempotency</th><td><?php echo esc_html('enabled'); ?></td></tr>
          </tbody>
        </table>
      </div>

      <?php if (!empty($migration_diagnostics)) : ?>
        <div style="max-width:760px;background:#fff;border:1px solid #dbe7f6;border-radius:16px;padding:18px;margin:16px 0;">
          <h2>Connection Persistence Diagnostics</h2>
          <p class="description">Safe update diagnostics. Values show whether connection fields exist, not the secrets themselves.</p>
          <?php if (is_array($uninstall_diagnostics) && !empty($uninstall_diagnostics)) : ?>
            <table class="widefat striped" style="margin:12px 0;">
              <tbody>
                <tr><th>Uninstall hook ran</th><td>yes</td></tr>
                <tr><th>Uninstall time</th><td><?php echo esc_html((string) ($uninstall_diagnostics['time'] ?? '')); ?></td></tr>
                <tr><th>Uninstall plugin</th><td><?php echo esc_html((string) ($uninstall_diagnostics['plugin'] ?? '')); ?></td></tr>
                <tr><th>Uninstall removed data</th><td><?php echo esc_html((string) ($uninstall_diagnostics['removed_data'] ?? 'no')); ?></td></tr>
                <tr><th>Connector settings existed then</th><td><?php echo esc_html((string) ($uninstall_diagnostics['connector_settings_existed'] ?? '')); ?></td></tr>
                <tr><th>License data existed then</th><td><?php echo esc_html((string) ($uninstall_diagnostics['license_data_existed'] ?? '')); ?></td></tr>
              </tbody>
            </table>
          <?php endif; ?>
          <?php foreach (array_slice($migration_diagnostics, 0, 3) as $diag) : ?>
            <?php
              $before = is_array($diag['before'] ?? null) ? $diag['before'] : [];
              $after = is_array($diag['after'] ?? null) ? $diag['after'] : [];
            ?>
            <table class="widefat striped" style="margin:12px 0;">
              <tbody>
                <tr><th>Time</th><td><?php echo esc_html((string) ($diag['time'] ?? '')); ?></td></tr>
                <tr><th>Plugin version</th><td><?php echo esc_html((string) ($diag['version'] ?? '')); ?></td></tr>
                <tr><th>Plugin basename</th><td><?php echo esc_html((string) ($diag['plugin_basename'] ?? '')); ?></td></tr>
                <tr><th>Plugin path</th><td><?php echo esc_html((string) ($diag['plugin_path'] ?? '')); ?></td></tr>
                <tr><th>Migration result</th><td><?php echo esc_html((string) ($diag['result'] ?? '')); ?></td></tr>
                <tr><th>Before settings existed</th><td><?php echo esc_html(!empty($before['settings_exist']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After merchant ID exists</th><td><?php echo esc_html(!empty($after['merchant_id_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After terminal ID exists</th><td><?php echo esc_html(!empty($after['terminal_id_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After public key exists</th><td><?php echo esc_html(!empty($after['public_key_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After access token exists</th><td><?php echo esc_html(!empty($after['access_token_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After license data exists</th><td><?php echo esc_html(!empty($after['license_data_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After license token exists</th><td><?php echo esc_html(!empty($after['license_token_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>After last sync exists</th><td><?php echo esc_html(!empty($after['last_sync_exists']) ? 'yes' : 'no'); ?></td></tr>
                <tr><th>Session checkout toggle</th><td><?php echo esc_html((string) ($after['use_checkout_sessions'] ?? 'no')); ?></td></tr>
                <tr><th>Mode</th><td><?php echo esc_html((string) ($after['mode'] ?? '')); ?></td></tr>
              </tbody>
            </table>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <form method="post" style="max-width:760px;background:#fff;border:1px solid #dbe7f6;border-radius:16px;padding:22px;">
        <?php wp_nonce_field('paycal_connector_save', 'paycal_connector_nonce'); ?>

        <table class="form-table" role="presentation">
          <tr>
            <th scope="row"><label for="platform_url">Platform URL</label></th>
            <td>
              <input name="platform_url" id="platform_url" type="url" class="regular-text" value="<?php echo esc_attr($settings['platform_url']); ?>" placeholder="https://paycal.online">
              <p class="description">Used for API sync, license checks and server verification against PayCal Platform.</p>
              <p class="description">משמש ל־API/SYNC מול PayCal Platform.</p>
            </td>
          </tr>
          <tr>
            <th scope="row"><label for="checkout_base_url">Checkout Base URL</label></th>
            <td>
              <input name="checkout_base_url" id="checkout_base_url" type="url" class="regular-text" value="<?php echo esc_attr($settings['checkout_base_url'] ?? 'https://pay.aspaclaria.co.il'); ?>" placeholder="https://pay.aspaclaria.co.il">
              <p class="description">Legacy hosted checkout URL. Keep this unchanged while testing the new session redirect.</p>
              <p class="description">דומיין דף התשלום שאליו WooCommerce מפנה את הלקוח.</p>
            </td>
          </tr>
          <tr>
            <th scope="row">Generic PayCal checkout sessions</th>
            <td>
              <label><input name="use_checkout_sessions" type="checkbox" value="yes" <?php checked($settings['use_checkout_sessions'] ?? 'no', 'yes'); ?>> Use checkout.paycal.online session redirects</label>
              <p class="description">Optional staged rollout. If session creation fails, checkout safely falls back to the existing hosted checkout URL.</p>
            </td>
          </tr>
          <tr>
            <th scope="row"><label for="merchant_id">Merchant ID</label></th>
            <td>
              <input name="merchant_id" id="merchant_id" type="text" class="regular-text" value="<?php echo esc_attr($settings['merchant_id']); ?>" placeholder="mrc_...">
              <p class="description">Merchant ID identifies the PayCal merchant. It is not a license key.</p>
            </td>
          </tr>
          <tr>
            <th scope="row"><label for="terminal_id">Terminal ID</label></th>
            <td>
              <input name="terminal_id" id="terminal_id" type="text" class="regular-text" value="<?php echo esc_attr($settings['terminal_id']); ?>" placeholder="trm_...">
              <p class="description">Terminal ID identifies the PayCal payment terminal.</p>
            </td>
          </tr>
          <tr>
            <th scope="row"><label for="public_key">Public Key</label></th>
            <td>
              <input name="public_key" id="public_key" type="text" class="regular-text" value="<?php echo esc_attr($settings['public_key']); ?>" placeholder="pk_...">
              <p class="description">אין לשמור כאן Secret Key פרטי. סודות נשמרים רק בפלטפורמה המרכזית.</p>
            </td>
          </tr>
          <tr>
            <th scope="row"><label for="access_token">Access Token</label></th>
            <td>
              <input name="access_token" id="access_token" type="password" class="regular-text" value="<?php echo esc_attr($settings['access_token'] ?? ''); ?>">
              <p class="description">Private connector token from PayCal Platform. Do not enter Apple Pay certificates, provider secrets or card data here.</p>
              <p class="description">Token מהפלטפורמה. לא להכניס כאן Apple Pay certificates או סודות סליקה.</p>
            </td>
          </tr>
          <tr>
            <th scope="row"><label for="mode">Mode</label></th>
            <td>
              <select name="mode" id="mode">
                <option value="production" <?php selected($settings['mode'], 'production'); ?>>Production</option>
                <option value="sandbox" <?php selected($settings['mode'], 'sandbox'); ?>>Sandbox</option>
              </select>
            </td>
          </tr>
        </table>

        <?php submit_button('שמור חיבור'); ?>
      </form>

      <form method="post" style="max-width:760px;background:#fff;border:1px solid #dbe7f6;border-radius:16px;padding:18px;margin-top:16px;">
        <h2>סנכרון מול PayCal Platform</h2>
        <p>Test the PayCal Platform connection, Merchant ID, Terminal ID, permissions and provider status. No payment is captured by this test.</p>
        <p>בודק Merchant, Terminal, הרשאות וסטטוס Apple Pay.</p>
        <?php wp_nonce_field('paycal_connector_sync', 'paycal_connector_sync_nonce'); ?>
        <?php submit_button('Test connection / sync now'); ?>
        <?php if (!empty($last_sync)) : ?>
          <pre style="white-space:pre-wrap;background:#f6f7f7;padding:12px;border-radius:10px;"><?php echo esc_html(wp_json_encode($last_sync, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
        <?php endif; ?>
      </form>

    </div>
    <?php
  }
}
