<?php
$pageTitle = $mode === 'create' ? 'New Project' : 'Edit Project: ' . ($project['business_name'] ?? '');
$v = fn($key) => htmlspecialchars($project[$key] ?? '', ENT_QUOTES, 'UTF-8');
require __DIR__ . '/../layout/header.php';
?>

<div class="d-flex align-items-center gap-3 mb-4">
  <a href="<?= dirname(BASE_URL) ?>/" class="btn btn-sm btn-light" title="Back to Dashboard">
    <i class="bi bi-grid-3x3-gap me-1"></i>Dashboard
  </a>
  <div>
    <h4 class="fw-bold mb-0"><?= $mode === 'create' ? 'New Project' : 'Edit Project' ?></h4>
    <p class="text-muted mb-0 small">Configure once — used across all Savit engines for this client.</p>
  </div>
</div>

<?php
// Fetch AI Research Prompts for this project
$researchedPrompts = [];
if ($mode === 'edit' && !empty($project['id'])) {
    try {
        $db = \CAE\Lib\Database::getInstance();
        $researchedPrompts = $db->fetchAll("SELECT id, prompt_text, visibility_score FROM brand_prompts WHERE brand_id = ? ORDER BY id DESC", [(int)$project['id']]);
    } catch (\Throwable $e) {}
}
?>

<?php
// Show OAuth success flash from callback redirect
if (!empty($_GET['oauth_success'])):
  $svc = strtoupper(htmlspecialchars($_GET['oauth_success']));
?>
<div class="alert alert-success alert-dismissible mb-3">
  <i class="bi bi-check-circle me-1"></i><?= $svc ?> connected successfully. You can now view performance data in the Audit Engine.
  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="POST" action="<?= $action ?>" id="project-form">

  <!-- Tab nav -->
  <div class="card border-0 shadow-sm mb-0">
    <div class="card-header p-0 bg-white border-bottom">
      <ul class="nav nav-tabs border-0 px-3 pt-2" id="project-tabs" role="tablist">
        <li class="nav-item">
          <button class="nav-link active fw-medium" type="button" data-bs-toggle="tab" data-bs-target="#tab-overview">
            <i class="bi bi-building me-1"></i>Business
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link fw-medium" type="button" data-bs-toggle="tab" data-bs-target="#tab-tracking">
            <i class="bi bi-graph-up me-1"></i>Analytics
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link fw-medium" type="button" data-bs-toggle="tab" data-bs-target="#tab-brand">
            <i class="bi bi-mic me-1"></i>Brand &amp; Content
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link fw-medium" type="button" data-bs-toggle="tab" data-bs-target="#tab-integrations">
            <i class="bi bi-plug me-1"></i>Google Connect
          </button>
        </li>
      </ul>
    </div>

    <div class="tab-content">

      <!-- ── Tab 1: Business ─────────────────────────────────────────── -->
      <div class="tab-pane fade show active p-4" id="tab-overview">
        <div class="row g-4">
          <!-- Core identity -->
          <div class="col-12">
            <div class="p-3 border rounded bg-light">
              <h6 class="fw-semibold mb-3 text-muted d-flex align-items-center gap-2">
                <i class="bi bi-building text-primary"></i> Core Identity
              </h6>
              <div class="row g-3">
                <div class="col-md-4">
                  <label class="form-label fw-medium">Business Name <span class="text-danger">*</span></label>
                  <input type="text" name="business_name" class="form-control" value="<?= $v('business_name') ?>" required placeholder="e.g. Savit Interactive">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">Website URL</label>
                  <input type="url" name="website_url" class="form-control" value="<?= $v('website_url') ?>" placeholder="https://example.com">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">Content Intent</label>
                  <select name="content_intent" class="form-select">
                    <option value="">— Select —</option>
                    <?php foreach (['Educate', 'Generate Leads', 'Drive Sales', 'Build Authority', 'Brand Awareness', 'SEO Traffic'] as $opt): ?>
                    <option value="<?= $opt ?>" <?= ($project['content_intent'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-medium">Target Audience</label>
                  <textarea name="target_audience" class="form-control" rows="2" placeholder="Demographics, interests, pain points, knowledge level…"><?= $v('target_audience') ?></textarea>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-medium">Brand Positioning</label>
                  <textarea name="brand_positioning" class="form-control" rows="2" placeholder="Unique value proposition — what sets this brand apart?"><?= $v('brand_positioning') ?></textarea>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-medium">Brand Guideline Document</label>
                  <input type="url" name="guideline_doc_url" class="form-control" value="<?= $v('guideline_doc_url') ?>" placeholder="Google Docs / Notion / Confluence URL">
                </div>
              </div>
            </div>
          </div>

          <!-- Business classification + team (mirrors Analytics tab fields) -->
          <div class="col-12">
            <div class="p-3 border rounded bg-light">
              <h6 class="fw-semibold mb-3 text-muted d-flex align-items-center gap-2">
                <i class="bi bi-people text-success"></i> Classification &amp; Team
              </h6>
              <div class="row g-3">
                <div class="col-md-2">
                  <label class="form-label fw-medium">Business ID</label>
                  <input type="text" name="business_id" class="form-control" value="<?= $v('business_id') ?>" placeholder="SI022">
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-medium">Category</label>
                  <input type="text" name="business_category" class="form-control" value="<?= $v('business_category') ?>" placeholder="Professional Services">
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-medium">Sub-Category</label>
                  <input type="text" name="business_sub_category" class="form-control" value="<?= $v('business_sub_category') ?>" placeholder="HR / Recruitment">
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-medium">Revenue (₹/mo)</label>
                  <input type="number" name="revenue_managed" class="form-control" value="<?= $v('revenue_managed') ?>" placeholder="50000">
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-medium">Onboard Date</label>
                  <input type="date" name="onboard_date" class="form-control" value="<?= $v('onboard_date') ?>">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">SEO Head</label>
                  <input type="text" name="seo_head" class="form-control" value="<?= $v('seo_head') ?>" placeholder="Milan">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">Manager</label>
                  <input type="text" name="manager_name" class="form-control" value="<?= $v('manager_name') ?>" placeholder="Vikas">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">Sr Analyst</label>
                  <input type="text" name="sr_analyst" class="form-control" value="<?= $v('sr_analyst') ?>" placeholder="Sachin">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- ── Tab 2: Brand Voice & SEO (merged) ──────────────────────── -->
      <div class="tab-pane fade p-4" id="tab-brand">
        <p class="text-muted small mb-4">How the brand writes and what it optimises for. Injected into every content prompt and QA check.</p>
        <div class="row g-3">

          <!-- Voice settings -->
          <div class="col-md-4">
            <label class="form-label fw-medium">Tone &amp; Voice</label>
            <select name="tone_voice" class="form-select">
              <?php foreach (['professional', 'conversational', 'authoritative', 'friendly', 'witty', 'empathetic', 'formal', 'casual', 'inspirational'] as $opt): ?>
              <option value="<?= $opt ?>" <?= ($project['tone_voice'] ?? 'professional') === $opt ? 'selected' : '' ?>><?= ucfirst($opt) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label fw-medium">Point of View</label>
            <select name="pov_type" class="form-select">
              <?php foreach (['first_person' => 'First Person (I/We)', 'second_person' => 'Second Person (You)', 'third_person' => 'Third Person (They/It)'] as $val => $label): ?>
              <option value="<?= $val ?>" <?= ($project['pov_type'] ?? 'third_person') === $val ? 'selected' : '' ?>><?= $label ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label fw-medium">CTA Style</label>
            <input type="text" name="cta_style" class="form-control" value="<?= $v('cta_style') ?>" placeholder="e.g. Book a free consultation">
          </div>
          <div class="col-12">
            <label class="form-label fw-medium">Brand Reference Style</label>
            <input type="text" name="brand_reference_style" class="form-control" value="<?= $v('brand_reference_style') ?>" placeholder="e.g. Always 'Savit', never 'the company'">
          </div>
          <div class="col-md-6">
            <label class="form-label fw-medium text-success"><i class="bi bi-check2 me-1"></i>Brand DOs</label>
            <textarea name="brand_dos" class="form-control" rows="4" placeholder="e.g.&#10;- Always mention the 10-year guarantee&#10;- Use Oxford comma&#10;- Include data and statistics"><?= $v('brand_dos') ?></textarea>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-medium text-danger"><i class="bi bi-x me-1"></i>Brand DON'Ts</label>
            <textarea name="brand_donts" class="form-control" rows="4" placeholder="e.g.&#10;- Never name competitors&#10;- Avoid aggressive sales language&#10;- No unverified claims"><?= $v('brand_donts') ?></textarea>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-medium"><i class="bi bi-slash-circle me-1 text-warning"></i>No-No Words / Phrases</label>
            <textarea name="no_no_words" class="form-control" rows="2" placeholder="cheap, best in class, guaranteed, revolutionary"><?= $v('no_no_words') ?></textarea>
            <div class="form-text">Comma-separated. Flagged in QA checks.</div>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-medium">Compliance Rules</label>
            <textarea name="compliance_rules" class="form-control" rows="2" placeholder="e.g. No medical claims. FTC disclosure required for sponsored content."><?= $v('compliance_rules') ?></textarea>
          </div>

          <!-- SEO Philosophy (merged from old Tab 3) -->
          <div class="col-12 mt-2">
            <hr class="my-1">
            <label class="form-label fw-medium mt-2"><i class="bi bi-search me-1 text-primary"></i>SEO Philosophy &amp; Guidelines</label>
            <textarea name="seo_philosophy" class="form-control" rows="5"
              placeholder="Describe your SEO approach. e.g.&#10;- Target long-tail, low-competition keywords&#10;- Prioritise semantic relevance over keyword density&#10;- Internal link to product pages naturally&#10;- Always include an FAQ section&#10;- Use schema markup hints in content"><?= $v('seo_philosophy') ?></textarea>
            <div class="form-text">Injected into every content generation prompt for this project.</div>
          </div>
        </div>
      </div>

      <!-- ── Tab 2: Analytics ─────────────────────────────────────────── -->
      <div class="tab-pane fade p-4" id="tab-tracking">
        <div class="row g-4">

          <!-- GA4 + GSC config -->
          <div class="col-12">
            <div class="p-3 border rounded bg-light">
              <h6 class="fw-semibold mb-3 text-muted d-flex align-items-center gap-2">
                <i class="bi bi-bar-chart-fill text-warning"></i> GA4 &amp; GSC Configuration
                <span class="badge bg-success-subtle text-success ms-auto" style="font-size:.65rem;">Used in Analytics Engine</span>
              </h6>
              <div class="row g-3">
                <div class="col-md-4">
                  <label class="form-label fw-medium"><i class="bi bi-bar-chart-fill text-warning me-1"></i>GA4 Property ID</label>
                  <input type="text" name="ga4_property_id" class="form-control" value="<?= $v('ga4_property_id') ?>" placeholder="e.g. 255874641">
                  <div class="form-text">GA4 → Admin → Property Settings → Property ID</div>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium"><i class="bi bi-search text-primary me-1"></i>GSC Site URL</label>
                  <input type="url" name="gsc_site_url" class="form-control" value="<?= $v('gsc_site_url') ?>" placeholder="https://www.example.com/">
                  <div class="form-text">Must exactly match the GSC property URL</div>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">Brand Term Regex</label>
                  <input type="text" name="brand_term_regex" class="form-control font-monospace" value="<?= $v('brand_term_regex') ?>" placeholder="e.g. Prompt|promptpersonnel">
                  <div class="form-text">Splits branded vs non-branded GSC clicks</div>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-medium">AI Overview Event</label>
                  <input type="text" name="ai_overview_event" class="form-control" value="<?= $v('ai_overview_event') ?>" placeholder="e.g. snippet_text">
                  <div class="form-text">GA4 event that fires for AI Overview impressions</div>
                </div>
              </div>
            </div>
          </div>

          <!-- Lead Categories -->
          <div class="col-12">
            <div class="p-3 border rounded">
              <h6 class="fw-semibold mb-1 d-flex align-items-center gap-2">
                <i class="bi bi-telephone-fill text-success"></i> Lead Categories
                <span class="badge bg-info-subtle text-info ms-1" style="font-size:.65rem;">GA4 event grouping for Analytics reports</span>
              </h6>
              <p class="text-muted small mb-3">Group GA4 events into lead types. CPL override takes priority over the global rate in <code>PPC/config.json</code>.</p>
              <?php
              $rawCats = $project['lead_categories'] ?? '';
              if (is_string($rawCats)) $rawCats = json_decode($rawCats, true) ?: [];
              $defaultCats = empty($rawCats) ? [
                  ['key' => 'calls',    'label' => 'Calls',    'events' => [], 'cpl_override' => null],
                  ['key' => 'forms',    'label' => 'Forms',    'events' => [], 'cpl_override' => null],
                  ['key' => 'whatsapp', 'label' => 'WhatsApp', 'events' => [], 'cpl_override' => null],
                  ['key' => 'email',    'label' => 'Email',    'events' => [], 'cpl_override' => null],
              ] : $rawCats;
              ?>
              <!-- Header row -->
              <div class="row g-2 mb-1" style="font-size:.72rem;font-weight:600;color:#64748b;padding:0 8px;">
                <div class="col-md-2">Key</div>
                <div class="col-md-2">Display Label</div>
                <div class="col-md-5">GA4 Event Names <span class="fw-normal">(comma-separated)</span></div>
                <div class="col-md-2">CPL Override (₹)</div>
                <div class="col-md-1"></div>
              </div>
              <div id="lead-cats-container">
                <?php foreach ($defaultCats as $i => $cat): ?>
                <div class="lead-cat-row row g-2 align-items-center mb-2 p-2 border rounded bg-white" data-idx="<?= $i ?>">
                  <div class="col-md-2">
                    <input type="text" name="lead_cat_key[<?= $i ?>]" class="form-control form-control-sm font-monospace"
                           value="<?= htmlspecialchars($cat['key'] ?? '') ?>" placeholder="calls">
                  </div>
                  <div class="col-md-2">
                    <input type="text" name="lead_cat_label[<?= $i ?>]" class="form-control form-control-sm"
                           value="<?= htmlspecialchars($cat['label'] ?? '') ?>" placeholder="Calls">
                  </div>
                  <div class="col-md-5">
                    <input type="text" name="lead_cat_events[<?= $i ?>]" class="form-control form-control-sm"
                           value="<?= htmlspecialchars(implode(', ', $cat['events'] ?? [])) ?>"
                           placeholder="Click To Call, GMB Call Button">
                  </div>
                  <div class="col-md-2">
                    <input type="number" name="lead_cat_cpl[<?= $i ?>]" class="form-control form-control-sm"
                           value="<?= $cat['cpl_override'] !== null ? htmlspecialchars((string)$cat['cpl_override']) : '' ?>"
                           placeholder="Use global">
                  </div>
                  <div class="col-md-1 text-end">
                    <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2 remove-cat-btn">✕</button>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>
              <input type="hidden" name="lead_categories_json" id="lead-categories-json">
              <button type="button" class="btn btn-sm btn-outline-primary mt-1" id="add-cat-btn">
                <i class="bi bi-plus me-1"></i>Add Lead Category
              </button>
            </div>
          </div>

          <!-- Page Categories (Audit URL grouping) -->
          <div class="col-12">
            <div class="p-3 border rounded">
              <h6 class="fw-semibold mb-1 d-flex align-items-center gap-2">
                <i class="bi bi-tags-fill text-primary"></i> Page Categories
                <span class="badge bg-primary-subtle text-primary ms-1" style="font-size:.65rem;">URL grouping for Audit + Reporting filters</span>
                <?php if ($mode === 'edit'): ?>
                <button type="button" class="btn btn-xs btn-outline-secondary ms-auto py-0 px-2" style="font-size:.7rem;" id="reload-page-cats-btn">
                  <i class="bi bi-arrow-clockwise me-1"></i>Reload
                </button>
                <?php endif; ?>
              </h6>
              <p class="text-muted small mb-3">Group website pages by URL pattern. Used to filter crawl data in Audit Engine and segment reports. Changes are saved live via API (no form submit needed).</p>

              <?php if ($mode !== 'edit'): ?>
              <div class="alert alert-info small py-2">
                <i class="bi bi-info-circle me-1"></i>Save the project first, then manage page categories here.
              </div>
              <?php else: ?>
              <div id="page-cats-area">
                <div class="text-muted small py-2"><span class="spinner-border spinner-border-sm me-1"></span>Loading categories…</div>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <!-- Rank Tracking -->
          <div class="col-12">
            <div class="p-3 border rounded bg-light">
              <h6 class="fw-semibold mb-3 text-muted d-flex align-items-center gap-2">
                <i class="bi bi-trophy text-warning"></i> Rank Tracking
                <span class="badge bg-secondary-subtle text-secondary ms-1" style="font-size:.6rem;">Coming Soon</span>
              </h6>
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label fw-medium">Primary Keywords</label>
                  <textarea name="rank_keywords" class="form-control font-monospace" rows="4"
                    placeholder="One keyword per line:&#10;seo company india&#10;digital marketing agency mumbai"><?= $v('rank_keywords') ?></textarea>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-medium">Competitor Domains</label>
                  <textarea name="rank_competitors" class="form-control font-monospace" rows="4"
                    placeholder="One domain per line:&#10;competitor1.com"><?= $v('rank_competitors') ?></textarea>
                </div>
                <div class="col-12">
                  <label class="form-label fw-medium"><i class="bi bi-robot me-1"></i>AI Prompt Tracking Queries</label>
                  <textarea name="prompt_queries" class="form-control font-monospace" rows="3"
                    placeholder="best seo company in india&#10;top digital marketing agencies mumbai"><?= $v('prompt_queries') ?></textarea>
                  <div class="form-text">Submitted to ChatGPT/Gemini/Perplexity to track brand mentions.</div>
                </div>

                <?php if (!empty($researchedPrompts)): ?>
                <div class="col-12 mt-3">
                  <div class="p-3 border rounded bg-white">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                      <h6 class="fw-bold mb-0 text-primary small text-uppercase tracking-wider">Researched Tracking Queries</h6>
                      <a href="<?= BASE_URL ?>/projects/<?= $project['id'] ?>/research" class="btn btn-xs btn-outline-primary py-0 px-2" style="font-size: 11px;">Manage All</a>
                    </div>
                    <div class="table-responsive">
                      <table class="table table-sm table-borderless align-middle mb-0" style="font-size: 12px;">
                        <thead>
                          <tr class="text-muted border-bottom">
                            <th>Prompt Query</th>
                            <th class="text-center">Visibility</th>
                            <th class="text-end">Action</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php foreach ($researchedPrompts as $rp): ?>
                          <tr class="border-bottom-dashed">
                            <td class="py-2">
                              <div class="fw-medium"><?= htmlspecialchars($rp['prompt_text']) ?></div>
                            </td>
                            <td class="text-center py-2">
                              <span class="badge rounded-pill <?= $rp['visibility_score'] >= 70 ? 'bg-success-subtle text-success' : ($rp['visibility_score'] >= 40 ? 'bg-warning-subtle text-warning' : 'bg-danger-subtle text-danger') ?>">
                                <?= $rp['visibility_score'] ?>%
                              </span>
                            </td>
                            <td class="text-end py-2">
                              <a href="<?= BASE_URL ?>/research/<?= $rp['id'] ?>" class="btn btn-xs btn-link p-0 text-muted" title="View Details"><i class="bi bi-eye"></i></a>
                            </td>
                          </tr>
                          <?php endforeach; ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
                <?php endif; ?>
              </div>
            </div>
          </div>

        </div>
      </div>

      <!-- ── Tab 3: Brand & Content ────────────────────────────────────── -->
      <!-- (moved to after Analytics; old Tab 2 content) -->

      <!-- ── Tab 4: Integrations ────────────────────────────────────── -->
      <div class="tab-pane fade p-4" id="tab-integrations">
        <p class="text-muted small mb-4">Connect Google services to overlay performance data in the Audit Engine and dashboard.</p>

        <?php if ($mode === 'edit'): ?>
        <div id="oauth-status-area">
          <div class="text-center py-4 text-muted small">
            <div class="spinner-border spinner-border-sm me-2"></div>Checking connection status…
          </div>
        </div>
        <?php else: ?>
        <div class="alert alert-info small py-2">
          <i class="bi bi-info-circle me-1"></i>Save the project first, then connect your Google services here.
        </div>
        <?php endif; ?>

        <!-- GBP Location ID (GA4/GSC are in Analytics tab) -->
        <hr class="my-4">
        <div class="alert alert-light border small py-2 mb-3">
          <i class="bi bi-info-circle me-1 text-primary"></i>
          GA4 Property ID and GSC Site URL are configured in the <strong>Analytics tab</strong>.
          Connect your Google account here to authorise data access.
        </div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-medium"><i class="bi bi-geo-alt text-danger me-1"></i>Google Business Profile — Location ID</label>
            <input type="text" name="gbp_location_id" class="form-control" value="<?= $v('gbp_location_id') ?>" placeholder="e.g. locations/12345678901234567">
            <div class="form-text">Found via <a href="https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder" target="_blank">Place ID Finder</a> or GBP dashboard URL.</div>
          </div>
        </div>
      </div>

    </div><!-- /tab-content -->
  </div><!-- /card -->

  <div class="d-flex gap-2 justify-content-between mt-3">
    <a href="<?= dirname(BASE_URL) ?>/" class="btn btn-light"><i class="bi bi-grid-3x3-gap me-1"></i>Dashboard</a>
    <button type="submit" class="btn btn-primary px-4">
      <i class="bi bi-<?= $mode === 'create' ? 'plus-lg' : 'check-lg' ?> me-1"></i>
      <?= $mode === 'create' ? 'Create Project' : 'Save Changes' ?>
    </button>
  </div>

</form>

<script>
(function () {
  const base    = (document.querySelector('meta[name="base-url"]') || {}).content || '';
  const key     = 'project_form_tab';
  const stored  = sessionStorage.getItem(key);

  // Persist active project to localStorage so all engines stay in context
  <?php if ($mode === 'edit' && !empty($project['id'])): ?>
  try {
    localStorage.setItem('savit_project', JSON.stringify({
      id:     <?= (int)$project['id'] ?>,
      name:   <?= json_encode($project['business_name'] ?? '') ?>,
      domain: <?= json_encode($project['website_url']    ?? '') ?>,
    }));
  } catch (_) {}
  <?php endif; ?>
  const hasOauthSuccess = new URLSearchParams(location.search).has('oauth_success');

  function tryShowTab(selector) {
    const btn = document.querySelector(selector);
    if (!btn) return;
    if (window.bootstrap && window.bootstrap.Tab) {
      window.bootstrap.Tab.getOrCreateInstance(btn).show();
    }
  }

  // Restore last-active tab
  if (stored) {
    tryShowTab(`[data-bs-target="${stored}"]`);
  }

  // Auto-open Integrations tab if oauth_success param present
  if (hasOauthSuccess) {
    tryShowTab('[data-bs-target="#tab-integrations"]');
  }

  // If Bootstrap loads after this inline script, retry once on full page load.
  if (!window.bootstrap || !window.bootstrap.Tab) {
    window.addEventListener('load', () => {
      if (stored) tryShowTab(`[data-bs-target="${stored}"]`);
      if (hasOauthSuccess) tryShowTab('[data-bs-target="#tab-integrations"]');
    }, { once: true });
  }

  // Persist active tab
  document.querySelectorAll('#project-tabs button').forEach(btn => {
    btn.addEventListener('shown.bs.tab', () => sessionStorage.setItem(key, btn.dataset.bsTarget));
  });
  document.getElementById('project-form').addEventListener('submit', () => {
    sessionStorage.removeItem(key);
    // Serialize lead categories to JSON before submit
    buildLeadCategoriesJson();
  });

  // ── Load OAuth status (edit mode only) ────────────────────────────────────
  let projectId = <?= (int)($project['id'] ?? 0) ?>;
  const auditBase = window.location.origin + <?= json_encode(rtrim(dirname(BASE_URL), '/') . '/Audit/public') ?>;

  // Fallback: recover project ID from URL in case server-side value is missing.
  if (!projectId) {
    const m = location.pathname.match(/\/projects\/(\d+)\/edit/i);
    if (m) projectId = Number(m[1]) || 0;
  }

  if (projectId > 0) {
    loadOAuthStatus(projectId, auditBase, base);
  }

  async function loadOAuthStatus(projId, auditB, contentB) {
    const area = document.getElementById('oauth-status-area');
    if (!area) return;

    const statusUrl = auditB.replace(/\/+$/, '') + '/api/projects/' + projId + '/oauth/status';
    console.log('Loading OAuth status from:', statusUrl);
    area.innerHTML = `<div class="alert alert-secondary small py-2 d-flex align-items-center justify-content-between">
      <span><i class="bi bi-clock-history me-1"></i>Checking connection status…</span>
      <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
    </div>`;

    try {
      const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
      const timeoutId = controller ? setTimeout(() => controller.abort(), 5000) : null;

      console.log('Starting fetch...');
      const res = await fetch(statusUrl, {
        credentials: 'same-origin',
        headers: { 'Accept': 'application/json' },
        signal: controller ? controller.signal : undefined,
      });
      console.log('Fetch response:', res.status, res.statusText);
      if (timeoutId) clearTimeout(timeoutId);

      if (!res.ok) {
        const body = await res.text();
        console.error('Fetch failed:', res.status, body);
        throw new Error(`HTTP ${res.status} ${res.statusText}: ${body}`);
      }

      const json = await res.json();
      console.log('Response JSON:', json);
      if (!json.success) throw new Error(json.message || 'Unexpected response from Audit Engine');

      const d = json.data;
      if (!d.configured) {
        area.innerHTML = `<div class="alert alert-warning small py-2">
          <i class="bi bi-exclamation-triangle me-1"></i>
          Google OAuth is not fully configured. Add <code>GOOGLE_CLIENT_ID</code>, <code>GOOGLE_CLIENT_SECRET</code>,
          and <code>GOOGLE_REDIRECT_URI</code> to <code>Audit/.env</code> to enable OAuth connections.
        </div>`;
        return;
      }

      area.innerHTML = ['ga4', 'gsc', 'gbp'].map(svc => {
        const info    = d[svc];
        const labels  = { ga4: 'Google Analytics 4', gsc: 'Search Console', gbp: 'Business Profile' };
        const icons   = { ga4: 'bi-bar-chart-fill text-warning', gsc: 'bi-search text-primary', gbp: 'bi-geo-alt text-danger' };

        if (info.connected) {
          return `<div class="d-flex align-items-center justify-content-between border rounded p-3 mb-3">
            <div class="d-flex align-items-center gap-3">
              <i class="bi ${icons[svc]} fs-5"></i>
              <div>
                <div class="fw-medium small">${labels[svc]}</div>
                <div class="text-success small"><i class="bi bi-check-circle me-1"></i>${escHtml(info.email)}</div>
                <div class="text-muted" style="font-size:.7rem;">Last synced: ${escHtml(info.updated_at || '—')}</div>
              </div>
            </div>
            <button type="button" class="btn btn-sm btn-outline-danger py-0" onclick="disconnectOAuth('${svc}', ${projId}, '${auditB}')">
              <i class="bi bi-x me-1"></i>Disconnect
            </button>
          </div>`;
        }

        return `<div class="d-flex align-items-center justify-content-between border rounded p-3 mb-3">
          <div class="d-flex align-items-center gap-3">
            <i class="bi ${icons[svc]} fs-5"></i>
            <div>
              <div class="fw-medium small">${labels[svc]}</div>
              <div class="text-muted small">Not connected</div>
            </div>
          </div>
          <button type="button" class="btn btn-sm btn-outline-primary py-0" onclick="connectOAuth('${svc}', ${projId}, '${auditB}')">
            <i class="bi bi-plug me-1"></i>Connect
          </button>
        </div>`;
      }).join('');

    } catch (e) {
      const message = e.name === 'AbortError'
        ? 'Request to Audit Engine timed out.'
        : `Could not load connection status: ${escHtml(e.message)}`;

      area.innerHTML = ['ga4', 'gsc', 'gbp'].map(svc => {
        const labels  = { ga4: 'Google Analytics 4', gsc: 'Search Console', gbp: 'Business Profile' };
        const icons   = { ga4: 'bi-bar-chart-fill text-warning', gsc: 'bi-search text-primary', gbp: 'bi-geo-alt text-danger' };

        return `<div class="d-flex align-items-center justify-content-between border rounded p-3 mb-3">
          <div class="d-flex align-items-center gap-3">
            <i class="bi ${icons[svc]} fs-5"></i>
            <div>
              <div class="fw-medium small">${labels[svc]}</div>
              <div class="text-muted small">Status unknown — unable to verify connection.</div>
            </div>
          </div>
          <button type="button" class="btn btn-sm btn-outline-primary py-0" onclick="connectOAuth('${svc}', ${projId}, '${auditB}')">
            <i class="bi bi-plug me-1"></i>Connect
          </button>
        </div>`;
      }).join('') + `<div class="alert alert-warning small mt-3">
        <i class="bi bi-exclamation-triangle me-1"></i>${message}
      </div>`;
    }
  }

  window.connectOAuth = async function(service, projId, auditB) {
    const res  = await fetch(auditB + '/api/projects/' + projId + '/oauth/connect', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ service }),
    });
    const json = await res.json();
    if (json.success && json.data.redirect_url) {
      window.location.href = json.data.redirect_url;
    } else {
      alert(json.message || 'Failed to start OAuth flow');
    }
  };

  window.disconnectOAuth = async function(service, projId, auditB) {
    if (!confirm('Disconnect ' + service.toUpperCase() + '? Performance data will no longer load for this project.')) return;
    const res  = await fetch(auditB + '/api/projects/' + projId + '/oauth/disconnect', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ service }),
    });
    const json = await res.json();
    if (json.success) location.reload();
    else alert(json.message || 'Disconnect failed');
  };

  function escHtml(s) {
    const d = document.createElement('div');
    d.appendChild(document.createTextNode(String(s||'')));
    return d.innerHTML;
  }

  // ── Page Categories (Audit URL grouping) ─────────────────────────────────
  const pageCatsArea = document.getElementById('page-cats-area');
  if (pageCatsArea && projectId > 0) {
    loadPageCategories();
    document.getElementById('reload-page-cats-btn')?.addEventListener('click', loadPageCategories);
  }

  async function loadPageCategories() {
    if (!pageCatsArea) return;
    pageCatsArea.innerHTML = '<div class="text-muted small py-1"><span class="spinner-border spinner-border-sm me-1"></span>Loading…</div>';
    try {
      const res  = await fetch(auditBase + '/api/projects/' + projectId + '/categories');
      const json = await res.json();
      if (!json.success) throw new Error(json.message);
      renderPageCats(json.data || []);
    } catch (e) {
      pageCatsArea.innerHTML = `<div class="alert alert-warning small py-2"><i class="bi bi-exclamation-triangle me-1"></i>Could not load: ${escHtml(e.message)}</div>`;
    }
  }

  function renderPageCats(cats) {
    const colorMap = { primary:'#0d6efd', success:'#198754', warning:'#fd7e14', danger:'#dc3545', info:'#0dcaf0', secondary:'#6c757d', dark:'#212529' };
    const rows = cats.map(c => `
      <div class="d-flex align-items-center gap-2 mb-2 p-2 border rounded bg-white page-cat-row" data-id="${c.id}">
        <span style="width:12px;height:12px;border-radius:3px;background:${colorMap[c.color]||'#6c757d'};flex-shrink:0;"></span>
        <input class="form-control form-control-sm" style="max-width:150px;" value="${escHtml(c.name)}" data-field="name">
        <select class="form-select form-select-sm" style="max-width:130px;" data-field="match_type">
          ${['path_prefix','contains','regex','noise_builtin'].map(t => `<option value="${t}" ${c.match_type===t?'selected':''}>${t}</option>`).join('')}
        </select>
        <input class="form-control form-control-sm flex-grow-1" value="${escHtml(c.match_value||'')}" placeholder="e.g. /blog/" data-field="match_value">
        <select class="form-select form-select-sm" style="max-width:100px;" data-field="color">
          ${Object.keys(colorMap).map(cl => `<option value="${cl}" ${c.color===cl?'selected':''}>${cl}</option>`).join('')}
        </select>
        <button type="button" class="btn btn-sm btn-success py-0 px-2 save-page-cat-btn" style="font-size:.7rem;">Save</button>
        <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2 del-page-cat-btn" style="font-size:.7rem;">✕</button>
      </div>`).join('');

    pageCatsArea.innerHTML = rows + `
      <button type="button" class="btn btn-sm btn-outline-primary mt-1" id="add-page-cat-btn">
        <i class="bi bi-plus me-1"></i>Add Page Category
      </button>`;

    pageCatsArea.querySelectorAll('.save-page-cat-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        const row   = btn.closest('.page-cat-row');
        const id    = +row.dataset.id;
        const body  = { name: row.querySelector('[data-field="name"]').value, match_type: row.querySelector('[data-field="match_type"]').value, match_value: row.querySelector('[data-field="match_value"]').value, color: row.querySelector('[data-field="color"]').value };
        const r = await fetch(`${auditBase}/api/projects/${projectId}/categories/${id}`, { method: 'PUT', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
        const j = await r.json();
        if (j.success) { btn.innerHTML='✓'; btn.className='btn btn-sm btn-success py-0 px-2'; setTimeout(()=>{btn.innerHTML='Save';},1500); }
        else alert(j.message);
      });
    });

    pageCatsArea.querySelectorAll('.del-page-cat-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        const row = btn.closest('.page-cat-row');
        const id  = +row.dataset.id;
        if (!confirm('Delete this category?')) return;
        const r = await fetch(`${auditBase}/api/projects/${projectId}/categories/${id}`, { method: 'DELETE' });
        const j = await r.json();
        if (j.success) row.remove(); else alert(j.message);
      });
    });

    pageCatsArea.querySelector('#add-page-cat-btn')?.addEventListener('click', async () => {
      const name = prompt('New category name:');
      if (!name) return;
      const r = await fetch(`${auditBase}/api/projects/${projectId}/categories`, {
        method: 'POST', headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ name, match_type: 'path_prefix', match_value: '', color: 'primary' })
      });
      const j = await r.json();
      if (j.success) loadPageCategories(); else alert(j.message);
    });
  }

  // ── Lead Categories dynamic UI ────────────────────────────────────────────
  let catIdx = document.querySelectorAll('.lead-cat-row').length;

  function buildLeadCategoriesJson() {
    const rows = document.querySelectorAll('.lead-cat-row');
    const cats = [];
    rows.forEach(row => {
      const i      = row.dataset.idx;
      const key    = (document.querySelector(`[name="lead_cat_key[${i}]"]`)?.value || '').trim();
      const label  = (document.querySelector(`[name="lead_cat_label[${i}]"]`)?.value || '').trim();
      const events = (document.querySelector(`[name="lead_cat_events[${i}]"]`)?.value || '')
                       .split(',').map(e => e.trim()).filter(Boolean);
      const cpl    = document.querySelector(`[name="lead_cat_cpl[${i}]"]`)?.value;
      if (key) {
        cats.push({ key, label: label || key, events, cpl_override: cpl ? +cpl : null });
      }
    });
    document.getElementById('lead-categories-json').value = JSON.stringify(cats);
  }

  document.getElementById('add-cat-btn')?.addEventListener('click', () => {
    const container = document.getElementById('lead-cats-container');
    const div = document.createElement('div');
    div.className = 'lead-cat-row row g-2 align-items-start mb-2 p-2 border rounded bg-light';
    div.dataset.idx = catIdx;
    div.innerHTML = `
      <div class="col-md-2"><label class="form-label small fw-medium">Key</label>
        <input type="text" name="lead_cat_key[${catIdx}]" class="form-control form-control-sm font-monospace" placeholder="calls"></div>
      <div class="col-md-2"><label class="form-label small fw-medium">Label</label>
        <input type="text" name="lead_cat_label[${catIdx}]" class="form-control form-control-sm" placeholder="Calls"></div>
      <div class="col-md-5"><label class="form-label small fw-medium">GA4 Event Names <span class="text-muted">(comma-separated)</span></label>
        <input type="text" name="lead_cat_events[${catIdx}]" class="form-control form-control-sm" placeholder="Click To Call, GMB Call"></div>
      <div class="col-md-2"><label class="form-label small fw-medium">CPL Override (₹)</label>
        <input type="number" name="lead_cat_cpl[${catIdx}]" class="form-control form-control-sm" placeholder="Global"></div>
      <div class="col-md-1 d-flex align-items-end pb-1">
        <button type="button" class="btn btn-sm btn-outline-danger py-1 remove-cat-btn">✕</button></div>`;
    container.appendChild(div);
    catIdx++;
  });

  document.addEventListener('click', e => {
    if (e.target.classList.contains('remove-cat-btn')) {
      e.target.closest('.lead-cat-row')?.remove();
    }
  });
})();
</script>

<?php require __DIR__ . '/../layout/footer.php'; ?>
