<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];
$success = $_SESSION['success_msg'] ?? '';
$error = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg'], $_SESSION['error_msg']);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // DELETE LINK
    if (isset($_POST['delete_domain_id'])) {
        $del_id = $_POST['delete_domain_id'];
        $pdo->prepare("DELETE FROM user_domains WHERE id = ? AND user_id = ?")->execute([$del_id, $user_id]);
        $_SESSION['success_msg'] = "Landing page link removed.";

    // DELETE CUSTOM ROOT DOMAIN
    } elseif (isset($_POST['delete_root_id'])) {
        $del_root_id = (int)$_POST['delete_root_id'];
        // Ensure it belongs to the user
        $pdo->prepare("DELETE FROM system_root_domains WHERE id = ? AND user_id = ?")->execute([$del_root_id, $user_id]);
        $_SESSION['success_msg'] = "Custom root domain removed.";

    // ADD CUSTOM ROOT DOMAIN
    } elseif (isset($_POST['add_custom_root'])) {
        $new_root = trim(strtolower($_POST['custom_root_domain'] ?? ''));
        $new_root = preg_replace('/^https?:\/\//', '', $new_root);
        $new_root = rtrim($new_root, '/');
        
        if (empty($new_root) || !preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $new_root)) {
            $_SESSION['error_msg'] = "Invalid domain format. Use e.g. 'mydomain.com'";
        } else {
            try {
                // If admin and requested system root, set user_id to NULL
                $is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
                $target_user_id = ($is_admin && isset($_POST['is_system_root'])) ? null : $user_id;
                
                $stmt = $pdo->prepare("INSERT INTO system_root_domains (domain_name, user_id, is_active) VALUES (?, ?, 1)");
                $stmt->execute([$new_root, $target_user_id]);
                $_SESSION['success_msg'] = "Custom root domain added! Now point your DNS to our server.";
            } catch (PDOException $e) {
                $_SESSION['error_msg'] = "Domain already exists or database error.";
            }
        }

    // EDIT
    } elseif (isset($_POST['edit_domain_id'])) {
        $edit_id = (int)$_POST['edit_domain_id'];
        $slug = trim(preg_replace('/[^a-z0-9_-]/i', '', strtolower($_POST['subdomain'] ?? '')));
        $root_id = (int)($_POST['root_id'] ?? 0);

        if (empty($slug)) {
            $_SESSION['error_msg'] = "Slug cannot be empty.";
        } else {
            if ($root_id > 0) {
                $stmt = $pdo->prepare("SELECT domain_name FROM system_root_domains WHERE id = ? AND is_active = 1");
                $stmt->execute([$root_id]);
                $root_domain = $stmt->fetchColumn();
                if ($root_domain) {
                    // Check if it's a subdomain root or a path root
                    // We distinguish by checking if there's a user_id on the root
                    $stmt_type = $pdo->prepare("SELECT user_id FROM system_root_domains WHERE id = ?");
                    $stmt_type->execute([$root_id]);
                    $is_personal_root = $stmt_type->fetchColumn() !== null;
                    
                    if ($is_personal_root) {
                        $domain_name = $root_domain . '/' . $slug;
                    } else {
                        $domain_name = $slug . '.' . $root_domain;
                    }
                } else {
                    $_SESSION['error_msg'] = "Selected root domain is invalid.";
                    header("Location: domains"); exit;
                }
            } else {
                $domain_name = $slug;
            }

            if (!preg_match('/^[a-z0-9._\-\/]+$/i', $domain_name)) {
                $_SESSION['error_msg'] = "Invalid link format.";
            } else {
                // Check duplicate (exclude own record)
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM user_domains WHERE domain_name = ? AND id != ?");
                $stmt->execute([$domain_name, $edit_id]);
                if ($stmt->fetchColumn() > 0) {
                    $_SESSION['error_msg'] = "This link identifier is already taken.";
                } else {
                    try {
                        $stmt = $pdo->prepare("UPDATE user_domains SET domain_name = ? WHERE id = ? AND user_id = ?");
                        if ($stmt->execute([$domain_name, $edit_id, $user_id])) {
                            $_SESSION['success_msg'] = "Landing page link updated!";
                        }
                    } catch(PDOException $e) { $_SESSION['error_msg'] = "Database error occurred."; }
                }
            }
        }

    // ADD NEW
    } else {
        $slug = '';
        if (!empty($_POST['subdomain'])) {
            $slug = trim(preg_replace('/[^a-z0-9_-]/i', '', strtolower($_POST['subdomain'])));
        }

        if (empty($slug)) {
            $slug = 'link-' . substr(bin2hex(random_bytes(4)), 0, 6);
        }

        $root_id = (int)($_POST['root_id'] ?? 0);
        
        if ($root_id > 0) {
            $stmt = $pdo->prepare("SELECT domain_name FROM system_root_domains WHERE id = ? AND is_active = 1");
            $stmt->execute([$root_id]);
            $root_domain = $stmt->fetchColumn();
            if ($root_domain) {
                // Check if it's a subdomain root or a path root
                $stmt_type = $pdo->prepare("SELECT user_id FROM system_root_domains WHERE id = ?");
                $stmt_type->execute([$root_id]);
                $is_personal_root = $stmt_type->fetchColumn() !== null;
                
                if ($is_personal_root) {
                    $domain_name = $root_domain . '/' . $slug;
                } else {
                    $domain_name = $slug . '.' . $root_domain;
                }
            } else {
                $_SESSION['error_msg'] = "Selected root domain is invalid.";
                header("Location: domains");
                exit;
            }
        } else {
            $domain_name = $slug;
        }

        if (!preg_match('/^[a-z0-9._\-\/]+$/i', $domain_name)) {
            $_SESSION['error_msg'] = "Invalid link format.";
        } else {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM user_domains WHERE domain_name = ?");
            $stmt->execute([$domain_name]);
            if ($stmt->fetchColumn() > 0) {
                $_SESSION['error_msg'] = "This link identifier is already taken.";
            } else {
                try {
                    $stmt = $pdo->prepare("INSERT INTO user_domains (user_id, domain_name, status) VALUES (?, ?, 'active')");
                    if ($stmt->execute([$user_id, $domain_name])) {
                        $_SESSION['success_msg'] = "Landing page link created!";
                    }
                } catch(PDOException $e) { $_SESSION['error_msg'] = "Database error occurred."; }
            }
        }
    }
    header("Location: domains");
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT * FROM user_domains WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    $domains = $stmt->fetchAll();
} catch (PDOException $e) { $domains = []; }

// Fetch active root domains (System Roots + User's Personal Roots + Admin Global Roots)
try {
    $root_domains = $pdo->prepare("
        SELECT rd.*, u.role as owner_role 
        FROM system_root_domains rd
        LEFT JOIN users u ON rd.user_id = u.id
        WHERE rd.is_active = 1 AND (rd.user_id IS NULL OR rd.user_id = ? OR u.role = 'admin') 
        ORDER BY rd.domain_name ASC
    ");
    $root_domains->execute([$user_id]);
    $root_domains = $root_domains->fetchAll();
} catch (PDOException $e) { $root_domains = []; }

$current_server = preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']);
$verified_domains = array_filter($domains, function($d) { return in_array(strtolower($d['status']), ['verified', 'active']); });
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Landing Pages - SonicPesa</title>
    <?php include 'includes/head.php'; ?>
    <style>
        .toast-container { z-index: 2000; }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">

            <?php if($error || $success): ?>
            <div class="toast-container position-fixed bottom-0 end-0 p-3">
                <div id="liveToast" class="toast align-items-center border-0 <?= $success ? 'bg-success-focus' : 'bg-danger-focus' ?>" role="alert" aria-live="assertive" aria-atomic="true" style="width: 320px; box-shadow: 0 10px 30px rgba(0,0,0,0.1);">
                    <div class="toast-header border-0 pb-2 pt-3 px-3 d-flex justify-content-between align-items-center" style="background: transparent;">
                        <strong class="me-auto fw-bold text-dark"><?= $success ? 'Success' : 'Error' ?></strong>
                        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                    <div class="toast-body text-white <?= $success ? 'bg-success' : 'bg-danger' ?> rounded-bottom p-3">
                        <?= htmlspecialchars($success ?: $error) ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="card basic-data-table">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h5 class="card-title mb-0">Landing Page Links</h5>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#manageRootsModal">
                            <iconify-icon icon="solar:globus-bold-duotone" class="me-1"></iconify-icon> My Custom Domains
                        </button>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDomainModal">
                            + Create Landing Page Link
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <table class="table bordered-table mb-0" id="dataTable" data-page-length='10'>
                        <thead>
                            <tr>
                                <th scope="col">Store Link</th>
                                <th scope="col">Added Date</th>
                                <th scope="col">Status</th>
                                <th scope="col">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($domains)): ?>
                                <?php foreach($domains as $d): ?>
                                <?php 
                                    $is_subdomain = strpos($d['domain_name'], '.') !== false;
                                    $full_url = $is_subdomain ? "https://" . $d['domain_name'] : SITE_URL . "/" . $d['domain_name'];
                                    // Determine current slug and root_id for edit pre-fill
                                    $edit_root_id = 0;
                                    $edit_slug = $d['domain_name'];
                                    if ($is_subdomain) {
                                        $dot_pos = strpos($d['domain_name'], '.');
                                        $edit_slug = substr($d['domain_name'], 0, $dot_pos);
                                        $edit_root_name = substr($d['domain_name'], $dot_pos + 1);
                                        foreach ($root_domains as $rd) {
                                            if ($rd['domain_name'] === $edit_root_name) {
                                                $edit_root_id = $rd['id'];
                                                break;
                                            }
                                        }
                                    }
                                ?>
                                <tr>
                                    <td>
                                        <a href="<?= $full_url ?>" target="_blank" class="text-primary-600 fw-bold">
                                            <?= str_replace(['https://','http://'], '', $full_url) ?> <i class="fas fa-external-link-alt ms-1 text-sm"></i>
                                        </a>
                                    </td>
                                    <td><?= date('d M, Y', strtotime($d['created_at'])) ?></td>
                                    <td>
                                        <span class="<?= in_array(strtolower($d['status']), ['verified', 'active']) ? 'bg-success-focus text-success-main' : 'bg-warning-focus text-warning-main' ?> px-16 py-4 rounded-pill fw-medium text-sm">
                                            <?= $d['status'] ? ucfirst($d['status']) : 'Pending' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a href="<?= SITE_URL ?>/analytics?id=<?= $d['id'] ?>" class="w-32-px h-32-px bg-primary-focus text-primary-main rounded-circle d-inline-flex align-items-center justify-content-center me-8" title="View Analytics">
                                            <iconify-icon icon="solar:chart-bold-duotone"></iconify-icon>
                                        </a>
                                        <!-- Edit Button -->
                                        <button type="button"
                                            class="w-32-px h-32-px bg-info-focus text-info-main rounded-circle d-inline-flex align-items-center justify-content-center me-8"
                                            title="Edit Link"
                                            onclick="openEditModal(<?= $d['id'] ?>, '<?= htmlspecialchars($edit_slug, ENT_QUOTES) ?>', <?= $edit_root_id ?>)">
                                            <iconify-icon icon="material-symbols:edit-outline"></iconify-icon>
                                        </button>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this domain?');">
                                            <input type="hidden" name="delete_domain_id" value="<?= $d['id'] ?>">
                                            <button type="submit" class="w-32-px h-32-px bg-danger-focus text-danger-main rounded-circle d-inline-flex align-items-center justify-content-center" title="Delete Domain">
                                                <iconify-icon icon="mingcute:delete-2-line"></iconify-icon>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center py-4">No domains added yet.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Add Domain Modal -->
        <div class="modal fade" id="addDomainModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Create Landing Page Link</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form action="domains" method="POST">
                        <div class="modal-body">
                            <div class="mb-24">
                                <label class="form-label fw-bold">Step 1: Choose Domain / Link Type</label>
                                <select name="root_id" id="domainTypeSelector" class="form-select mb-12">
                                    <option value="0" data-type="path">Standard Path (<?= str_replace(['https://','http://'], '', SITE_URL) ?>/...)</option>
                                    <optgroup label="System Roots (Subdomains)">
                                        <?php foreach ($root_domains as $rd): if($rd['user_id']) continue; ?>
                                            <option value="<?= $rd['id'] ?>" data-type="subdomain">Subdomain (...<?= htmlspecialchars($rd['domain_name']) ?>)</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php 
                                    $has_personal = false;
                                    foreach($root_domains as $rd) if($rd['user_id'] == $user_id) { $has_personal = true; break; }
                                    if($has_personal): ?>
                                    <optgroup label="My Custom Domains (Path Based)">
                                        <?php foreach ($root_domains as $rd): if($rd['user_id'] != $user_id) continue; ?>
                                            <option value="<?= $rd['id'] ?>" data-type="personal"><?= htmlspecialchars($rd['domain_name']) ?>/...</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>

                                    <?php 
                                    $has_admin_global = false;
                                    foreach($root_domains as $rd) if($rd['user_id'] && $rd['user_id'] != $user_id && $rd['owner_role'] == 'admin') { $has_admin_global = true; break; }
                                    if($has_admin_global): ?>
                                    <optgroup label="Global Domains (Path Based)">
                                        <?php foreach ($root_domains as $rd): if(!$rd['user_id'] || $rd['user_id'] == $user_id || $rd['owner_role'] != 'admin') continue; ?>
                                            <option value="<?= $rd['id'] ?>" data-type="personal"><?= htmlspecialchars($rd['domain_name']) ?>/...</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>
                                </select>
                            </div>

                            <div class="mb-24">
                                <label class="form-label fw-bold">Step 2: Enter Custom Slug / Name</label>
                                <div class="input-group">
                                    <span class="input-group-text d-none" id="prefixText">sub.</span>
                                    <input type="text" name="subdomain" class="form-control" placeholder="my-store"
                                        value="<?= htmlspecialchars($_SESSION['user_name'] ?? '') ?>" id="slugInput">
                                    <span class="input-group-text" id="suffixText">/<?= str_replace(['https://','http://'], '', SITE_URL) ?></span>
                                </div>
                                <div class="mt-8 text-secondary text-sm" id="previewUrl">Preview: <?= SITE_URL ?>/<?= htmlspecialchars($_SESSION['user_name'] ?? 'my-store') ?></div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary w-100">Create Landing Link</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Edit Domain Modal -->
        <div class="modal fade" id="editDomainModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Edit Landing Page Link</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form action="domains" method="POST">
                        <input type="hidden" name="edit_domain_id" id="editDomainId">
                        <div class="modal-body">
                            <div class="mb-24">
                                <label class="form-label fw-bold">Link Type</label>
                                <select name="root_id" id="editDomainTypeSelector" class="form-select mb-12">
                                    <option value="0" data-type="path">Standard Path (<?= str_replace(['https://','http://'], '', SITE_URL) ?>/...)</option>
                                    <optgroup label="System Roots">
                                        <?php foreach ($root_domains as $rd): if($rd['user_id']) continue; ?>
                                            <option value="<?= $rd['id'] ?>" data-type="subdomain">Subdomain (...<?= htmlspecialchars($rd['domain_name']) ?>)</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php if($has_personal): ?>
                                    <optgroup label="My Custom Domains">
                                        <?php foreach ($root_domains as $rd): if($rd['user_id'] != $user_id) continue; ?>
                                            <option value="<?= $rd['id'] ?>" data-type="personal"><?= htmlspecialchars($rd['domain_name']) ?>/...</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>
                                    <?php if($has_admin_global): ?>
                                    <optgroup label="Global Domains">
                                        <?php foreach ($root_domains as $rd): if(!$rd['user_id'] || $rd['user_id'] == $user_id || $rd['owner_role'] != 'admin') continue; ?>
                                            <option value="<?= $rd['id'] ?>" data-type="personal"><?= htmlspecialchars($rd['domain_name']) ?>/...</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="mb-24">
                                <label class="form-label fw-bold">Slug / Name</label>
                                <div class="input-group">
                                    <span class="input-group-text d-none" id="editPrefixText">sub.</span>
                                    <input type="text" name="subdomain" class="form-control" id="editSlugInput" placeholder="my-store">
                                    <span class="input-group-text" id="editSuffixText">/<?= str_replace(['https://','http://'], '', SITE_URL) ?></span>
                                </div>
                                <div class="mt-8 text-secondary text-sm" id="editPreviewUrl">Preview: </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Manage Roots Modal -->
        <div class="modal fade" id="manageRootsModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">My Custom Domains</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form method="POST" class="mb-24 p-16 bg-base radius-8 border">
                            <label class="form-label fw-bold">Add New Custom Domain</label>
                            <div class="d-flex gap-8">
                                <input type="text" name="custom_root_domain" class="form-control" placeholder="e.g. my-cool-website.com">
                                <button type="submit" name="add_custom_root" class="btn btn-primary text-nowrap">Add Domain</button>
                            </div>
                            <?php if(isset($_SESSION['role']) && $_SESSION['role'] === 'admin'): ?>
                            <div class="form-check mt-12">
                                <input class="form-check-input" type="checkbox" name="is_system_root" id="isSystemRoot">
                                <label class="form-check-label fw-bold text-sm" for="isSystemRoot">
                                    Make as System Root (Enable Subdomains for all users)
                                </label>
                            </div>
                            <?php endif; ?>
                            <p class="text-xs text-secondary mt-8 mb-0"><i class="fas fa-info-circle"></i> Point your domain's <strong>A Record</strong> to our server IP first.</p>
                        </form>

                        <div class="table-responsive">
                            <table class="table bordered-table mb-0">
                                <thead>
                                    <tr>
                                        <th>Domain Name</th>
                                        <th>Added</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $personal_roots = array_filter($root_domains, function($r) { return $r['user_id'] != null; });
                                    if(!empty($personal_roots)): 
                                        foreach($personal_roots as $pr):
                                    ?>
                                    <tr>
                                        <td class="fw-bold"><?= htmlspecialchars($pr['domain_name']) ?></td>
                                        <td><?= date('d M, Y', strtotime($pr['created_at'])) ?></td>
                                        <td>
                                            <form method="POST" onsubmit="return confirm('Delete this custom domain? All links on it will break.');">
                                                <input type="hidden" name="delete_root_id" value="<?= $pr['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">Remove</button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="3" class="text-center py-4 text-secondary">No custom domains added yet.</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>
    <script>
        const siteUrl = "<?= str_replace(['https://','http://'], '', SITE_URL) ?>";

        document.addEventListener('DOMContentLoaded', function() {
            const toastEl = document.getElementById('liveToast');
            if (toastEl) {
                const toast = bootstrap.Toast.getOrCreateInstance(toastEl, { delay: 4000 });
                toast.show();
            }

            // ---- ADD Modal Preview ----
            const typeSelector = document.getElementById('domainTypeSelector');
            const slugInput = document.getElementById('slugInput');
            const suffixText = document.getElementById('suffixText');
            const prefixText = document.getElementById('prefixText');
            const previewUrl = document.getElementById('previewUrl');

            function updatePreview() {
                const opt = typeSelector.options[typeSelector.selectedIndex];
                const type = opt.getAttribute('data-type');
                const slug = slugInput.value || 'my-store';
                
                if (type === "path") {
                    suffixText.textContent = "";
                    suffixText.classList.add('d-none');
                    prefixText.textContent = siteUrl + "/";
                    prefixText.classList.remove('d-none');
                    previewUrl.textContent = "Preview: https://" + siteUrl + "/" + slug;
                } else if (type === "subdomain") {
                    const domain = opt.text.match(/\((.*?)\)/)[1];
                    suffixText.textContent = domain;
                    suffixText.classList.remove('d-none');
                    prefixText.textContent = "";
                    prefixText.classList.add('d-none');
                    previewUrl.textContent = "Preview: https://" + slug + domain;
                } else if (type === "personal") {
                    const domain = opt.text.replace('/...', '');
                    suffixText.textContent = "";
                    suffixText.classList.add('d-none');
                    prefixText.textContent = domain + "/";
                    prefixText.classList.remove('d-none');
                    previewUrl.textContent = "Preview: https://" + domain + "/" + slug;
                }
            }

            if (typeSelector && slugInput) {
                typeSelector.addEventListener('change', updatePreview);
                slugInput.addEventListener('input', updatePreview);
                updatePreview();
            }

            // ---- EDIT Modal Preview ----
            const editTypeSelector = document.getElementById('editDomainTypeSelector');
            const editSlugInput = document.getElementById('editSlugInput');
            const editSuffixText = document.getElementById('editSuffixText');
            const editPrefixText = document.getElementById('editPrefixText');
            const editPreviewUrl = document.getElementById('editPreviewUrl');

            function updateEditPreview() {
                const opt = editTypeSelector.options[editTypeSelector.selectedIndex];
                const type = opt ? opt.getAttribute('data-type') : 'path';
                const slug = editSlugInput.value || 'my-store';

                if (type === "path") {
                    editSuffixText.textContent = "";
                    editSuffixText.classList.add('d-none');
                    editPrefixText.textContent = siteUrl + "/";
                    editPrefixText.classList.remove('d-none');
                    editPreviewUrl.textContent = "Preview: https://" + siteUrl + "/" + slug;
                } else if (type === "subdomain") {
                    const domain = opt.text.match(/\((.*?)\)/)[1];
                    editSuffixText.textContent = domain;
                    editSuffixText.classList.remove('d-none');
                    editPrefixText.textContent = "";
                    editPrefixText.classList.add('d-none');
                    editPreviewUrl.textContent = "Preview: https://" + slug + domain;
                } else if (type === "personal") {
                    const domain = opt.text.replace('/...', '');
                    editSuffixText.textContent = "";
                    editSuffixText.classList.add('d-none');
                    editPrefixText.textContent = domain + "/";
                    editPrefixText.classList.remove('d-none');
                    editPreviewUrl.textContent = "Preview: https://" + domain + "/" + slug;
                }
            }

            editTypeSelector.addEventListener('change', updateEditPreview);
            editSlugInput.addEventListener('input', updateEditPreview);
        });

        function openEditModal(id, slug, rootId) {
            document.getElementById('editDomainId').value = id;
            document.getElementById('editSlugInput').value = slug;
            document.getElementById('editDomainTypeSelector').value = rootId;

            // Trigger preview update
            document.getElementById('editDomainTypeSelector').dispatchEvent(new Event('change'));

            const modal = new bootstrap.Modal(document.getElementById('editDomainModal'));
            modal.show();
        }
    </script>
</body>
</html>


