<?php
namespace PayCal\Connector;

defined('ABSPATH') || exit;

class SyncClient {
  private const OPTION = 'paycal_connector_last_sync';

  public static function sync(): array {
    $settings = ConnectorStore::get();
    \paycal_debug_log('[PayCal] Sync requested.');

    if (empty($settings['platform_url']) || empty($settings['public_key'])) {
      \paycal_debug_log('[PayCal] Sync failed: missing platform URL or public key.');
      return ['ok' => false, 'message' => 'Missing platform URL or public key.'];
    }

    $url = rtrim($settings['platform_url'], '/') . '/wp-json/paycal/v1/sync';

    if (!function_exists('wp_remote_post')) {
      $result = ['ok' => false, 'message' => 'WordPress HTTP API unavailable.', 'synced_at' => current_time('mysql')];
      update_option(self::OPTION, $result, false);
      \paycal_debug_log('[PayCal] Sync failed: WordPress HTTP API unavailable.');
      return $result;
    }

    $headers = [
      'Content-Type' => 'application/json',
      'X-PayCal-Public-Key' => $settings['public_key'],
    ];

    // Optional token. Keep it in wp_options only if the merchant intentionally enters it.
    if (!empty($settings['access_token'])) {
      $headers['X-PayCal-Token'] = $settings['access_token'];
    }

    $response = wp_remote_post($url, [
      'timeout' => 15,
      'headers' => $headers,
      'body' => wp_json_encode([
        'merchant_id' => $settings['merchant_id'] ?? '',
        'terminal_id' => $settings['terminal_id'] ?? '',
        'site_url' => home_url('/'),
        'plugin_version' => defined('PAYCAL_VERSION') ? PAYCAL_VERSION : 'unknown',
      ]),
    ]);

    if (is_wp_error($response)) {
      $result = ['ok' => false, 'message' => $response->get_error_message()];
      update_option(self::OPTION, $result, false);
      \paycal_debug_log('[PayCal] Sync failed: ' . $response->get_error_message());
      return $result;
    }

    $code = wp_remote_retrieve_response_code($response);
    $raw = wp_remote_retrieve_body($response);
    $body = json_decode($raw, true);
    if (!is_array($body)) {
      \paycal_debug_log('[PayCal] Sync returned malformed response. HTTP ' . (int) $code . ', body_hash=' . hash('sha256', (string) $raw));
    }

    $result = [
      'ok' => $code >= 200 && $code < 300,
      'code' => $code,
      'body' => is_array($body) ? $body : [],
      'synced_at' => current_time('mysql'),
    ];

    if ($result['ok'] && is_array($body)) {
      $save = [];
      if (!empty($body['merchant']['uid'])) {
        $save['merchant_id'] = sanitize_text_field($body['merchant']['uid']);
      }
      if (!empty($body['terminal']['uid'])) {
        $save['terminal_id'] = sanitize_text_field($body['terminal']['uid']);
      }
      if (!empty($save)) {
        ConnectorStore::save($save);
      }
    }

    if (!$result['ok']) {
      \paycal_debug_log('[PayCal] Sync returned HTTP ' . $code);
    } else {
      \paycal_debug_log('[PayCal] Sync completed.');
    }

    update_option(self::OPTION, $result, false);
    return $result;
  }

  public static function last_sync(): array {
    $last = get_option(self::OPTION, []);
    return is_array($last) ? $last : [];
  }
}
