<?php
session_start();
require_once "../config/db.php"; // adjust path to your DB connection
$stmt = $pdo->query("SELECT name FROM secondary_keyword ORDER BY name ASC");
$secondary_keyword = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Mock data (later this can come from DB)
$locations = ["Dubai", "London", "New York", "Mumbai", "Sydney"];

// Function to create slugs
function slugify($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    return strtolower($text);
}

$generatedPages = [];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $primarykw = trim($_POST["primary-keyword"]);
    $selectedSecKey = $_POST["secondary_keyword"] ?? [];
    $selectedLocations = $_POST["locations"] ?? [];

    foreach ($selectedSecKey as $sk) {
        foreach ($selectedLocations as $loc) {
            $title = "$primarykw $sk in $loc";
            $slug = slugify($title);

            // Avoid duplicates
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM pages WHERE slug = ?");
            $stmt->execute([$slug]);
            if ($stmt->fetchColumn() == 0) {
                $stmt = $pdo->prepare("
                    INSERT INTO pages (title, slug, main_title, main_description, meta_title, meta_description, meta_keywords) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $title,
                    $slug,
                    $title, // main_title same as title
                    "This is the main description for $title.",
                    $title, // meta_title
                    "Meta description for $title.",
                    strtolower($primarykw) . ", " . strtolower($sk) . ", " . strtolower($loc)
                ]);
            }

            $generatedPages[] = ["title" => $title, "slug" => $slug];
        }
    }
}

// Not logged in → redirect
if (!isset($_SESSION["admin_logged_in"])) {
  header("Location: /admin/login.php");
  exit;
}

// Logged in but not superadmin → redirect to products
if ($_SESSION["admin_role"] !== "superadmin") {
  header("Location: admin/products");
  exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Page Generator</title>
    <link href="https://fonts.googleapis.com/css2?family=Urbanist:wght@300;400;500;600;700;900&display=swap"
    rel="stylesheet">

    <link rel="stylesheet" href="./assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="./assets/css/slick.css">
    <link rel="stylesheet" href="./assets/css/style.css">
    <link rel="stylesheet" href="./assets/css/responsive.css">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .section { margin-bottom: 20px; }
        label { margin-right: 10px; }
        .checkbox-group { display: flex; flex-wrap: wrap; gap: 10px; }
        .result { background: #f9f9f9; padding: 10px; border: 1px solid #ccc; margin-top: 20px; }
    </style>
</head>
<body>
<div class="body-bg">
<?php include 'includes/sidebar.php'; ?>


<section class="nftmax-adashboard nftmax-show">


<h2>Create Dynamic Pages</h2>
<form method="post" class="mt-3">
    <div class="section">
        <strong>Primary Keyword:</strong>
        <input class="form-control w-auto" type="text" name="primary-keyword" placeholder="Enter Primary Keyword" required>
    </div>

    <div class="section">
    <strong>Select Secondary Keyword:</strong>
    <div>
        <label>
            <input type="checkbox" id="selectAllSubcats"> <strong>Select / Unselect All</strong>
        </label>
    </div>
    <div class="checkbox-group" id="subcatGroup">
        <?php foreach ($secondary_keyword as $sk): ?>
            <label>
                <input type="checkbox" name="secondary_keyword[]" value="<?= $sk ?>"> <?= $sk ?>
            </label>
        <?php endforeach; ?>
    </div>
</div>



<div class="section">
  <strong>Select Location:</strong>
  <div class="row">
    <div class="col-md-4">
      <label>Country</label>
      <select id="country" class="form-control">
        <option value="">-- Select Country --</option>
        <option value="__all__">All Countries</option>
      </select>
    </div>
    <div class="col-md-4">
      <label>State</label>
      <select id="state" class="form-control">
        <option value="">-- Select State --</option>
        <option value="__all__">All States</option>
      </select>
    </div>
    <div class="col-md-4">
      <label>City</label>
      <select id="city" class="form-control">
        <option value="">-- Select City --</option>
        <option value="__all__">All Cities</option>
      </select>
    </div>
  </div>

  <!-- Hidden inputs will be injected here before submit -->
  <div id="locationsContainer"></div>
</div>

    <button style="width: auto;" class="btn-one" type="submit">Generate Pages</button>
    <a href="all-pages.php" style="display: block; width: auto; color: black !important; text-decoration:underline" type="submit">View Generated Pages</a>
</form>

<?php if (!empty($generatedPages)): ?>
    <div class="result">
        <h3>Generated & Stored Pages:</h3>
        <ul>
            <?php foreach ($generatedPages as $page): ?>
                <li>
                    <a target="_blank" href="page.php?slug=<?= urlencode($page["slug"]) ?>">
                        <?= htmlspecialchars($page["title"]) ?>
                    </a>
                    — <em><?= $page["slug"] ?></em>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

</section>

</div>


<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script>
<script src="./assets/js/jquery-3.6.3.min.js"></script>
  <script src="./assets/js/slick.min.js"></script>
  <script src="./assets/js/bootstrap.bundle.min.js"></script>
  <script src="./assets/js/chart.js"></script>
  <script src="./assets/js/custom.js"></script>
  <script src="./assets/js/modeControl.js"></script>

  <script>
  // Select/Unselect All secondary_keyword
  document.getElementById('selectAllSubcats').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('#subcatGroup input[type="checkbox"]');
    checkboxes.forEach(cb => cb.checked = this.checked);
  });

  let countriesData = [];

  // Load JSON (ensure the path is correct)
  fetch("countries-states-cities.json")
    .then(res => res.json())
    .then(data => {
      countriesData = data;
      populateCountries();
    });

  // Populate Country dropdown
  function populateCountries() {
    const countrySelect = document.getElementById("country");
    countriesData.forEach(country => {
      const option = document.createElement("option");
      option.value = country.name;
      option.textContent = country.name;
      countrySelect.appendChild(option);
    });
  }

  // Country change → load states
  document.getElementById("country").addEventListener("change", function() {
    const stateSelect = document.getElementById("state");
    const citySelect = document.getElementById("city");
    stateSelect.innerHTML = '<option value="">-- Select State --</option><option value="__all__">All States</option>';
    citySelect.innerHTML = '<option value="">-- Select City --</option><option value="__all__">All Cities</option>';

    if (this.value === "__all__" || !this.value) {
      return; // All countries or none selected → nothing else to populate
    }

    const selectedCountry = countriesData.find(c => c.name === this.value);
    if (selectedCountry && Array.isArray(selectedCountry.states)) {
      selectedCountry.states.forEach(state => {
        const option = document.createElement("option");
        option.value = state.name;
        option.textContent = state.name;
        stateSelect.appendChild(option);
      });
    }
  });

  // State change → load cities
  document.getElementById("state").addEventListener("change", function() {
    const citySelect = document.getElementById("city");
    citySelect.innerHTML = '<option value="">-- Select City --</option><option value="__all__">All Cities</option>';

    if (this.value === "__all__" || !this.value) {
      return; // All states or none selected → don't populate cities
    }

    const selectedCountry = countriesData.find(c => c.name === document.getElementById("country").value);
    if (!selectedCountry) return;

    const selectedState = (selectedCountry.states || []).find(s => s.name === this.value);
    if (selectedState && Array.isArray(selectedState.cities)) {
      selectedState.cities.forEach(city => {
        const option = document.createElement("option");
        option.value = city.name;
        option.textContent = city.name;
        citySelect.appendChild(option);
      });
    }
  });

  // Build locations[] before submit
  document.querySelector('form').addEventListener('submit', function(e) {
    const countryVal = document.getElementById('country').value;
    const stateVal   = document.getElementById('state').value;
    const cityVal    = document.getElementById('city').value;

    const locations = deriveLocations(countryVal, stateVal, cityVal);

    if (locations.length === 0) {
      alert('Please select a Country/State/City or an "All" option.');
      e.preventDefault();
      return;
    }

    // Inject hidden inputs
    const container = document.getElementById('locationsContainer');
    container.innerHTML = '';
    // Remove duplicates & empty
    const unique = [...new Set(locations.filter(Boolean))];
    unique.forEach(loc => {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = 'locations[]';
      input.value = loc;
      container.appendChild(input);
    });
  });

  function deriveLocations(countryVal, stateVal, cityVal) {
    // 1) All Countries
    if (countryVal === '__all__') {
      return countriesData.map(c => c.name);
    }

    const selectedCountry = countriesData.find(c => c.name === countryVal);

    // 2) All States (for a specific country)
    if (selectedCountry && stateVal === '__all__') {
      return (selectedCountry.states || []).map(s => s.name);
    }

    // 3) All Cities (for a specific state)
    if (selectedCountry && cityVal === '__all__') {
      const selectedState = (selectedCountry.states || []).find(s => s.name === stateVal);
      if (!selectedState) return [];
      return (selectedState.cities || []).map(ci => ci.name);
    }

    // 4) Specific selections
    if (cityVal) return [cityVal];
    if (stateVal) return [stateVal];
    if (countryVal) return [countryVal];

    return [];
  }
</script>


</body>
</html>
