<?php
$countries = [
    'IN' => 'India',          'US' => 'United States', 'GB' => 'United Kingdom',
    'CA' => 'Canada',         'AU' => 'Australia',     'AE' => 'UAE',
    'SG' => 'Singapore',      'DE' => 'Germany',
];
?>

<!-- SheetJS for Excel import -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.mini.min.js"></script>

<div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-4 gap-3">
  <div>
    <h2 class="h5 fw-bold mb-1">SERP Tracker</h2>
    <p class="text-muted small mb-0">
      <?php echo $project
          ? 'Keyword rankings for ' . htmlspecialchars($project['business_name'])
          : 'All keyword tracking submissions'; ?>
    </p>
  </div>
  <button class="btn btn-primary btn-sm d-flex align-items-center gap-2 px-3"
          data-bs-toggle="modal" data-bs-target="#addSubmissionModal">
    <i class="bi bi-plus-lg"></i> New Submission
  </button>
</div>

<div class="card border-0 shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0 no-datatable">
        <thead class="table-light">
          <tr>
            <th class="ps-4 py-3 small text-uppercase fw-semibold text-muted">Submission ID</th>
            <th class="py-3 small text-uppercase fw-semibold text-muted">Project</th>
            <th class="py-3 small text-uppercase fw-semibold text-muted">Keywords</th>
            <th class="py-3 small text-uppercase fw-semibold text-muted">Target URL</th>
            <th class="py-3 text-center small text-uppercase fw-semibold text-muted">Engine</th>
            <th class="py-3 small text-uppercase fw-semibold text-muted">Created</th>
            <th class="pe-4 py-3 text-end small text-uppercase fw-semibold text-muted">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($submissions)): ?>
          <tr>
            <td colspan="7" class="text-center py-5">
              <div class="text-muted">
                <i class="bi bi-graph-up-arrow fs-2 mb-3 d-block opacity-50"></i>
                <p class="mb-2 fw-medium small">No SERP submissions yet.</p>
                <button class="btn btn-primary btn-sm mt-1"
                        data-bs-toggle="modal" data-bs-target="#addSubmissionModal">
                  <i class="bi bi-plus-lg me-1"></i>Add First Submission
                </button>
              </div>
            </td>
          </tr>
          <?php else: ?>
          <?php foreach ($submissions as $sub):
            $kwCount = count(array_filter(array_map('trim', explode("\n", $sub['keywords']))));
          ?>
          <tr>
            <td class="ps-4">
              <span class="fw-semibold font-monospace" style="font-size:0.75rem;">
                <?php echo htmlspecialchars($sub['submission_id']); ?>
              </span>
            </td>
            <td>
              <span class="small text-dark fw-medium"><?php echo htmlspecialchars($sub['project_name']); ?></span>
            </td>
            <td>
              <span class="badge bg-primary-subtle text-primary fw-normal">
                <?php echo $kwCount; ?> keyword<?php echo $kwCount !== 1 ? 's' : ''; ?>
              </span>
            </td>
            <td>
              <small class="text-muted text-truncate d-block" style="max-width:200px;">
                <?php echo htmlspecialchars($sub['weburl']); ?>
              </small>
            </td>
            <td class="text-center">
              <img src="https://www.google.com/s2/favicons?domain=google.com&sz=16" class="me-1" alt="">
              <small class="text-muted"><?php echo strtoupper(str_replace('google.', '', $sub['search_engine'])); ?></small>
            </td>
            <td>
              <small class="text-muted"><?php echo date('M j, Y', strtotime($sub['created_at'])); ?></small>
            </td>
            <td class="pe-4 text-end">
              <div class="d-flex justify-content-end gap-2 align-items-center">
                <button class="btn btn-outline-secondary btn-sm px-2 serp-edit-btn"
                        data-id="<?php echo $sub['id']; ?>"
                        data-keywords="<?php echo htmlspecialchars($sub['keywords']); ?>"
                        data-weburl="<?php echo htmlspecialchars($sub['weburl']); ?>"
                        data-engine="<?php echo htmlspecialchars($sub['search_engine']); ?>"
                        data-country="<?php echo htmlspecialchars($sub['country_code']); ?>"
                        title="Edit submission">
                  <i class="bi bi-pencil"></i>
                </button>
                <a href="<?php echo $basePath; ?>/serp/details?id=<?php echo urlencode($sub['submission_id']); ?>&project_id=<?php echo $sub['project_id']; ?>"
                   class="btn btn-primary btn-sm px-3">View</a>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ── Add Submission Modal ────────────────────────────────────────────────── -->
<div class="modal fade" id="addSubmissionModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0 shadow">
      <div class="modal-header border-bottom">
        <h5 class="modal-title fw-bold">New SERP Submission</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="addSubmissionForm">
        <div class="modal-body p-4">

          <!-- Project -->
          <div class="mb-3">
            <label class="form-label fw-medium small">Project</label>
            <select class="form-select form-select-sm" id="add_project_id" name="project_id" required>
              <option value="" data-url="">Select project...</option>
              <?php foreach ($projects as $p): ?>
              <option value="<?php echo $p['id']; ?>"
                      data-url="<?php echo htmlspecialchars($p['website_url'] ?? ''); ?>"
                      <?php echo ($projectId && $projectId == $p['id']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($p['business_name'] ?: $p['website_url']); ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- Target URL — readonly, auto-filled from project -->
          <div class="mb-3">
            <label class="form-label fw-medium small d-flex align-items-center gap-2">
              Target Website URL
              <span class="badge bg-secondary-subtle text-secondary fw-normal" style="font-size:0.68rem;">
                <i class="bi bi-lock-fill me-1"></i>Auto-filled from project
              </span>
            </label>
            <input type="text" class="form-control form-control-sm bg-light text-muted"
                   id="add_weburl" name="weburl"
                   placeholder="Select a project above to auto-fill URL"
                   readonly required>
          </div>

          <!-- Keywords -->
          <div class="mb-3">
            <div class="d-flex align-items-center justify-content-between mb-1">
              <label class="form-label fw-medium small mb-0">
                Keywords
                <span class="text-muted fw-normal">(one per line, max 5000)</span>
              </label>
              <div class="d-flex gap-2">
                <!-- Paste from clipboard -->
                <button type="button" class="btn btn-outline-secondary btn-sm py-0 px-2"
                        id="add_paste_btn" title="Paste from clipboard"
                        style="font-size:0.75rem;">
                  <i class="bi bi-clipboard2-fill me-1"></i>Paste
                </button>
                <!-- Import CSV / Excel -->
                <button type="button" class="btn btn-outline-primary btn-sm py-0 px-2"
                        id="add_import_btn" title="Import from CSV or Excel"
                        style="font-size:0.75rem;">
                  <i class="bi bi-file-earmark-spreadsheet me-1"></i>Import
                </button>
                <input type="file" id="add_import_file" accept=".csv,.xlsx,.xls,.txt" class="d-none">
              </div>
            </div>
            <textarea class="form-control form-control-sm" id="add_keywords" name="keywords"
                      rows="8"
                      placeholder="seo company mumbai&#10;best digital marketing agency&#10;web design services"
                      required></textarea>
            <div class="d-flex justify-content-between mt-1">
              <span id="add_kw_counter" class="small text-muted">0 / 5000 keywords</span>
              <button type="button" class="btn btn-link btn-sm p-0 text-danger small"
                      id="add_clear_kw" style="font-size:0.75rem;">
                <i class="bi bi-x-circle me-1"></i>Clear
              </button>
            </div>
          </div>

          <!-- Search Engine + Country -->
          <div class="row g-2">
            <div class="col-6">
              <label class="form-label fw-medium small">Search Engine</label>
              <select class="form-select form-select-sm" name="search_engine">
                <option value="google.com">Google.com (Global)</option>
                <option value="google.co.in">Google.co.in (India)</option>
                <option value="google.co.uk">Google.co.uk (UK)</option>
                <option value="google.com.au">Google.com.au (AU)</option>
              </select>
            </div>
            <div class="col-6">
              <label class="form-label fw-medium small">Country</label>
              <select class="form-select form-select-sm" name="country_code">
                <?php foreach ($countries as $code => $name): ?>
                <option value="<?php echo $code; ?>" <?php echo $code === 'IN' ? 'selected' : ''; ?>>
                  <?php echo $code; ?> — <?php echo $name; ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

        </div>
        <div class="modal-footer border-top">
          <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary btn-sm px-4" id="add_submit_btn">
            Create Submission
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- ── Edit Submission Modal ───────────────────────────────────────────────── -->
<div class="modal fade" id="editSubmissionModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0 shadow">
      <div class="modal-header border-bottom">
        <h5 class="modal-title fw-bold">Edit Submission</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="editSubmissionForm">
        <input type="hidden" id="edit_id">
        <div class="modal-body p-4">

          <!-- URL (editable in edit mode) -->
          <div class="mb-3">
            <label class="form-label fw-medium small">Target Website URL</label>
            <input type="url" class="form-control form-control-sm" id="edit_weburl" required>
          </div>

          <!-- Keywords -->
          <div class="mb-3">
            <div class="d-flex align-items-center justify-content-between mb-1">
              <label class="form-label fw-medium small mb-0">
                Keywords
                <span class="text-muted fw-normal">(one per line, max 5000)</span>
              </label>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-outline-secondary btn-sm py-0 px-2"
                        id="edit_paste_btn" title="Paste from clipboard"
                        style="font-size:0.75rem;">
                  <i class="bi bi-clipboard2-fill me-1"></i>Paste
                </button>
                <button type="button" class="btn btn-outline-primary btn-sm py-0 px-2"
                        id="edit_import_btn" title="Import from CSV or Excel"
                        style="font-size:0.75rem;">
                  <i class="bi bi-file-earmark-spreadsheet me-1"></i>Import
                </button>
                <input type="file" id="edit_import_file" accept=".csv,.xlsx,.xls,.txt" class="d-none">
              </div>
            </div>
            <textarea class="form-control form-control-sm" id="edit_keywords" rows="8" required></textarea>
            <div class="d-flex justify-content-between mt-1">
              <span id="edit_kw_counter" class="small text-muted">0 / 5000 keywords</span>
              <button type="button" class="btn btn-link btn-sm p-0 text-danger small"
                      id="edit_clear_kw" style="font-size:0.75rem;">
                <i class="bi bi-x-circle me-1"></i>Clear
              </button>
            </div>
          </div>

          <!-- Search Engine + Country -->
          <div class="row g-2">
            <div class="col-6">
              <label class="form-label fw-medium small">Search Engine</label>
              <select class="form-select form-select-sm" id="edit_engine">
                <option value="google.com">Google.com (Global)</option>
                <option value="google.co.in">Google.co.in (India)</option>
                <option value="google.co.uk">Google.co.uk (UK)</option>
                <option value="google.com.au">Google.com.au (AU)</option>
              </select>
            </div>
            <div class="col-6">
              <label class="form-label fw-medium small">Country</label>
              <select class="form-select form-select-sm" id="edit_country">
                <?php foreach ($countries as $code => $name): ?>
                <option value="<?php echo $code; ?>"><?php echo $code; ?> — <?php echo $name; ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

        </div>
        <div class="modal-footer border-top">
          <button type="button" class="btn btn-outline-danger btn-sm me-auto" id="deleteSubmissionBtn">
            <i class="bi bi-trash me-1"></i>Delete
          </button>
          <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary btn-sm px-4">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function () {
  const base    = '<?php echo $basePath; ?>';
  const MAX_KW  = 5000;

  // ── Keyword counter ─────────────────────────────────────────────────────────
  function countKw(text) {
    return text.split('\n').filter(l => l.trim() !== '').length;
  }

  function refreshCounter(taId, counterId) {
    const ta    = document.getElementById(taId);
    const ct    = document.getElementById(counterId);
    const count = countKw(ta.value);
    ct.textContent = count.toLocaleString() + ' / ' + MAX_KW.toLocaleString() + ' keywords';
    ct.className   = count > MAX_KW ? 'small text-danger fw-semibold'
                   : count > MAX_KW * 0.9 ? 'small text-warning fw-semibold'
                   : 'small text-muted';
  }

  function appendToTextarea(taId, counterId, lines) {
    const ta       = document.getElementById(taId);
    const existing = ta.value.trim();
    const combined = existing ? existing + '\n' + lines.join('\n') : lines.join('\n');
    // enforce max
    const all = combined.split('\n').filter(l => l.trim() !== '');
    if (all.length > MAX_KW) {
      alert('Limit is ' + MAX_KW.toLocaleString() + ' keywords. ' + (all.length - MAX_KW).toLocaleString() + ' lines were trimmed.');
    }
    ta.value = all.slice(0, MAX_KW).join('\n');
    refreshCounter(taId, counterId);
  }

  // ── Clipboard paste ─────────────────────────────────────────────────────────
  async function pasteToTextarea(taId, counterId) {
    try {
      const text  = await navigator.clipboard.readText();
      const lines = text.split(/\r?\n/).map(l => l.trim()).filter(l => l !== '');
      appendToTextarea(taId, counterId, lines);
    } catch (_) {
      alert('Clipboard access was denied. Please paste manually into the keywords box.');
    }
  }

  // ── File import (CSV / Excel) ───────────────────────────────────────────────
  function importFile(file, taId, counterId) {
    const name = file.name.toLowerCase();
    const reader = new FileReader();

    if (name.endsWith('.xlsx') || name.endsWith('.xls')) {
      if (typeof XLSX === 'undefined') {
        alert('Excel library not loaded. Please refresh and try again.');
        return;
      }
      reader.onload = function (e) {
        const wb   = XLSX.read(new Uint8Array(e.target.result), { type: 'array' });
        const ws   = wb.Sheets[wb.SheetNames[0]];
        const rows = XLSX.utils.sheet_to_json(ws, { header: 1, raw: false });
        const kws  = rows
          .map(r => String(r[0] ?? '').trim())
          .filter(k => k !== '' && k.toLowerCase() !== 'keyword');
        appendToTextarea(taId, counterId, kws);
      };
      reader.readAsArrayBuffer(file);
    } else {
      // CSV / TXT
      reader.onload = function (e) {
        const lines = e.target.result.split(/\r?\n/);
        const kws = lines
          .map(l => l.split(/[,\t;]/)[0].trim().replace(/^["']|["']$/g, ''))
          .filter(k => k !== '' && k.toLowerCase() !== 'keyword');
        appendToTextarea(taId, counterId, kws);
      };
      reader.readAsText(file, 'UTF-8');
    }
  }

  // ── Wire up ADD modal ───────────────────────────────────────────────────────

  // Auto-fill URL from project
  document.getElementById('add_project_id').addEventListener('change', function () {
    const opt = this.options[this.selectedIndex];
    const url = opt.dataset.url || '';
    document.getElementById('add_weburl').value = url;
  });
  // Pre-fill if a project is already selected on load
  (function () {
    const sel = document.getElementById('add_project_id');
    const opt = sel.options[sel.selectedIndex];
    if (opt && opt.value) document.getElementById('add_weburl').value = opt.dataset.url || '';
  }());

  // Keyword counter — live
  document.getElementById('add_keywords').addEventListener('input', function () {
    refreshCounter('add_keywords', 'add_kw_counter');
  });

  // Paste button
  document.getElementById('add_paste_btn').addEventListener('click', function () {
    pasteToTextarea('add_keywords', 'add_kw_counter');
  });

  // Import button → trigger file input
  document.getElementById('add_import_btn').addEventListener('click', function () {
    document.getElementById('add_import_file').value = '';
    document.getElementById('add_import_file').click();
  });
  document.getElementById('add_import_file').addEventListener('change', function () {
    if (this.files[0]) importFile(this.files[0], 'add_keywords', 'add_kw_counter');
  });

  // Clear keywords
  document.getElementById('add_clear_kw').addEventListener('click', function () {
    document.getElementById('add_keywords').value = '';
    refreshCounter('add_keywords', 'add_kw_counter');
  });

  // Submit
  document.getElementById('addSubmissionForm').addEventListener('submit', async function (e) {
    e.preventDefault();
    const kwCount = countKw(document.getElementById('add_keywords').value);
    if (kwCount === 0) { alert('Please enter at least one keyword.'); return; }
    if (kwCount > MAX_KW) { alert('Too many keywords (' + kwCount + '). Maximum is ' + MAX_KW + '.'); return; }

    const btn = document.getElementById('add_submit_btn');
    btn.disabled = true;
    btn.textContent = 'Creating...';

    const res  = await fetch(base + '/api/serp/submissions', { method: 'POST', body: new FormData(this) });
    const data = await res.json();
    if (data.success) {
      location.reload();
    } else {
      alert('Error: ' + (data.message || 'Could not create submission'));
      btn.disabled = false;
      btn.textContent = 'Create Submission';
    }
  });

  // Reset add modal on close
  document.getElementById('addSubmissionModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('addSubmissionForm').reset();
    document.getElementById('add_weburl').value = '';
    refreshCounter('add_keywords', 'add_kw_counter');
  });

  // ── Wire up EDIT modal ──────────────────────────────────────────────────────

  document.getElementById('edit_keywords').addEventListener('input', function () {
    refreshCounter('edit_keywords', 'edit_kw_counter');
  });

  document.getElementById('edit_paste_btn').addEventListener('click', function () {
    pasteToTextarea('edit_keywords', 'edit_kw_counter');
  });

  document.getElementById('edit_import_btn').addEventListener('click', function () {
    document.getElementById('edit_import_file').value = '';
    document.getElementById('edit_import_file').click();
  });
  document.getElementById('edit_import_file').addEventListener('change', function () {
    if (this.files[0]) importFile(this.files[0], 'edit_keywords', 'edit_kw_counter');
  });

  document.getElementById('edit_clear_kw').addEventListener('click', function () {
    document.getElementById('edit_keywords').value = '';
    refreshCounter('edit_keywords', 'edit_kw_counter');
  });

  // Populate edit modal
  document.querySelectorAll('.serp-edit-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      document.getElementById('edit_id').value       = this.dataset.id;
      document.getElementById('edit_weburl').value   = this.dataset.weburl;
      document.getElementById('edit_keywords').value = this.dataset.keywords;
      document.getElementById('edit_engine').value   = this.dataset.engine;
      document.getElementById('edit_country').value  = this.dataset.country;
      refreshCounter('edit_keywords', 'edit_kw_counter');
      new bootstrap.Modal(document.getElementById('editSubmissionModal')).show();
    });
  });

  // Save edit
  document.getElementById('editSubmissionForm').addEventListener('submit', async function (e) {
    e.preventDefault();
    const id  = document.getElementById('edit_id').value;
    const btn = this.querySelector('[type=submit]');
    btn.disabled = true;
    btn.textContent = 'Saving...';
    const payload = {
      keywords:      document.getElementById('edit_keywords').value,
      weburl:        document.getElementById('edit_weburl').value,
      search_engine: document.getElementById('edit_engine').value,
      country_code:  document.getElementById('edit_country').value,
    };
    const res  = await fetch(base + '/api/serp/submissions/' + id, {
      method:  'PUT',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify(payload),
    });
    const data = await res.json();
    if (data.success) {
      location.reload();
    } else {
      alert('Error: ' + (data.message || 'Could not update submission'));
      btn.disabled = false;
      btn.textContent = 'Save Changes';
    }
  });

  // Delete
  document.getElementById('deleteSubmissionBtn').addEventListener('click', async function () {
    const id = document.getElementById('edit_id').value;
    if (!confirm('Delete this submission and all its rank history? This cannot be undone.')) return;
    const res  = await fetch(base + '/api/serp/submissions/' + id, { method: 'DELETE' });
    const data = await res.json();
    if (data.success) {
      location.reload();
    } else {
      alert('Error deleting submission');
    }
  });
}());
</script>
