<?php
$countries = [
    'IN' => ['name' => 'India',          'flag' => 'in'],
    'US' => ['name' => 'United States',  'flag' => 'us'],
    'GB' => ['name' => 'United Kingdom', 'flag' => 'gb'],
    'CA' => ['name' => 'Canada',         'flag' => 'ca'],
    'AU' => ['name' => 'Australia',      'flag' => 'au'],
    'AE' => ['name' => 'UAE',            'flag' => 'ae'],
    'SG' => ['name' => 'Singapore',      'flag' => 'sg'],
    'DE' => ['name' => 'Germany',        'flag' => 'de'],
];
$currentCountry = $submission['country_code'] ?? 'IN';
$countryMeta    = $countries[$currentCountry] ?? $countries['IN'];
?>

<!-- Breadcrumb + Export -->
<div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-3 gap-2">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb mb-0" style="font-size:0.8rem;">
      <li class="breadcrumb-item">
        <a href="<?php echo $basePath; ?>/serp?project_id=<?php echo $projectId; ?>"
           class="text-decoration-none text-muted">SERP Tracker</a>
      </li>
      <li class="breadcrumb-item active text-truncate" style="max-width:240px;">
        <?php echo htmlspecialchars($submissionId); ?>
      </li>
    </ol>
  </nav>
  <a href="<?php echo $basePath; ?>/api/serp/export-csv?id=<?php echo urlencode($submissionId); ?>"
     class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2 px-3">
    <i class="bi bi-filetype-csv small"></i> Export CSV
  </a>
</div>

<!-- Page heading -->
<div class="mb-4">
  <h1 class="h5 fw-bold mb-1">Keyword Tracking Report</h1>
  <div class="text-muted small mb-3">
    <i class="bi bi-link-45deg me-1"></i><?php echo htmlspecialchars($submission['weburl']); ?>
  </div>

  <!-- Meta bar -->
  <div class="d-flex align-items-center flex-wrap gap-2 gap-md-3 serp-meta-row small text-muted">

    <!-- Country selector -->
    <div class="dropdown">
      <button class="btn btn-white btn-sm border dropdown-toggle d-flex align-items-center gap-2 py-1"
              type="button" data-bs-toggle="dropdown">
        <img src="https://flagcdn.com/<?php echo $countryMeta['flag']; ?>.svg"
             width="16" id="selected-flag" alt="">
        <span id="selected-country">Country: <?php echo $countryMeta['name']; ?></span>
      </button>
      <ul class="dropdown-menu shadow-sm border-0" style="max-height:280px;overflow-y:auto;">
        <?php foreach ($countries as $code => $meta): ?>
        <li>
          <a class="dropdown-item country-item d-flex align-items-center gap-2" href="#"
             data-code="<?php echo $code; ?>"
             data-name="<?php echo $meta['name']; ?>"
             data-flag="<?php echo $meta['flag']; ?>">
            <img src="https://flagcdn.com/<?php echo $meta['flag']; ?>.svg" width="16" alt="">
            <span><?php echo $meta['name']; ?></span>
          </a>
        </li>
        <?php endforeach; ?>
      </ul>
    </div>

    <!-- History dropdown -->
    <div class="dropdown">
      <button class="btn btn-white btn-sm border dropdown-toggle d-flex align-items-center gap-2 py-1"
              type="button" data-bs-toggle="dropdown">
        <i class="bi bi-clock-history small"></i>
        <span>History</span>
      </button>
      <ul class="dropdown-menu shadow-sm border-0" id="history-dropdown"
          style="max-height:280px;overflow-y:auto;min-width:230px;">
        <li><a class="dropdown-item disabled small">Loading...</a></li>
      </ul>
    </div>

    <!-- Run button + last run -->
    <div class="d-flex align-items-center gap-2">
      <span class="text-primary fw-semibold" style="cursor:pointer;" id="btn-run-report">
        <i class="bi bi-arrow-clockwise me-1"></i>Run
      </span>
      <span id="last-run-time">
        Last Run:
        <?php echo !empty($ranks) ? date('M d, H:i', strtotime($ranks[0]['checked_at'])) : '(Never run)'; ?>
      </span>
    </div>

    <!-- Linked project -->
    <div class="d-flex align-items-center gap-2 text-muted">
      Project:
      <span class="text-dark fw-medium"><?php echo htmlspecialchars($project['business_name']); ?></span>
    </div>
  </div>
</div>

<!-- Stats cards -->
<div class="row g-3 mb-4">
  <div class="col-md-6">
    <div class="card border-0 shadow-sm p-3">
      <div class="text-muted small text-uppercase fw-semibold mb-1" style="font-size:0.7rem;letter-spacing:.5px;">
        Keywords Tracked
      </div>
      <div class="h4 mb-0 fw-bold"><?php echo count($currentKeywords); ?></div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card border-0 shadow-sm p-3">
      <div class="text-muted small text-uppercase fw-semibold mb-1" style="font-size:0.7rem;letter-spacing:.5px;">
        Target Domain
      </div>
      <div class="h4 mb-0 fw-bold text-truncate"><?php echo htmlspecialchars($submission['weburl']); ?></div>
    </div>
  </div>
</div>

<!-- Ranking table -->
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header bg-white border-bottom py-3">
    <h5 class="mb-0 fw-semibold" style="font-size:0.9rem;">Ranking Overview</h5>
  </div>
  <div class="card-body p-3">
    <div class="table-responsive">
      <table id="serpTable" class="table table-hover align-middle mb-0 w-100">
        <thead class="table-light">
          <tr>
            <th class="ps-3">Keyword</th>
            <?php foreach ($runIds as $rId): ?>
            <th class="text-center run-col"><?php echo $columnLabels[$rId]; ?></th>
            <?php endforeach; ?>
            <th class="text-center" id="trend-col">Trend</th>
            <th class="pe-3 url-col">URL on Google</th>
          </tr>
        </thead>
        <tbody id="ranking-body">
          <?php foreach ($currentKeywords as $keyword):
            $latestId  = $runIds[0] ?? null;
            $prevId    = $runIds[1] ?? null;
            $currRank  = ($latestId && isset($keywordData[$keyword]['ranks'][$latestId]) && is_numeric($keywordData[$keyword]['ranks'][$latestId]))
                       ? (int)$keywordData[$keyword]['ranks'][$latestId] : null;
            $prevRank  = ($prevId && isset($keywordData[$keyword]['ranks'][$prevId]) && is_numeric($keywordData[$keyword]['ranks'][$prevId]))
                       ? (int)$keywordData[$keyword]['ranks'][$prevId] : null;
            $latestUrl = $latestId ? ($keywordData[$keyword]['urls'][$latestId] ?? '') : '';
          ?>
          <tr>
            <td class="ps-3 fw-medium small"><?php echo htmlspecialchars($keyword); ?></td>
            <?php foreach ($runIds as $rId):
              $r = $keywordData[$keyword]['ranks'][$rId] ?? '-';
              $cls = is_numeric($r) && $r <= 3 ? 'text-success fw-bold'
                   : (is_numeric($r) && $r <= 10 ? 'text-primary' : '');
            ?>
            <td class="text-center">
              <span class="<?php echo $cls; ?> small"><?php echo $r; ?></span>
            </td>
            <?php endforeach; ?>
            <td class="text-center">
              <?php if ($currRank !== null && $prevRank !== null):
                $diff = $prevRank - $currRank;
              ?>
                <?php if ($diff > 0): ?>
                  <span class="text-success small"><i class="bi bi-caret-up-fill me-1"></i><?php echo $diff; ?></span>
                <?php elseif ($diff < 0): ?>
                  <span class="text-danger small"><i class="bi bi-caret-down-fill me-1"></i><?php echo abs($diff); ?></span>
                <?php else: ?>
                  <span class="text-muted small">—</span>
                <?php endif; ?>
              <?php else: ?>
                <span class="text-muted small">—</span>
              <?php endif; ?>
            </td>
            <td class="pe-3">
              <?php if ($latestUrl): ?>
              <a href="<?php echo htmlspecialchars($latestUrl); ?>" target="_blank" rel="noopener"
                 class="text-primary small text-decoration-none d-block text-truncate" style="max-width:360px;">
                <?php echo htmlspecialchars($latestUrl); ?>
              </a>
              <?php else: ?>
              <span class="text-muted small">Not found in top 100</span>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Distribution chart (only shown when there is at least one run) -->
<?php if (!empty($runIds)): ?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header bg-white border-bottom py-3">
    <h5 class="mb-0 fw-semibold" style="font-size:0.9rem;">Ranking Distribution History</h5>
  </div>
  <div class="card-body">
    <div id="serpRankChart"></div>
  </div>
</div>
<?php endif; ?>

<!-- Run Report Modal -->
<div class="modal fade" id="runReportModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow">
      <div class="modal-header border-bottom">
        <h5 class="modal-title fw-bold">Run SERP Report</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4">
        <form id="runReportForm">
          <input type="hidden" id="run_submission_id" value="<?php echo htmlspecialchars($submissionId); ?>">
          <div class="mb-3">
            <label class="form-label fw-medium small">Device Type</label>
            <select id="run_device" class="form-select form-select-sm">
              <option value="desktop">Desktop</option>
              <option value="mobile">Mobile</option>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium small">Search Mode</label>
            <select id="run_search_type" class="form-select form-select-sm">
              <option value="normal">Normal Search (Top 100)</option>
              <option value="fast">Fast Search (Page 1–10)</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="form-label fw-medium small">Target Location <span class="text-muted fw-normal">(city / country)</span></label>
            <input type="text" id="run_city" class="form-control form-control-sm"
                   placeholder="e.g. Mumbai, India" required>
          </div>
          <button type="submit" class="btn btn-primary w-100 py-2" id="runSubmitBtn">
            <i class="bi bi-lightning-fill me-2"></i>Fetch Latest Rankings
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Floating background-job progress widget (bottom-right corner) -->
<div id="serpJobWidget"
     style="display:none;position:fixed;bottom:24px;right:24px;z-index:1055;
            width:300px;background:#fff;border-radius:12px;
            box-shadow:0 4px 24px rgba(0,0,0,.15);border:1px solid #e5e7eb;padding:16px;">
  <div class="d-flex justify-content-between align-items-start mb-2">
    <div class="d-flex align-items-center gap-2">
      <div class="spinner-border spinner-border-sm text-primary" id="serpJobSpinner" role="status"></div>
      <span class="fw-semibold" style="font-size:0.82rem;">SERP Running</span>
    </div>
    <button type="button" class="btn-close" style="font-size:0.65rem;" id="serpJobDismiss" title="Dismiss"></button>
  </div>
  <div id="serpJobMsg" class="text-muted mb-2" style="font-size:0.78rem;">Starting...</div>
  <div class="progress" style="height:6px;border-radius:3px;">
    <div id="serpJobBar" class="progress-bar progress-bar-striped progress-bar-animated bg-primary"
         role="progressbar" style="width:0%"></div>
  </div>
  <div class="d-flex justify-content-between align-items-center mt-1">
    <span id="serpJobPct" class="text-muted" style="font-size:0.72rem;">0%</span>
    <span id="serpJobRefresh" style="display:none;">
      <a href="javascript:location.reload()" class="btn btn-sm btn-primary py-0 px-2" style="font-size:0.72rem;">
        Refresh to see results
      </a>
    </span>
  </div>
</div>

<!-- ApexCharts -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

<style>
.serp-meta-row > .dropdown { flex-shrink: 0; }
.url-col { min-width: 200px; }
@media (max-width: 768px) {
  .serp-meta-row { flex-direction: column; align-items: flex-start !important; gap: 0.75rem !important; }
  .serp-meta-row > * { width: 100%; }
  .serp-meta-row .btn { width: 100%; justify-content: space-between; }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const base         = '<?php echo $basePath; ?>';
  const submissionId = '<?php echo addslashes($submissionId); ?>';
  let   selectedCountry = '<?php echo $currentCountry; ?>';
  let   jobPollTimer    = null;

  // ── DataTable ──────────────────────────────────────────────────────────────
  function initTable() {
    if ($.fn.DataTable.isDataTable('#serpTable')) {
      $('#serpTable').DataTable().destroy();
    }
    $('#serpTable').DataTable({
      pageLength: 15,
      lengthMenu: [15, 25, 50, 100],
      ordering:   true,
      searching:  true,
      info:       true,
    });
  }
  initTable();

  // ── ApexChart ──────────────────────────────────────────────────────────────
  <?php if (!empty($runIds)): ?>
  new ApexCharts(document.querySelector('#serpRankChart'), {
    series: [
      { name: 'Top 3',      data: <?php echo json_encode($chartTop3); ?> },
      { name: 'Top 4–10',   data: <?php echo json_encode($chartTop10); ?> },
      { name: 'Top 11–100', data: <?php echo json_encode($chartTop100); ?> },
      { name: 'Not Found',  data: <?php echo json_encode($chartNotFound); ?> },
    ],
    chart: { type: 'bar', height: 320, stacked: true, toolbar: { show: false } },
    colors: ['#198754', '#0d6efd', '#ffc107', '#adb5bd'],
    plotOptions: { bar: { horizontal: false, borderRadius: 3, dataLabels: { total: { enabled: false } } } },
    xaxis: { categories: <?php echo json_encode($chartLabels); ?> },
    legend: { position: 'top' },
    fill: { opacity: 1 },
  }).render();
  <?php endif; ?>

  // ── Country selector ───────────────────────────────────────────────────────
  document.querySelectorAll('.country-item').forEach(function (el) {
    el.addEventListener('click', function (e) {
      e.preventDefault();
      selectedCountry = this.dataset.code;
      document.getElementById('selected-country').textContent = 'Country: ' + this.dataset.name;
      document.getElementById('selected-flag').src = 'https://flagcdn.com/' + this.dataset.flag + '.svg';
    });
  });

  // ── History dropdown ───────────────────────────────────────────────────────
  fetch(base + '/api/serp/history?submission_id=' + encodeURIComponent(submissionId))
    .then(r => r.json())
    .then(function (data) {
      const dd = document.getElementById('history-dropdown');
      if (data.success && data.history.length) {
        dd.innerHTML = data.history.map(function (h) {
          return '<li><a class="dropdown-item history-item small py-2" href="#" data-run-id="' + h.id + '">'
               + '<div class="fw-semibold">' + h.device + '</div>'
               + '<div class="text-muted" style="font-size:0.72rem;">' + h.time + '</div>'
               + '</a></li>';
        }).join('');
      } else {
        dd.innerHTML = '<li><a class="dropdown-item disabled small">No history available</a></li>';
      }
    })
    .catch(function () {
      document.getElementById('history-dropdown').innerHTML =
        '<li><a class="dropdown-item disabled small">Error loading history</a></li>';
    });

  // ── History item click ─────────────────────────────────────────────────────
  document.addEventListener('click', function (e) {
    const item = e.target.closest('.history-item');
    if (!item) return;
    e.preventDefault();
    const runId = item.dataset.runId;

    fetch(base + '/api/serp/run-detail?run_id=' + runId)
      .then(r => r.json())
      .then(function (data) {
        if (!data.success) return;

        if ($.fn.DataTable.isDataTable('#serpTable')) $('#serpTable').DataTable().destroy();
        document.querySelectorAll('.run-col').forEach(el => el.remove());
        document.getElementById('trend-col').insertAdjacentHTML(
          'beforebegin',
          '<th class="text-center run-col">' + data.checked_at + '</th>'
        );

        document.getElementById('ranking-body').innerHTML = data.results.map(function (res) {
          const r   = res.rank;
          const cls = (!isNaN(parseFloat(r)) && isFinite(r) && +r <= 3)  ? 'text-success fw-bold small'
                    : (!isNaN(parseFloat(r)) && isFinite(r) && +r <= 10) ? 'text-primary small'
                    : 'small';
          const urlCell = res.url
            ? '<a href="' + res.url + '" target="_blank" rel="noopener" class="text-primary small text-decoration-none d-block text-truncate" style="max-width:360px;">' + res.url + '</a>'
            : '<span class="text-muted small">Not found in top 100</span>';
          return '<tr>'
            + '<td class="ps-3 fw-medium small">' + res.keyword + '</td>'
            + '<td class="text-center"><span class="' + cls + '">' + r + '</span></td>'
            + '<td class="text-center"><span class="text-muted small">—</span></td>'
            + '<td class="pe-3">' + urlCell + '</td>'
            + '</tr>';
        }).join('');

        initTable();
        document.getElementById('last-run-time').textContent = 'Run: ' + data.checked_at;
      });
  });

  // ── Job progress widget ────────────────────────────────────────────────────
  const widget   = document.getElementById('serpJobWidget');
  const jobMsg   = document.getElementById('serpJobMsg');
  const jobBar   = document.getElementById('serpJobBar');
  const jobPct   = document.getElementById('serpJobPct');
  const jobRef   = document.getElementById('serpJobRefresh');
  const jobSpin  = document.getElementById('serpJobSpinner');

  document.getElementById('serpJobDismiss').addEventListener('click', function () {
    widget.style.display = 'none';
    if (jobPollTimer) { clearInterval(jobPollTimer); jobPollTimer = null; }
  });

  function showWidget(msg, pct) {
    jobMsg.textContent         = msg;
    jobBar.style.width         = pct + '%';
    jobPct.textContent         = pct + '%';
    widget.style.display       = 'block';
  }

  function pollJobStatus(jobId) {
    if (jobPollTimer) clearInterval(jobPollTimer);

    jobPollTimer = setInterval(function () {
      fetch(base + '/api/serp/job-status?job_id=' + encodeURIComponent(jobId))
        .then(r => r.json())
        .then(function (data) {
          if (!data.success) return;

          showWidget(data.message || '...', data.percent || 0);

          if (data.status === 'done') {
            clearInterval(jobPollTimer);
            jobPollTimer     = null;
            jobSpin.style.display = 'none';
            jobBar.classList.remove('progress-bar-animated', 'progress-bar-striped');
            jobBar.classList.add('bg-success');
            jobRef.style.display = 'inline';
            document.querySelector('#serpJobWidget .fw-semibold').textContent = 'SERP Complete';
          } else if (data.status === 'failed') {
            clearInterval(jobPollTimer);
            jobPollTimer     = null;
            jobSpin.style.display = 'none';
            jobBar.classList.remove('progress-bar-animated', 'progress-bar-striped', 'bg-primary');
            jobBar.classList.add('bg-danger');
            document.querySelector('#serpJobWidget .fw-semibold').textContent = 'SERP Failed';
          }
        })
        .catch(function () { /* network hiccup — keep polling */ });
    }, 3000);
  }

  // ── Run button ─────────────────────────────────────────────────────────────
  document.getElementById('btn-run-report').addEventListener('click', function () {
    new bootstrap.Modal(document.getElementById('runReportModal')).show();
  });

  document.getElementById('runReportForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const city = document.getElementById('run_city').value.trim();
    if (!city) {
      alert('Please enter a target location for accurate rankings.');
      return;
    }

    const submitBtn = document.getElementById('runSubmitBtn');
    submitBtn.disabled    = true;
    submitBtn.textContent = 'Starting…';

    const device     = document.getElementById('run_device').value;
    const searchType = document.getElementById('run_search_type').value;
    const url        = base + '/api/serp/start-job'
                     + '?submission_id=' + encodeURIComponent(submissionId)
                     + '&device_type='   + device
                     + '&search_type='   + searchType
                     + '&city_name='     + encodeURIComponent(city)
                     + '&country_code='  + selectedCountry;

    fetch(url)
      .then(r => r.json())
      .then(function (data) {
        submitBtn.disabled    = false;
        submitBtn.innerHTML   = '<i class="bi bi-lightning-fill me-2"></i>Fetch Latest Rankings';

        bootstrap.Modal.getInstance(document.getElementById('runReportModal')).hide();

        if (!data.success) {
          alert('Error starting job: ' + (data.message || data.error || 'Unknown error'));
          return;
        }

        // Reset widget state
        jobSpin.style.display = '';
        jobBar.classList.add('progress-bar-animated', 'progress-bar-striped');
        jobBar.classList.remove('bg-success', 'bg-danger');
        jobBar.classList.add('bg-primary');
        jobRef.style.display  = 'none';
        document.querySelector('#serpJobWidget .fw-semibold').textContent = 'SERP Running';

        showWidget('Starting SERP check...', 2);

        // Start polling BEFORE firing the long-running request
        pollJobStatus(data.job_id);

        // Fire-and-forget: trigger the actual SERP processing.
        // keepalive:true keeps the request alive even if the user navigates away.
        // PHP sets ignore_user_abort(true) so processing continues regardless.
        fetch(base + '/api/serp/process-job?job_id=' + encodeURIComponent(data.job_id), { keepalive: true })
          .catch(function () { /* connection close is expected — ignore */ });
      })
      .catch(function (err) {
        submitBtn.disabled    = false;
        submitBtn.innerHTML   = '<i class="bi bi-lightning-fill me-2"></i>Fetch Latest Rankings';
        alert('Failed to start job: ' + err.message);
      });
  });
});
</script>
