<?php
namespace PayCal\Admin;

defined('ABSPATH') || exit;

use PayCal\Connector\DashboardClient;

class Page_Payments {
  public static function register_menu(): void {
    add_submenu_page(
      'woocommerce',
      'PayCal Payments',
      'PayCal Payments',
      'manage_woocommerce',
      'paycal-payments',
      [__CLASS__, 'render']
    );
  }

  public static function render(): void {
    if (!self::can_view()) {
      wp_die(esc_html__('You do not have permission to view PayCal payments.', 'klamra-paycal-for-aspaclaria'));
    }

    $force = isset($_GET['paycal_refresh']) && check_admin_referer('paycal_dashboard_refresh', 'paycal_nonce');
    $result = DashboardClient::get($force);
    $data = is_array($result['data'] ?? null) ? $result['data'] : [];
    $summary = is_array($data['summary'] ?? null) ? $data['summary'] : [];
    $merchant = is_array($data['merchant'] ?? null) ? $data['merchant'] : [];
    $payments = is_array($data['recent_payments'] ?? null) ? $data['recent_payments'] : [];
    $settlements = is_array($data['recent_settlements'] ?? null) ? $data['recent_settlements'] : [];
    $reconciliation = is_array($data['latest_reconciliation'] ?? null) ? $data['latest_reconciliation'] : [];
    $currency = self::text($summary['currency'] ?? 'ILS');

    echo '<div class="wrap paycal-payments-wrap">';
    self::styles();

    echo '<section class="paycal-payments-hero">';
    echo '  <div class="paycal-payments-copy">';
    echo '    <span class="paycal-payments-eyebrow">PAYCAL MERCHANT PAYMENTS</span>';
    echo '    <h1>PayCal Payments</h1>';
    echo '    <p>תצוגת תשלומים ו־settlements לקריאה בלבד מתוך PayCal Platform.</p>';
    echo '    <div class="paycal-payments-meta">';
    echo '      <span>' . esc_html(self::text($merchant['business_name'] ?? 'Connected merchant')) . '</span>';
    echo '      <span>' . esc_html(self::text($merchant['mode'] ?? '')) . '</span>';
    echo '      <span>' . esc_html($currency) . '</span>';
    echo '    </div>';
    echo '  </div>';
    echo '  <img class="paycal-payments-mark" src="' . esc_url(PAYCAL_URL . 'assets/images/bugs-runner.png') . '" alt="">';
    echo '</section>';

    if (!empty($result['auth_error'])) {
      echo '<div class="notice notice-error"><p>' . esc_html($result['message'] ?? 'PayCal dashboard access was denied.') . '</p></div>';
    } elseif (empty($result['ok'])) {
      echo '<div class="notice notice-warning"><p>' . esc_html($result['message'] ?? 'PayCal Platform is unavailable.') . '</p></div>';
    } elseif (!empty($result['stale'])) {
      echo '<div class="notice notice-warning"><p>' . esc_html__('PayCal Platform is unavailable right now. Showing the last cached dashboard snapshot.', 'klamra-paycal-for-aspaclaria') . ' ' . esc_html($result['last_updated'] ? 'Last updated: ' . self::timestamp($result['last_updated']) : '') . '</p></div>';
    }

    echo '<div class="paycal-payments-toolbar">';
    echo '  <span>Last updated: ' . esc_html(self::timestamp($result['last_updated'] ?? '')) . '</span>';
    echo '  <a class="button" href="' . esc_url(wp_nonce_url(admin_url('admin.php?page=paycal-payments&paycal_refresh=1'), 'paycal_dashboard_refresh', 'paycal_nonce')) . '">Refresh</a>';
    echo '</div>';

    echo '<section class="paycal-payments-stats">';
    self::metric('Gross', self::money($summary['gross_total'] ?? '0.00', $currency));
    self::metric('Fee', self::money($summary['fee_total'] ?? '0.00', $currency));
    self::metric('Net', self::money($summary['net_total'] ?? '0.00', $currency));
    self::metric('Pending Settlement', self::money($summary['pending_settlement'] ?? '0.00', $currency));
    self::metric('Settled Settlement', self::money($summary['settled_settlement'] ?? '0.00', $currency));
    self::metric('Ledger Entries', self::text($summary['ledger_entry_count'] ?? '0'));
    echo '</section>';

    echo '<section class="paycal-payments-grid">';
    echo '<article class="paycal-panel paycal-panel-wide"><div class="paycal-panel-head"><h2>Recent PayCal Payments</h2><span>' . esc_html((string) count($payments)) . '</span></div>';
    self::payments_table($payments);
    echo '</article>';

    echo '<article class="paycal-panel"><div class="paycal-panel-head"><h2>Reconciliation</h2></div>';
    self::reconciliation_card($reconciliation);
    echo '</article>';

    echo '<article class="paycal-panel paycal-panel-wide"><div class="paycal-panel-head"><h2>Settlements</h2><span>' . esc_html(self::text($summary['settlement_batch_count'] ?? '0')) . '</span></div>';
    self::settlements_table($settlements);
    echo '</article>';
    echo '</section>';

    echo '</div>';
  }

  private static function can_view(): bool {
    return current_user_can('manage_options') || current_user_can('manage_woocommerce') || current_user_can('edit_shop_orders');
  }

  private static function styles(): void {
    echo '<style>
      .paycal-payments-wrap{max-width:1280px}
      .paycal-payments-hero{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 210px;gap:24px;align-items:center;min-height:245px;margin:18px 0 18px;padding:32px;border-radius:8px;overflow:hidden;background:radial-gradient(circle at 80% 40%,rgba(255,45,202,.24),transparent 34%),linear-gradient(135deg,#15110f 0%,#2c1b12 48%,#090908 100%);color:#fff;border:1px solid rgba(233,173,54,.45)}
      .paycal-payments-hero h1{margin:8px 0 8px;font-size:42px;line-height:1.08;color:#fff;letter-spacing:0}
      .paycal-payments-hero p{font-size:15px;max-width:560px;color:#f5dfc0}
      .paycal-payments-eyebrow{display:block;color:#ffcf5a;font-weight:700;font-size:12px;letter-spacing:0}
      .paycal-payments-meta{display:flex;flex-wrap:wrap;gap:8px;margin-top:18px}
      .paycal-payments-meta span{border:1px solid rgba(255,205,90,.35);background:rgba(255,255,255,.08);border-radius:999px;padding:7px 11px;color:#fff}
      .paycal-payments-mark{width:210px;max-width:100%;filter:drop-shadow(0 0 24px rgba(255,48,199,.52))}
      .paycal-payments-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin:14px 0;color:#5d6673}
      .paycal-payments-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(165px,1fr));gap:12px;margin:16px 0}
      .paycal-stat{background:#fff;border:1px solid #dfe6ef;border-radius:8px;padding:15px;box-shadow:0 1px 2px rgba(16,24,40,.04)}
      .paycal-stat span{display:block;color:#667085;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:0}
      .paycal-stat strong{display:block;margin-top:7px;font-size:24px;line-height:1.1;color:#1d2939}
      .paycal-payments-grid{display:grid;grid-template-columns:minmax(0,2fr) minmax(280px,1fr);gap:14px}
      .paycal-panel{background:#fff;border:1px solid #dfe6ef;border-radius:8px;padding:16px;overflow:auto}
      .paycal-panel-wide{grid-column:auto}
      .paycal-panel-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}
      .paycal-panel h2{font-size:17px;margin:0;color:#1d2939}
      .paycal-table{width:100%;border-collapse:collapse}
      .paycal-table th{text-align:left;color:#667085;font-size:12px;text-transform:uppercase;letter-spacing:0;border-bottom:1px solid #e4e7ec;padding:10px 8px}
      .paycal-table td{border-bottom:1px solid #eef2f6;padding:10px 8px;vertical-align:top}
      .paycal-code{font-family:monospace;background:#f6f7f9;border-radius:6px;padding:2px 5px}
      .paycal-status{display:inline-block;border-radius:999px;padding:4px 8px;font-size:12px;font-weight:700;background:#f2f4f7;color:#344054}
      .paycal-status.is-settled,.paycal-status.is-approved,.paycal-status.is-matched{background:#e7f8ef;color:#067647}
      .paycal-status.is-failed,.paycal-status.is-mismatch{background:#fff1f3;color:#c01048}
      .paycal-recon-list{display:grid;gap:10px;margin-top:4px}
      .paycal-recon-list div{display:flex;justify-content:space-between;gap:12px;border-bottom:1px solid #eef2f6;padding-bottom:8px}
      .paycal-empty{color:#667085;padding:18px;background:#f8fafc;border-radius:8px}
      @media (max-width:782px){.paycal-payments-hero{grid-template-columns:1fr;padding:22px}.paycal-payments-hero h1{font-size:32px}.paycal-payments-mark{width:150px}.paycal-payments-grid{grid-template-columns:1fr}}
    </style>';
  }

  private static function metric(string $label, string $value): void {
    echo '<article class="paycal-stat"><span>' . esc_html($label) . '</span><strong>' . esc_html($value) . '</strong></article>';
  }

  private static function payments_table(array $rows): void {
    if (empty($rows)) {
      echo '<div class="paycal-empty">No PayCal payments to show yet.</div>';
      return;
    }
    echo '<table class="paycal-table"><thead><tr><th>Created</th><th>Payment</th><th>Order</th><th>Status</th><th>Gross</th><th>Fee</th><th>Net</th><th>Settlement</th><th>Invoice</th></tr></thead><tbody>';
    foreach ($rows as $row) {
      $invoice = self::text($row['invoice_url'] ?? '');
      echo '<tr>';
      echo '<td>' . esc_html(self::timestamp($row['created_at'] ?? '')) . '</td>';
      echo '<td><span class="paycal-code">' . esc_html(self::text($row['payment_id'] ?? '')) . '</span></td>';
      echo '<td>' . esc_html(self::text($row['order_id'] ?? '')) . '</td>';
      echo '<td>' . wp_kses(self::status(self::text($row['status'] ?? '')), self::status_allowed_html()) . '</td>';
      echo '<td>' . esc_html(self::money($row['gross_amount'] ?? '0.00', $row['currency'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::money($row['fee_amount'] ?? '0.00', $row['currency'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::money($row['net_amount'] ?? '0.00', $row['currency'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::text($row['settlement_status'] ?? 'Pending Settlement')) . '</td>';
      echo '<td>' . ($invoice !== '' ? '<a href="' . esc_url($invoice) . '" target="_blank" rel="noopener noreferrer">Open</a>' : '') . '</td>';
      echo '</tr>';
    }
    echo '</tbody></table>';
  }

  private static function settlements_table(array $rows): void {
    if (empty($rows)) {
      echo '<div class="paycal-empty">No settlements to show yet.</div>';
      return;
    }
    echo '<table class="paycal-table"><thead><tr><th>Created</th><th>Settled</th><th>Reference</th><th>Status</th><th>Entries</th><th>Gross</th><th>Fee</th><th>Net</th><th>Bank Ref</th></tr></thead><tbody>';
    foreach ($rows as $row) {
      echo '<tr>';
      echo '<td>' . esc_html(self::timestamp($row['created_at'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::timestamp($row['settled_at'] ?? '')) . '</td>';
      echo '<td><span class="paycal-code">' . esc_html(self::text($row['settlement_uid'] ?? '')) . '</span></td>';
      echo '<td>' . wp_kses(self::status(self::text($row['status'] ?? '')), self::status_allowed_html()) . '</td>';
      echo '<td>' . esc_html(self::text($row['entry_count'] ?? '0')) . '</td>';
      echo '<td>' . esc_html(self::money($row['gross_amount'] ?? '0.00', $row['currency'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::money($row['fee_amount'] ?? '0.00', $row['currency'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::money($row['net_amount'] ?? '0.00', $row['currency'] ?? '')) . '</td>';
      echo '<td>' . esc_html(self::text($row['bank_reference'] ?? '')) . '</td>';
      echo '</tr>';
    }
    echo '</tbody></table>';
  }

  private static function reconciliation_card(array $row): void {
    if (empty(array_filter($row))) {
      echo '<div class="paycal-empty">No reconciliation events yet.</div>';
      return;
    }
    echo '<div class="paycal-recon-list">';
    echo '<div><span>Status</span>' . wp_kses(self::status(self::text($row['match_status'] ?? '')), self::status_allowed_html()) . '</div>';
    echo '<div><span>Event</span><strong>' . esc_html(self::text($row['event_type'] ?? '')) . '</strong></div>';
    echo '<div><span>Provider</span><strong>' . esc_html(self::text($row['provider'] ?? '')) . '</strong></div>';
    echo '<div><span>Settlement</span><strong>' . esc_html(self::text($row['settlement_uid'] ?? '')) . '</strong></div>';
    echo '<div><span>Reference</span><strong>' . esc_html(self::text($row['settlement_reference'] ?? '')) . '</strong></div>';
    echo '<div><span>Updated</span><strong>' . esc_html(self::timestamp($row['created_at'] ?? '')) . '</strong></div>';
    echo '</div>';
  }

  private static function status(string $status): string {
    $status = self::text($status);
    $class = sanitize_html_class('is-' . str_replace('_', '-', strtolower($status)));
    return '<span class="paycal-status ' . esc_attr($class) . '">' . esc_html($status !== '' ? $status : 'pending') . '</span>';
  }

  private static function status_allowed_html(): array {
    return [
      'span' => [
        'class' => true,
      ],
    ];
  }

  private static function money($amount, $currency): string {
    $amount = is_numeric($amount) ? number_format((float) $amount, 2, '.', '') : '0.00';
    $currency = self::text($currency ?: 'ILS');
    return trim($amount . ' ' . $currency);
  }

  private static function text($value): string {
    return is_scalar($value) ? sanitize_text_field((string) $value) : '';
  }

  private static function timestamp($value): string {
    $raw = self::text($value);
    if ($raw === '') {
      return '';
    }

    $has_timezone = (bool) preg_match('/(?:Z|[+-]\d{2}:?\d{2})$/', $raw);
    $timestamp = strtotime($has_timezone ? $raw : $raw . ' UTC');
    if (!$timestamp) {
      return $raw;
    }

    $format = trim((string) get_option('date_format') . ' ' . (string) get_option('time_format'));
    if ($format === '') {
      $format = 'Y-m-d H:i:s';
    }

    return wp_date($format, $timestamp, wp_timezone());
  }
}
