<?php defined('ABSPATH') || exit;

$plan      = FixLinks_License::get_plan();
$total     = FixLinks_DB::count_broken();
$pending   = FixLinks_DB::count_broken('pending');
$applied   = FixLinks_DB::count_broken('applied');
$links     = FixLinks_DB::get_broken_links(null, 50);
$redirects = FixLinks_Redirects::get_all();
$is_free   = ($plan === 'free');
$status    = get_option('fixlinks_crawl_status', 'idle');
$c_total   = (int)get_option('fixlinks_crawl_total', 0);
$c_done    = (int)get_option('fixlinks_crawl_done', 0);
$c_pct     = $c_total > 0 ? min(100, round($c_done / $c_total * 100)) : 0;
?>
<div class="wrap fixlinks-wrap">

  <div class="fixlinks-header">
    <div class="fixlinks-header-title">
      <span class="fixlinks-logo-icon">🔗</span>
      <div>
        <h1>FixLinks AI</h1>
        <span class="fixlinks-version">v<?php echo esc_html(FIXLINKS_VERSION) ?></span>
      </div>
    </div>
    <div class="fixlinks-header-actions">
      <button id="fixlinks-run-crawl" class="fixlinks-btn fixlinks-btn-secondary">
        <span class="fixlinks-btn-icon">🔍</span> <?php echo esc_html__('Run Crawl Now', 'fixlinks-ai') ?>
      </button>
      <?php if (!$is_free): ?>
        <button id="fixlinks-bulk-suggest" class="fixlinks-btn fixlinks-btn-outline">
          <span class="fixlinks-btn-icon">✨</span> <?php echo esc_html__('Bulk Get Suggestions', 'fixlinks-ai') ?>
        </button>
        <button id="fixlinks-bulk-apply" class="fixlinks-btn fixlinks-btn-primary">
          <span class="fixlinks-btn-icon">⚡</span> <?php echo esc_html__('Bulk Apply AI', 'fixlinks-ai') ?>
        </button>
      <?php endif; ?>
      <?php if ($plan === 'agency'):
        $rpt = wp_nonce_url(admin_url('admin-post.php?action=fixlinks_export_report'), 'fixlinks_export_report'); ?>
        <a href="<?php echo esc_url($rpt) ?>" target="_blank" class="fixlinks-btn fixlinks-btn-outline">
          <span class="fixlinks-btn-icon">📊</span> <?php echo esc_html__('Download Report', 'fixlinks-ai') ?>
        </a>
      <?php endif; ?>
    </div>
  </div>

  <div class="fixlinks-stats-grid">
    <div class="fixlinks-stat-card">
      <div class="fixlinks-stat-icon fixlinks-stat-icon-default">🔗</div>
      <div class="fixlinks-stat-body">
        <div class="fixlinks-stat-value"><?php echo (int)$total ?></div>
        <div class="fixlinks-stat-label"><?php echo esc_html__('Total Broken', 'fixlinks-ai') ?></div>
      </div>
    </div>
    <div class="fixlinks-stat-card fixlinks-stat-card-danger">
      <div class="fixlinks-stat-icon fixlinks-stat-icon-danger">⚠️</div>
      <div class="fixlinks-stat-body">
        <div class="fixlinks-stat-value"><?php echo (int)$pending ?></div>
        <div class="fixlinks-stat-label"><?php echo esc_html__('Needs Review', 'fixlinks-ai') ?></div>
      </div>
    </div>
    <div class="fixlinks-stat-card fixlinks-stat-card-success">
      <div class="fixlinks-stat-icon fixlinks-stat-icon-success">✅</div>
      <div class="fixlinks-stat-body">
        <div class="fixlinks-stat-value"><?php echo (int)$applied ?></div>
        <div class="fixlinks-stat-label"><?php echo esc_html__('Fixed', 'fixlinks-ai') ?></div>
      </div>
    </div>
    <div class="fixlinks-stat-card fixlinks-stat-card-info">
      <div class="fixlinks-stat-icon fixlinks-stat-icon-info">↩️</div>
      <div class="fixlinks-stat-body">
        <div class="fixlinks-stat-value"><?php echo count($redirects) ?></div>
        <div class="fixlinks-stat-label"><?php echo esc_html__('Active Redirects', 'fixlinks-ai') ?></div>
      </div>
    </div>
  </div>

  <?php if (!empty(get_option('fixlinks_last_crawl'))): ?>
    <p class="fixlinks-last-crawl">🕐 <?php echo esc_html__('Last crawl:', 'fixlinks-ai') ?> <strong><?php echo esc_html(get_option('fixlinks_last_crawl')) ?></strong></p>
  <?php endif; ?>

  <?php if ($status === 'running'): ?>
  <div class="fixlinks-progress-wrap" id="fixlinks-progress-wrap">
    <div class="fixlinks-progress-header">
      <strong><?php echo esc_html__('Crawl in progress…', 'fixlinks-ai') ?></strong>
      <span id="fixlinks-progress-text" class="fixlinks-progress-text"><?php echo esc_html($c_done) ?>/<?php echo esc_html($c_total) ?> URLs</span>
    </div>
    <div class="fixlinks-progress-track">
      <div id="fixlinks-progress-bar" class="fixlinks-progress-bar" style="width:<?php echo esc_attr($c_pct) ?>%"></div>
    </div>
    <div class="fixlinks-progress-pct"><?php echo esc_html($c_pct) ?>% complete</div>
  </div>
  <?php endif; ?>

  <?php if ($is_free && $total >= 10): ?>
  <div class="fixlinks-notice fixlinks-notice-warning">
    <span class="fixlinks-notice-icon">⚠️</span>
    <div>
      <strong><?php echo esc_html__('Free plan limit reached.', 'fixlinks-ai') ?></strong>
      <?php
			/* translators: %d: number of broken links */
			echo sprintf( esc_html__( 'Showing 10 of %d broken links.', 'fixlinks-ai' ), absint( $total ) );
			?>
      <a href="https://fixlinks.getinfotoyou.com/#pricing" target="_blank" rel="noopener"><?php echo esc_html__('Upgrade to Pro →', 'fixlinks-ai') ?></a>
    </div>
  </div>
  <?php endif; ?>

  <div class="fixlinks-section-header">
    <h2><?php echo esc_html__('Broken Links', 'fixlinks-ai') ?></h2>
    <?php if ($pending > 0): ?>
      <span class="fixlinks-badge fixlinks-badge-danger"><?php echo (int)$pending ?> pending</span>
    <?php endif; ?>
  </div>

  <?php if (empty($links)): ?>
  <div class="fixlinks-empty-state">
    <div class="fixlinks-empty-icon">🎉</div>
    <h3><?php echo esc_html__('No broken links found!', 'fixlinks-ai') ?></h3>
    <p><?php echo esc_html__('Run a crawl to check your site for broken outbound links.', 'fixlinks-ai') ?></p>
  </div>
  <?php else: ?>
  <div class="fixlinks-table-wrap">
  <table class="fixlinks-table">
    <thead>
      <tr>
        <th><?php echo esc_html__('Broken URL', 'fixlinks-ai') ?></th>
        <th><?php echo esc_html__('Found on Page', 'fixlinks-ai') ?></th>
        <th class="fixlinks-col-narrow"><?php echo esc_html__('Code', 'fixlinks-ai') ?></th>
        <th><?php echo esc_html__('AI Suggestion', 'fixlinks-ai') ?></th>
        <th class="fixlinks-col-action"><?php echo esc_html__('Action', 'fixlinks-ai') ?></th>
      </tr>
    </thead>
    <tbody>
    <?php
    $show = $is_free ? array_slice($links, 0, 10) : $links;
    foreach ($show as $link):
        $sc = $link->http_status === 404 ? 'error-404' : ($link->http_status >= 500 ? 'error-5xx' : 'error-0');
    ?>
    <tr id="fixlinks-row-<?php echo (int)$link->id ?>" class="fixlinks-row <?php echo $link->status === 'applied' ? 'fixlinks-row-applied' : '' ?>">
      <td class="fixlinks-cell-url">
        <a href="<?php echo esc_url($link->broken_url) ?>" target="_blank" rel="noopener" class="fixlinks-broken-url"><?php echo esc_html($link->broken_url) ?></a>
        <?php if ($link->anchor_text): ?>
          <span class="fixlinks-anchor-text">"<?php echo esc_html($link->anchor_text) ?>"</span>
        <?php endif; ?>
      </td>
      <td>
        <a href="<?php echo esc_url($link->source_page) ?>" target="_blank" rel="noopener" class="fixlinks-source-link">
        <?php echo esc_html( wp_parse_url( $link->source_page, PHP_URL_PATH ) ); ?>
        </a>
      </td>
      <td><span class="fixlinks-status-badge <?php echo esc_attr($sc) ?>"><?php echo $link->http_status ? absint( $link->http_status ) : esc_html__( 'Timeout', 'fixlinks-ai' ) ?></span></td>
      <td class="fixlinks-suggestion-cell-<?php echo (int)$link->id ?>">
        <?php if ($link->ai_suggestion): ?>
          <div class="fixlinks-suggestion-wrap">
            <input type="text" value="<?php echo esc_attr($link->ai_suggestion) ?>" class="fixlinks-redirect-input" />
            <span class="fixlinks-confidence <?php echo esc_attr($link->confidence ?? 'low') ?>"><?php echo esc_html(ucfirst($link->confidence ?? 'low')) ?></span>
          </div>
        <?php elseif (!$is_free): ?>
          <button class="fixlinks-btn fixlinks-btn-ai fixlinks-get-suggestion"
            data-id="<?php echo (int)$link->id ?>"
            data-url="<?php echo esc_attr($link->broken_url) ?>">✨ <?php echo esc_html__('Get AI suggestion', 'fixlinks-ai') ?></button>
        <?php else: ?>
          <span class="fixlinks-upgrade-hint"><?php echo esc_html__('Upgrade for AI', 'fixlinks-ai') ?></span>
        <?php endif; ?>
      </td>
      <td class="fixlinks-col-action">
        <?php if ($link->status === 'applied'): ?>
          <div class="fixlinks-action-wrap">
            <span class="fixlinks-applied-badge">✓ <?php echo esc_html__('Applied', 'fixlinks-ai') ?></span>
            <button class="fixlinks-btn fixlinks-btn-ghost fixlinks-rollback" data-from="<?php echo esc_attr($link->broken_url) ?>"><?php echo esc_html__('Undo', 'fixlinks-ai') ?></button>
          </div>
        <?php elseif ($link->ai_suggestion): ?>
          <button class="fixlinks-btn fixlinks-btn-primary fixlinks-apply"
            data-id="<?php echo (int)$link->id ?>"
            data-from="<?php echo esc_attr($link->broken_url) ?>">↩ <?php echo esc_html__('Apply 301', 'fixlinks-ai') ?></button>
        <?php else: ?>
          <span class="fixlinks-no-action">—</span>
        <?php endif; ?>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>

  <?php if ($is_free && $total > 10): ?>
  <div class="fixlinks-upgrade-banner">
    <div>
      <strong><?php
			/* translators: %d: number of hidden broken links */
			echo sprintf( esc_html__( '%d more broken links hidden.', 'fixlinks-ai' ), absint( $total - 10 ) );
			?></strong>
      <span style="color:#6B7280"> <?php echo esc_html__('Upgrade to see all links + AI suggestions.', 'fixlinks-ai') ?></span>
    </div>
    <a href="https://fixlinks.getinfotoyou.com/#pricing" target="_blank" rel="noopener" class="fixlinks-btn fixlinks-btn-primary"><?php echo esc_html__('Upgrade to Pro — $15/mo', 'fixlinks-ai') ?></a>
  </div>
  <?php endif; ?>

  <?php if (!empty($redirects)): ?>
  <div class="fixlinks-section-header" style="margin-top:32px">
    <h2><?php echo esc_html__('Active Redirects', 'fixlinks-ai') ?></h2>
    <span class="fixlinks-badge fixlinks-badge-info"><?php echo count($redirects) ?> active</span>
  </div>
  <p class="fixlinks-section-desc"><?php echo esc_html__('Served via WordPress DB — works on Nginx + Apache. No .htaccess required.', 'fixlinks-ai') ?></p>
  <div class="fixlinks-table-wrap">
  <table class="fixlinks-table">
    <thead>
      <tr>
        <th><?php echo esc_html__('From Path', 'fixlinks-ai') ?></th>
        <th><?php echo esc_html__('To URL', 'fixlinks-ai') ?></th>
        <th class="fixlinks-col-narrow"><?php echo esc_html__('Hits', 'fixlinks-ai') ?></th>
        <th class="fixlinks-col-narrow"><?php echo esc_html__('Applied', 'fixlinks-ai') ?></th>
        <th class="fixlinks-col-action"><?php echo esc_html__('Action', 'fixlinks-ai') ?></th>
      </tr>
    </thead>
    <tbody>
    <?php foreach ($redirects as $r): ?>
    <tr class="fixlinks-row">
      <td><code class="fixlinks-code"><?php echo esc_html($r->from_path) ?></code></td>
      <td><a href="<?php echo esc_url($r->to_url) ?>" target="_blank" rel="noopener" class="fixlinks-to-url"><?php echo esc_html($r->to_url) ?></a></td>
      <td>
        <?php if ($r->hit_count > 0): ?>
          <span class="fixlinks-hit-badge"><?php echo (int)$r->hit_count ?></span>
        <?php else: ?>
          <span style="color:#9CA3AF">0</span>
        <?php endif; ?>
      </td>
      <td><span class="fixlinks-date"><?php echo esc_html(substr($r->created_at, 0, 10)) ?></span></td>
      <td><button class="fixlinks-btn fixlinks-btn-ghost fixlinks-rollback" data-from="<?php echo esc_attr($r->from_path) ?>"><?php echo esc_html__('Remove', 'fixlinks-ai') ?></button></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>

</div>