<?php
require_once "../../config/db.php";
session_start();

// Slugify function (same as in product-save.php)
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);
}

// Fetch categories for dropdown
$catStmt = $pdo->query("SELECT id, name FROM categories ORDER BY name ASC");
$categories = $catStmt->fetchAll(PDO::FETCH_ASSOC);

// If editing
$product = null;
$usedLocations = [];
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $id = intval($_GET['id']);
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    // Fetch already generated product pages for this product
    $existingPagesStmt = $pdo->prepare("SELECT slug FROM product_page WHERE product_id = ?");
    $existingPagesStmt->execute([$id]);
    $existingPages = $existingPagesStmt->fetchAll(PDO::FETCH_COLUMN);

    // Extract clean location part from each slug
    foreach ($existingPages as $slug) {
        $pattern = "/^" . preg_quote(slugify($product['name']), '/') . "-.*?-/";
        $cleanSlug = preg_replace($pattern, "", $slug);
        $usedLocations[] = strtolower(str_replace("-", " ", $cleanSlug));
    }
}

if (!isset($_SESSION["admin_logged_in"])) {
    header("Location: /admin/login.php");
    exit;
}
?>
<!DOCTYPE html>
<html>

<head>
    <title>Add / Edit Projects</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
</head>

<body>
<div class="body-bg">
    <?php include '../includes/sidebar.php'; ?>

    <section class="nftmax-adashboard nftmax-show">
        <div class="heading d-block">
            <h3><?= $product ? 'Edit' : 'Add' ?> Project</h3>
        </div>

        <form action="product-save.php" method="POST" enctype="multipart/form-data" class="mt-4">
            <?php if ($product): ?>
                <input type="hidden" name="id" value="<?= $product['id'] ?>">
            <?php endif; ?>

            <div class="row">
                <!-- Product Info -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Project Name</label>
                    <input type="text" name="product_name" class="form-control" required
                        value="<?= htmlspecialchars($product['name'] ?? '') ?>">
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>"
                                <?= ($product && $product['category_id'] == $cat['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cat['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Featured Product</label><br>
                    <input type="checkbox" id="featured_product" name="featured_product" value="1"
                        <?= !empty($product['featured_product']) ? 'checked' : '' ?>>
                    <label for="featured_product">Mark as Featured</label>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Project Tags (comma separated)</label>
                    <input type="text" name="product_tags" class="form-control"
                        value="<?php
                                if ($product) {
                                    $tagStmt = $pdo->prepare('SELECT tag_name FROM product_tags WHERE product_id = ?');
                                    $tagStmt->execute([$product['id']]);
                                    $tags = $tagStmt->fetchAll(PDO::FETCH_COLUMN);
                                    echo htmlspecialchars(implode(', ', $tags));
                                }
                                ?>">
                    </div>

                <!-- ✅ NEW: Challenges -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Challenges</label>
                    <textarea name="challenges" class="form-control" rows="3" placeholder="Enter challenges faced"><?= htmlspecialchars($product['challenges'] ?? '') ?></textarea>
                </div>

                <!-- ✅ NEW: Solutions -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Solutions</label>
                    <textarea name="solutions" class="form-control" rows="3" placeholder="Enter solutions implemented"><?= htmlspecialchars($product['solutions'] ?? '') ?></textarea>
                </div>



                    <div class="col-md-12 mb-3">
                        <label class="form-label d-block">Project Image</label>
                        <p class="text-success">Preferred Dimension: 1920x600</p>
                        <input type="file" name="product_image" class="form-control" accept="image/*">

                        <div id="imagePreview" class="mt-3">
                            <?php if (!empty($product['image'])): ?>
                                <div class="position-relative d-inline-block">
                                    <img src="../uploads/<?= htmlspecialchars($product['image']) ?>" width="120" class="rounded shadow">
                                    <button type="button" class="btn btn-danger btn-sm position-absolute top-0 end-0 delete-image" data-img="<?= htmlspecialchars($product['image']) ?>">×</button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="col-md-12 mb-3">
                        <label class="form-label">Project Overview</label>
                        <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($product['description'] ?? '') ?></textarea>
                    </div>
                    
                    <!-- ✅ Result Field -->
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Result</label>
                        <textarea name="result" class="form-control" rows="3" placeholder="Enter project results"><?= htmlspecialchars($product['result'] ?? '') ?></textarea>
                    </div>

                    <!-- ✅ Dynamic Descriptions -->
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Dynamic Description 1</label>
                        <textarea name="dynamic_description_1" class="form-control" rows="3" placeholder="You can use variables: $primarykw, $seckw, $loc"><?= htmlspecialchars($product['dynamic_description_1'] ?? '') ?></textarea>
                        <small class="text-muted">Use variables: <code>$primarykw</code>, <code>$seckw</code>, <code>$loc</code></small>
                    </div>

                    <div class="col-md-12 mb-3">
                        <label class="form-label">Dynamic Description 2</label>
                        <textarea name="dynamic_description_2" class="form-control" rows="3" placeholder="You can use variables: $primarykw, $seckw, $loc"><?= htmlspecialchars($product['dynamic_description_2'] ?? '') ?></textarea>
                        <small class="text-muted">Use variables: <code>$primarykw</code>, <code>$seckw</code>, <code>$loc</code></small>
                    </div>


    <!-- ✅ Testimonial Section -->
    <div class="col-md-12 mb-3">
        <h5>Client Testimonial</h5>
        <?php
        $testimonial = [];
        if (!empty($product['testimonial'])) {
            $testimonial = json_decode($product['testimonial'], true) ?? [];
        }
        ?>
        <div class="row">
            <div class="col-md-4 mb-2">
                <label class="form-label">Client Name</label>
                <input type="text" name="testimonial_client_name" class="form-control"
                    value="<?= htmlspecialchars($testimonial['client_name'] ?? '') ?>">
            </div>
            <div class="col-md-4 mb-2">
                <label class="form-label">Designation</label>
                <input type="text" name="testimonial_designation" class="form-control"
                    value="<?= htmlspecialchars($testimonial['designation'] ?? '') ?>">
            </div>
            <div class="col-md-12 mb-2">
                <label class="form-label">Message</label>
                <textarea name="testimonial_message" class="form-control" rows="3" placeholder="Client's feedback"><?= htmlspecialchars($testimonial['message'] ?? '') ?></textarea>
            </div>
        </div>
    </div>

                <!-- SEO Section -->
                <div class="col-md-12 mt-4">
                    <h5>SEO Tools</h5>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">SEO Title</label>
                    <input type="text" name="seo_title" class="form-control"
                        value="<?= htmlspecialchars($product['seo_title'] ?? '') ?>">
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Meta Keywords</label>
                    <input type="text" name="meta_keywords" class="form-control" placeholder="keyword1, keyword2"
                        value="<?= htmlspecialchars($product['meta_keywords'] ?? '') ?>">
                </div>

                <div class="col-md-12 mb-3">
                    <label class="form-label">Meta Description</label>
                    <textarea name="meta_description" class="form-control" rows="2"><?= htmlspecialchars($product['meta_description'] ?? '') ?></textarea>
                </div>

                <?php if (isset($_SESSION['admin_role']) && $_SESSION['admin_role'] === 'superadmin'): ?>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Page Options</label><br>
                        <label>
                            <input type="radio" name="create_pages" value="no" <?= ($_SESSION['admin_role'] === 'superadmin') ? '' : 'checked' ?>> Only Save Project
                        </label>
                        <label class="ms-3">
                            <input type="radio" name="create_pages" value="yes" <?= ($_SESSION['admin_role'] === 'superadmin') ? 'checked' : '' ?>> Save Project + Generate Dynamic Pages
                        </label>
                    </div>

                    <!-- Dynamic Page Generator Section -->
                    <div class="mt-5">
                        <h4>Generate Dynamic Pages for this Project</h4>

                        <?php
                        $stmt = $pdo->query("SELECT name FROM secondary_keyword ORDER BY name ASC");
                        $secondary_keyword = $stmt->fetchAll(PDO::FETCH_COLUMN);
                        ?>

                        <div class="section">
                            <label><strong>Primary Keyword (Project Name):</strong></label>
                            <input class="form-control w-auto" type="text"
                                name="primary-keyword"
                                value="<?= htmlspecialchars($product['name'] ?? '') ?>"
                                readonly>
                        </div>

                        <div class="section mt-3">
                            <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 $sub): ?>
                                    <label>
                                        <input type="checkbox" name="secondary_keyword[]" value="<?= $sub ?>"> <?= $sub ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="section mt-3">
                            <strong>Select Location:</strong>
                            <div class="row">
                                <div class="col-md-4">
                                    <label><strong>Countries</strong></label>
                                    <div style="height: 200px; overflow-y: scroll" id="countryContainer"></div>
                                </div>
                                <div class="col-md-4">
                                    <label><strong>States</strong></label>
                                    <div style="height: 200px; overflow-y: scroll" id="stateContainer"></div>
                                </div>
                                <div class="col-md-4">
                                    <label><strong>Cities</strong></label>
                                    <div style="height: 200px; overflow-y: scroll" id="cityContainer"></div>
                                </div>
                            </div>
                            <div id="locationsContainer"></div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="col-12">
                    <button type="submit" class="btn btn-success">Save Project</button>
                    <a href="index.php" class="btn btn-secondary">Cancel</a>
                </div>
            </div>
        </form>

        <?php
        if (!empty($_SESSION['generatedPages'])):
            $generatedPages = $_SESSION['generatedPages'];
            unset($_SESSION['generatedPages']);
        ?>
            <div class="result mt-4">
                <h4>Generated & Stored Project Pages:</h4>
                <ul>
                    <?php foreach ($generatedPages as $page): ?>
                        <li>
                            <a target="_blank" href="/product.php?slug=<?= urlencode($page["slug"]) ?>">
                                <?= htmlspecialchars($page["title"]) ?>
                            </a>
                            — <em><?= $page["slug"] ?></em>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
    </section>
</div>


    <script src="../assets/js/jquery-3.6.3.min.js"></script>
    <script src="../assets/js/bootstrap.bundle.min.js"></script>

    <script>
// ✅ Normalize text for consistent matching
function slugify(text) {
    return text
        .toString()
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .replace(/[^a-zA-Z0-9]+/g, "-")
        .replace(/^-+|-+$/g, "")
        .toLowerCase();
}

let countriesData = [];
const usedLocations = <?= json_encode($usedLocations) ?>.map(l => slugify(l));

fetch("../countries-states-cities.json")
    .then(res => res.json())
    .then(data => {
        countriesData = data;
        populateCountries();
    });

// -----------------------
// Populate Countries
// -----------------------
function populateCountries() {
    const container = document.getElementById("countryContainer");
    container.innerHTML = "";

    const allLabel = document.createElement("label");
    allLabel.innerHTML = `<input type="checkbox" id="allCountries"> <strong>All Countries</strong>`;
    allLabel.style.display = "block";
    container.appendChild(allLabel);

    countriesData.forEach(country => {
        const label = document.createElement("label");
        label.style.display = "block";
        label.innerHTML = `<input type="checkbox" name="countries[]" value="${country.name}"> ${country.name}`;
        if (usedLocations.includes(slugify(country.name))) {
            label.innerHTML += ` <em style="color:red">(Already generated)</em>`;
        }
        container.appendChild(label);
    });

    document.getElementById("allCountries").addEventListener("change", toggleAllCountries);
    container.querySelectorAll("input[name='countries[]']").forEach(cb => {
        cb.addEventListener("change", handleCountryChange);
    });
}

function toggleAllCountries() {
    const allChecked = document.getElementById("allCountries").checked;
    const countryCheckboxes = document.querySelectorAll("input[name='countries[]']");
    const stateContainer = document.getElementById("stateContainer");
    const cityContainer = document.getElementById("cityContainer");

    countryCheckboxes.forEach(cb => {
        cb.checked = false;
        cb.disabled = allChecked;
    });

    if (allChecked) {
        stateContainer.innerHTML = "<em>All States disabled when All Countries selected</em>";
        cityContainer.innerHTML = "<em>All Cities disabled when All Countries selected</em>";
    } else {
        stateContainer.innerHTML = "";
        cityContainer.innerHTML = "";
    }
}

// -----------------------
// Handle Country Change
// -----------------------
function handleCountryChange() {
    const checkedCountries = Array.from(document.querySelectorAll('#countryContainer input[name="countries[]"]:checked')).map(cb => cb.value);
    const stateContainer = document.getElementById("stateContainer");
    const cityContainer = document.getElementById("cityContainer");

    stateContainer.innerHTML = "";
    cityContainer.innerHTML = "";

    if (checkedCountries.length === 1) {
        // SINGLE COUNTRY MODE
        const cn = checkedCountries[0];
        const country = countriesData.find(c => c.name === cn);
        if (!country) return;

        // All States
        const allStatesLabel = document.createElement("label");
        allStatesLabel.style.display = "block";
        allStatesLabel.innerHTML = `<input type="checkbox" id="allStatesForCountry"> <strong>All States of ${cn}</strong>`;
        stateContainer.appendChild(allStatesLabel);

        (country.states || []).forEach(st => {
            const label = document.createElement("label");
            label.style.display = "block";
            label.innerHTML = `<input type="checkbox" name="states[]" value="${st.name}"> ${st.name} (${cn})`;

            // ✅ Show Already Generated for state pages
            if (usedLocations.includes(slugify(st.name)) || usedLocations.includes(slugify(st.name + " " + cn))) {
                label.innerHTML += ` <em style="color:red">(Already generated)</em>`;
            }

            stateContainer.appendChild(label);
        });

        // All Cities
        const allCitiesLabel = document.createElement("label");
        allCitiesLabel.style.display = "block";
        allCitiesLabel.innerHTML = `<input type="checkbox" id="allCitiesForCountry"> <strong>All Cities of ${cn}</strong>`;
        cityContainer.appendChild(allCitiesLabel);

        // When "All Cities" checked → disable all states (toggle on/off properly)
        document.getElementById("allCitiesForCountry").addEventListener("change", function() {
            const isAllCities = this.checked;
            const stateCheckboxes = stateContainer.querySelectorAll("input[name='states[]'], #allStatesForCountry");

            if (isAllCities) {
                // Disable state selection
                stateCheckboxes.forEach(cb => { cb.checked = false; cb.disabled = true; });
                showAllCitiesForCountry(country, cityContainer, cn, true);
            } else {
                // ✅ Re-enable states when unchecked
                stateCheckboxes.forEach(cb => cb.disabled = false);
                cityContainer.innerHTML = `<label><input type="checkbox" id="allCitiesForCountry"> <strong>All Cities of ${cn}</strong></label>`;
                // rebind listener to itself
                document.getElementById("allCitiesForCountry").addEventListener("change", arguments.callee);
            }
        });


        // When "All States" checked → disable cities
        document.getElementById("allStatesForCountry").addEventListener("change", function() {
            const isAllStates = this.checked;
            const stateCheckboxes = stateContainer.querySelectorAll("input[name='states[]']");
            if (isAllStates) {
                stateCheckboxes.forEach(cb => cb.checked = true);
                cityContainer.innerHTML = "<em>All Cities disabled when All States selected</em>";
            } else {
                stateCheckboxes.forEach(cb => cb.checked = false);
                cityContainer.innerHTML = `<label><input type="checkbox" id="allCitiesForCountry"> <strong>All Cities of ${cn}</strong></label>`;
                document.getElementById("allCitiesForCountry").addEventListener("change", handleAllCitiesToggle);
            }
        });

        // Populate city list when state is checked
        stateContainer.querySelectorAll('input[name="states[]"]').forEach(cb => {
            cb.addEventListener("change", function() {
                const selectedStates = Array.from(stateContainer.querySelectorAll('input[name="states[]"]:checked')).map(cb => cb.value);
                populateCitiesForSelectedStates(country, selectedStates);
            });
        });

    } else if (checkedCountries.length > 1) {
        populateStates();
    }
}

// -----------------------
// Populate States for Multi-country
// -----------------------
function populateStates() {
    const stateContainer = document.getElementById("stateContainer");
    const cityContainer = document.getElementById("cityContainer");
    stateContainer.innerHTML = "";
    cityContainer.innerHTML = "";

    const selectedCountries = Array.from(document.querySelectorAll('#countryContainer input[name="countries[]"]:checked')).map(cb => cb.value);
    if (selectedCountries.length === 0) return;

    const allLabel = document.createElement("label");
    allLabel.innerHTML = `<input type="checkbox" id="allStates"> <strong>All States</strong>`;
    allLabel.style.display = "block";
    stateContainer.appendChild(allLabel);

    selectedCountries.forEach(cn => {
        const country = countriesData.find(c => c.name === cn);
        if (country && country.states) {
            country.states.forEach(st => {
                const label = document.createElement("label");
                label.style.display = "block";
                label.innerHTML = `<input type="checkbox" name="states[]" value="${st.name}"> ${st.name} (${cn})`;

                // ✅ State already generated indicator
                if (usedLocations.includes(slugify(st.name)) || usedLocations.includes(slugify(st.name + " " + cn))) {
                    label.innerHTML += ` <em style="color:red">(Already generated)</em>`;
                }

                stateContainer.appendChild(label);
            });
        }
    });

    document.getElementById("allStates").addEventListener("change", toggleAllStates);
    stateContainer.querySelectorAll("input[name='states[]']").forEach(cb => {
        cb.addEventListener("change", populateCities);
    });
}

// -----------------------
// Populate Cities (Multi-country)
// -----------------------
function populateCities() {
    const cityContainer = document.getElementById("cityContainer");
    cityContainer.innerHTML = "";

    const selectedStates = Array.from(document.querySelectorAll('#stateContainer input[name="states[]"]:checked')).map(cb => cb.value);
    if (selectedStates.length === 0) return;

    const allLabel = document.createElement("label");
    allLabel.innerHTML = `<input type="checkbox" id="allCities"> <strong>All Cities</strong>`;
    allLabel.style.display = "block";
    cityContainer.appendChild(allLabel);

    countriesData.forEach(cn => {
        (cn.states || []).forEach(st => {
            if (selectedStates.includes(st.name)) {
                (st.cities || []).forEach(city => {
                    const label = document.createElement("label");
                    label.style.display = "block";
                    label.innerHTML = `<input type="checkbox" name="cities[]" value="${city.name}"> ${city.name} (${st.name})`;

                    // ✅ City "Already generated"
                    if (
                        usedLocations.includes(slugify(city.name)) ||
                        usedLocations.includes(slugify(city.name + " " + st.name))
                    ) {
                        label.innerHTML += ` <em style="color:red">(Already generated)</em>`;
                    }

                    cityContainer.appendChild(label);
                });
            }
        });
    });

    document.getElementById("allCities").addEventListener("change", toggleAllCities);
}

// -----------------------
// Helper: Show all cities for a country (single country mode)
// -----------------------
function showAllCitiesForCountry(country, cityContainer, cn, bindToggle) {
    cityContainer.innerHTML = `<label><input type="checkbox" id="allCitiesForCountry" checked> <strong>All Cities of ${cn}</strong></label>`;
    (country.states || []).forEach(st => {
        (st.cities || []).forEach(city => {
            const label = document.createElement("label");
            label.style.display = "block";
            label.innerHTML = `<input type="checkbox" name="cities[]" value="${city.name}" checked> ${city.name} (${st.name})`;

            // ✅ Show "Already generated" for cities too
            if (
                usedLocations.includes(slugify(city.name)) ||
                usedLocations.includes(slugify(city.name + " " + st.name))
            ) {
                label.innerHTML += ` <em style="color:red">(Already generated)</em>`;
            }

            cityContainer.appendChild(label);
        });
    });

    if (bindToggle) {
        document.getElementById("allCitiesForCountry").addEventListener("change", function() {
            const allChecked = this.checked;
            cityContainer.querySelectorAll("input[name='cities[]']").forEach(cb => cb.checked = allChecked);
        });
    }
}

// -----------------------
// Helper: Populate cities when specific states selected
// -----------------------
function populateCitiesForSelectedStates(country, selectedStates) {
    const cityContainer = document.getElementById("cityContainer");
    cityContainer.innerHTML = "";
    if (!selectedStates.length) return;

    const allLabel = document.createElement("label");
    allLabel.style.display = "block";
    allLabel.innerHTML = `<input type="checkbox" id="allCities"> <strong>All Cities</strong>`;
    cityContainer.appendChild(allLabel);

    (country.states || []).forEach(st => {
        if (selectedStates.includes(st.name)) {
            (st.cities || []).forEach(city => {
                const label = document.createElement("label");
                label.style.display = "block";
                label.innerHTML = `<input type="checkbox" name="cities[]" value="${city.name}"> ${city.name} (${st.name})`;

                // ✅ City already generated
                if (
                    usedLocations.includes(slugify(city.name)) ||
                    usedLocations.includes(slugify(city.name + " " + st.name))
                ) {
                    label.innerHTML += ` <em style="color:red">(Already generated)</em>`;
                }

                cityContainer.appendChild(label);
            });
        }
    });

    document.getElementById("allCities").addEventListener("change", toggleAllCities);
}

// -----------------------
// Generic Toggles
// -----------------------
function toggleAllStates() {
    const allChecked = document.getElementById("allStates").checked;
    const stateCheckboxes = document.querySelectorAll("input[name='states[]']");
    const cityContainer = document.getElementById("cityContainer");
    stateCheckboxes.forEach(cb => {
        cb.checked = false;
        cb.disabled = allChecked;
    });
    cityContainer.innerHTML = allChecked
        ? "<em>All Cities disabled when All States selected</em>"
        : "";
}

function toggleAllCities() {
    const allChecked = this.checked;
    document.querySelectorAll("input[name='cities[]']").forEach(cb => cb.checked = allChecked);
}

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

// -----------------------
// Form Submit
// -----------------------
document.querySelector('form').addEventListener('submit', function(e) {
    const createPages = document.querySelector('input[name="create_pages"]:checked')?.value;

    if (createPages === 'yes') {
        const selectedSecondary = document.querySelectorAll('input[name="secondary_keyword[]"]:checked');
        if (selectedSecondary.length === 0) {
            alert('Please add at least one Secondary Keyword before generating pages.');
            e.preventDefault();
            return;
        }

        const allCountries = document.getElementById("allCountries")?.checked;
        const allStates = document.getElementById("allStates")?.checked;
        const allCitiesGlobal = document.getElementById("allCities")?.checked;              // multi-country "All Cities"
        const allCitiesForCountry = document.getElementById("allCitiesForCountry")?.checked; // single-country "All Cities"

        let locations = [];

        if (allCountries) {
            // all countries
            locations = countriesData.map(c => c.name);
        } else if (allStates) {
            // prefer checked states from DOM; if none, gather all states from selected countries
            const checkedStates = Array.from(document.querySelectorAll('#stateContainer input[name="states[]"]:checked')).map(cb => cb.value);
            if (checkedStates.length) {
                locations.push(...checkedStates);
            } else {
                const selCountries = Array.from(document.querySelectorAll('#countryContainer input[name="countries[]"]:checked')).map(cb => cb.value);
                selCountries.forEach(cn => {
                    const country = countriesData.find(c => c.name === cn);
                    if (country && Array.isArray(country.states)) {
                        locations.push(...country.states.map(s => s.name));
                    }
                });
            }
        } else if (allCitiesGlobal || allCitiesForCountry) {
            // --- PREFERRED: take checked city checkboxes from DOM (this is most robust) ---
            const checkedCitiesFromDOM = Array.from(document.querySelectorAll('#cityContainer input[name="cities[]"]:checked')).map(cb => cb.value);

            if (checkedCitiesFromDOM.length) {
                locations.push(...checkedCitiesFromDOM);
            } else {
                // DOM had no city checkboxes (edge cases); fallback to JSON-based gathering per selected countries
                const selCountries = Array.from(document.querySelectorAll('#countryContainer input[name="countries[]"]:checked')).map(cb => cb.value);
                selCountries.forEach(cn => {
                    const country = countriesData.find(c => c.name === cn);
                    if (!country) return;
                    (country.states || []).forEach(st => {
                        if (Array.isArray(st.cities) && st.cities.length > 0) {
                            st.cities.forEach(ci => {
                                if (ci && ci.name) locations.push(ci.name);
                            });
                        }
                    });
                    // If still nothing for this country, push country name to ensure generation runs
                    // (keeps previous fallback behaviour)
                    if (locations.length === 0 && country.name) {
                        locations.push(country.name);
                    }
                });
            }
        } else {
            // Normal case: gather checked countries, states, cities from DOM
            const countries = Array.from(document.querySelectorAll('#countryContainer input[name="countries[]"]:checked')).map(cb => cb.value);
            const states = Array.from(document.querySelectorAll('#stateContainer input[name="states[]"]:checked')).map(cb => cb.value);
            const cities = Array.from(document.querySelectorAll('#cityContainer input[name="cities[]"]:checked')).map(cb => cb.value);
            locations = [...countries, ...states, ...cities];
        }

        // make unique and filter empty
        const unique = [...new Set(locations.filter(Boolean))];

        
        if (unique.length === 0) {
            alert('Please select at least one Country/State/City or choose All.');
            e.preventDefault();
            return;
        }

        const container = document.getElementById('locationsContainer');
        container.innerHTML = '';
        unique.forEach(loc => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'locations[]';
            input.value = loc;
            container.appendChild(input);
        });
    }
});

// -----------------------
// Loader + Disable Save Button
// -----------------------
const form = document.querySelector('form');
const saveBtn = form.querySelector('button[type="submit"]');

// Create loader element
const loader = document.createElement("span");
loader.className = "spinner-border spinner-border-sm ms-2";
loader.style.display = "none";
saveBtn.appendChild(loader);

form.addEventListener("submit", function() {
    saveBtn.disabled = true;
    loader.style.display = "inline-block";
    saveBtn.textContent = "Saving...";
    saveBtn.appendChild(loader);
});


</script>



<script>
document.querySelector('input[name="product_image"]').addEventListener('change', function(e) {
    const previewContainer = document.getElementById('imagePreview');
    previewContainer.innerHTML = "";
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(evt) {
            const img = document.createElement('img');
            img.src = evt.target.result;
            img.width = 120;
            img.classList.add('rounded', 'shadow');
            previewContainer.appendChild(img);
        };
        reader.readAsDataURL(file);
    }
});

// Delete image (AJAX)
document.querySelectorAll('.delete-image').forEach(btn => {
    btn.addEventListener('click', function() {
        if (confirm('Remove this image?')) {
            const img = this.getAttribute('data-img');
            fetch('product-image-delete.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'img=' + encodeURIComponent(img) + '&product_id=<?= $product['id'] ?? 0 ?>'
            }).then(() => location.reload());
        }
    });
});
</script>



</body>

</html>